babylon.max.js 2.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. // Operators
  62. Color3.prototype.toArray = function (array, index) {
  63. if (index === undefined) {
  64. index = 0;
  65. }
  66. array[index] = this.r;
  67. array[index + 1] = this.g;
  68. array[index + 2] = this.b;
  69. return this;
  70. };
  71. Color3.prototype.toColor4 = function (alpha) {
  72. if (alpha === void 0) { alpha = 1; }
  73. return new Color4(this.r, this.g, this.b, alpha);
  74. };
  75. Color3.prototype.asArray = function () {
  76. var result = [];
  77. this.toArray(result, 0);
  78. return result;
  79. };
  80. Color3.prototype.toLuminance = function () {
  81. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  82. };
  83. Color3.prototype.multiply = function (otherColor) {
  84. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  85. };
  86. Color3.prototype.multiplyToRef = function (otherColor, result) {
  87. result.r = this.r * otherColor.r;
  88. result.g = this.g * otherColor.g;
  89. result.b = this.b * otherColor.b;
  90. return this;
  91. };
  92. Color3.prototype.equals = function (otherColor) {
  93. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  94. };
  95. Color3.prototype.equalsFloats = function (r, g, b) {
  96. return this.r === r && this.g === g && this.b === b;
  97. };
  98. Color3.prototype.scale = function (scale) {
  99. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  100. };
  101. Color3.prototype.scaleToRef = function (scale, result) {
  102. result.r = this.r * scale;
  103. result.g = this.g * scale;
  104. result.b = this.b * scale;
  105. return this;
  106. };
  107. Color3.prototype.add = function (otherColor) {
  108. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  109. };
  110. Color3.prototype.addToRef = function (otherColor, result) {
  111. result.r = this.r + otherColor.r;
  112. result.g = this.g + otherColor.g;
  113. result.b = this.b + otherColor.b;
  114. return this;
  115. };
  116. Color3.prototype.subtract = function (otherColor) {
  117. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  118. };
  119. Color3.prototype.subtractToRef = function (otherColor, result) {
  120. result.r = this.r - otherColor.r;
  121. result.g = this.g - otherColor.g;
  122. result.b = this.b - otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.clone = function () {
  126. return new Color3(this.r, this.g, this.b);
  127. };
  128. Color3.prototype.copyFrom = function (source) {
  129. this.r = source.r;
  130. this.g = source.g;
  131. this.b = source.b;
  132. return this;
  133. };
  134. Color3.prototype.copyFromFloats = function (r, g, b) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. return this;
  139. };
  140. Color3.prototype.toHexString = function () {
  141. var intR = (this.r * 255) | 0;
  142. var intG = (this.g * 255) | 0;
  143. var intB = (this.b * 255) | 0;
  144. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  145. };
  146. Color3.prototype.toLinearSpace = function () {
  147. var convertedColor = new Color3();
  148. this.toLinearSpaceToRef(convertedColor);
  149. return convertedColor;
  150. };
  151. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  152. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  153. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  154. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  155. return this;
  156. };
  157. Color3.prototype.toGammaSpace = function () {
  158. var convertedColor = new Color3();
  159. this.toGammaSpaceToRef(convertedColor);
  160. return convertedColor;
  161. };
  162. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  163. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  164. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  165. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  166. return this;
  167. };
  168. // Statics
  169. Color3.FromHexString = function (hex) {
  170. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  171. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  172. return new Color3(0, 0, 0);
  173. }
  174. var r = parseInt(hex.substring(1, 3), 16);
  175. var g = parseInt(hex.substring(3, 5), 16);
  176. var b = parseInt(hex.substring(5, 7), 16);
  177. return Color3.FromInts(r, g, b);
  178. };
  179. Color3.FromArray = function (array, offset) {
  180. if (offset === void 0) { offset = 0; }
  181. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  182. };
  183. Color3.FromInts = function (r, g, b) {
  184. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  185. };
  186. Color3.Lerp = function (start, end, amount) {
  187. var r = start.r + ((end.r - start.r) * amount);
  188. var g = start.g + ((end.g - start.g) * amount);
  189. var b = start.b + ((end.b - start.b) * amount);
  190. return new Color3(r, g, b);
  191. };
  192. Color3.Red = function () { return new Color3(1, 0, 0); };
  193. Color3.Green = function () { return new Color3(0, 1, 0); };
  194. Color3.Blue = function () { return new Color3(0, 0, 1); };
  195. Color3.Black = function () { return new Color3(0, 0, 0); };
  196. Color3.White = function () { return new Color3(1, 1, 1); };
  197. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  198. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  199. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  200. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  201. return Color3;
  202. })();
  203. BABYLON.Color3 = Color3;
  204. var Color4 = (function () {
  205. function Color4(r, g, b, a) {
  206. this.r = r;
  207. this.g = g;
  208. this.b = b;
  209. this.a = a;
  210. }
  211. // Operators
  212. Color4.prototype.addInPlace = function (right) {
  213. this.r += right.r;
  214. this.g += right.g;
  215. this.b += right.b;
  216. this.a += right.a;
  217. return this;
  218. };
  219. Color4.prototype.asArray = function () {
  220. var result = [];
  221. this.toArray(result, 0);
  222. return result;
  223. };
  224. Color4.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.r;
  229. array[index + 1] = this.g;
  230. array[index + 2] = this.b;
  231. array[index + 3] = this.a;
  232. return this;
  233. };
  234. Color4.prototype.add = function (right) {
  235. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  236. };
  237. Color4.prototype.subtract = function (right) {
  238. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  239. };
  240. Color4.prototype.subtractToRef = function (right, result) {
  241. result.r = this.r - right.r;
  242. result.g = this.g - right.g;
  243. result.b = this.b - right.b;
  244. result.a = this.a - right.a;
  245. return this;
  246. };
  247. Color4.prototype.scale = function (scale) {
  248. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  249. };
  250. Color4.prototype.scaleToRef = function (scale, result) {
  251. result.r = this.r * scale;
  252. result.g = this.g * scale;
  253. result.b = this.b * scale;
  254. result.a = this.a * scale;
  255. return this;
  256. };
  257. Color4.prototype.toString = function () {
  258. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  259. };
  260. Color4.prototype.clone = function () {
  261. return new Color4(this.r, this.g, this.b, this.a);
  262. };
  263. Color4.prototype.copyFrom = function (source) {
  264. this.r = source.r;
  265. this.g = source.g;
  266. this.b = source.b;
  267. this.a = source.a;
  268. return this;
  269. };
  270. Color4.prototype.toHexString = function () {
  271. var intR = (this.r * 255) | 0;
  272. var intG = (this.g * 255) | 0;
  273. var intB = (this.b * 255) | 0;
  274. var intA = (this.a * 255) | 0;
  275. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  276. };
  277. // Statics
  278. Color4.FromHexString = function (hex) {
  279. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  280. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  281. return new Color4(0, 0, 0, 0);
  282. }
  283. var r = parseInt(hex.substring(1, 3), 16);
  284. var g = parseInt(hex.substring(3, 5), 16);
  285. var b = parseInt(hex.substring(5, 7), 16);
  286. var a = parseInt(hex.substring(7, 9), 16);
  287. return Color4.FromInts(r, g, b, a);
  288. };
  289. Color4.Lerp = function (left, right, amount) {
  290. var result = new Color4(0, 0, 0, 0);
  291. Color4.LerpToRef(left, right, amount, result);
  292. return result;
  293. };
  294. Color4.LerpToRef = function (left, right, amount, result) {
  295. result.r = left.r + (right.r - left.r) * amount;
  296. result.g = left.g + (right.g - left.g) * amount;
  297. result.b = left.b + (right.b - left.b) * amount;
  298. result.a = left.a + (right.a - left.a) * amount;
  299. };
  300. Color4.FromArray = function (array, offset) {
  301. if (offset === void 0) { offset = 0; }
  302. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  303. };
  304. Color4.FromInts = function (r, g, b, a) {
  305. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  306. };
  307. Color4.CheckColors4 = function (colors, count) {
  308. // Check if color3 was used
  309. if (colors.length === count * 3) {
  310. var colors4 = [];
  311. for (var index = 0; index < colors.length; index += 3) {
  312. var newIndex = (index / 3) * 4;
  313. colors4[newIndex] = colors[index];
  314. colors4[newIndex + 1] = colors[index + 1];
  315. colors4[newIndex + 2] = colors[index + 2];
  316. colors4[newIndex + 3] = 1.0;
  317. }
  318. return colors4;
  319. }
  320. return colors;
  321. };
  322. return Color4;
  323. })();
  324. BABYLON.Color4 = Color4;
  325. var Vector2 = (function () {
  326. function Vector2(x, y) {
  327. this.x = x;
  328. this.y = y;
  329. }
  330. Vector2.prototype.toString = function () {
  331. return "{X: " + this.x + " Y:" + this.y + "}";
  332. };
  333. // Operators
  334. Vector2.prototype.toArray = function (array, index) {
  335. if (index === void 0) { index = 0; }
  336. array[index] = this.x;
  337. array[index + 1] = this.y;
  338. return this;
  339. };
  340. Vector2.prototype.asArray = function () {
  341. var result = [];
  342. this.toArray(result, 0);
  343. return result;
  344. };
  345. Vector2.prototype.copyFrom = function (source) {
  346. this.x = source.x;
  347. this.y = source.y;
  348. return this;
  349. };
  350. Vector2.prototype.copyFromFloats = function (x, y) {
  351. this.x = x;
  352. this.y = y;
  353. return this;
  354. };
  355. Vector2.prototype.add = function (otherVector) {
  356. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  357. };
  358. Vector2.prototype.addVector3 = function (otherVector) {
  359. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  360. };
  361. Vector2.prototype.subtract = function (otherVector) {
  362. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  363. };
  364. Vector2.prototype.subtractInPlace = function (otherVector) {
  365. this.x -= otherVector.x;
  366. this.y -= otherVector.y;
  367. return this;
  368. };
  369. Vector2.prototype.multiplyInPlace = function (otherVector) {
  370. this.x *= otherVector.x;
  371. this.y *= otherVector.y;
  372. return this;
  373. };
  374. Vector2.prototype.multiply = function (otherVector) {
  375. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  376. };
  377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  378. result.x = this.x * otherVector.x;
  379. result.y = this.y * otherVector.y;
  380. return this;
  381. };
  382. Vector2.prototype.multiplyByFloats = function (x, y) {
  383. return new Vector2(this.x * x, this.y * y);
  384. };
  385. Vector2.prototype.divide = function (otherVector) {
  386. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  387. };
  388. Vector2.prototype.divideToRef = function (otherVector, result) {
  389. result.x = this.x / otherVector.x;
  390. result.y = this.y / otherVector.y;
  391. return this;
  392. };
  393. Vector2.prototype.negate = function () {
  394. return new Vector2(-this.x, -this.y);
  395. };
  396. Vector2.prototype.scaleInPlace = function (scale) {
  397. this.x *= scale;
  398. this.y *= scale;
  399. return this;
  400. };
  401. Vector2.prototype.scale = function (scale) {
  402. return new Vector2(this.x * scale, this.y * scale);
  403. };
  404. Vector2.prototype.equals = function (otherVector) {
  405. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  406. };
  407. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  408. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  409. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  410. };
  411. // Properties
  412. Vector2.prototype.length = function () {
  413. return Math.sqrt(this.x * this.x + this.y * this.y);
  414. };
  415. Vector2.prototype.lengthSquared = function () {
  416. return (this.x * this.x + this.y * this.y);
  417. };
  418. // Methods
  419. Vector2.prototype.normalize = function () {
  420. var len = this.length();
  421. if (len === 0)
  422. return this;
  423. var num = 1.0 / len;
  424. this.x *= num;
  425. this.y *= num;
  426. return this;
  427. };
  428. Vector2.prototype.clone = function () {
  429. return new Vector2(this.x, this.y);
  430. };
  431. // Statics
  432. Vector2.Zero = function () {
  433. return new Vector2(0, 0);
  434. };
  435. Vector2.FromArray = function (array, offset) {
  436. if (offset === void 0) { offset = 0; }
  437. return new Vector2(array[offset], array[offset + 1]);
  438. };
  439. Vector2.FromArrayToRef = function (array, offset, result) {
  440. result.x = array[offset];
  441. result.y = array[offset + 1];
  442. };
  443. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  444. var squared = amount * amount;
  445. var cubed = amount * squared;
  446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Clamp = function (value, min, max) {
  455. var x = value.x;
  456. x = (x > max.x) ? max.x : x;
  457. x = (x < min.x) ? min.x : x;
  458. var y = value.y;
  459. y = (y > max.y) ? max.y : y;
  460. y = (y < min.y) ? min.y : y;
  461. return new Vector2(x, y);
  462. };
  463. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  464. var squared = amount * amount;
  465. var cubed = amount * squared;
  466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  468. var part3 = (cubed - (2.0 * squared)) + amount;
  469. var part4 = cubed - squared;
  470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  472. return new Vector2(x, y);
  473. };
  474. Vector2.Lerp = function (start, end, amount) {
  475. var x = start.x + ((end.x - start.x) * amount);
  476. var y = start.y + ((end.y - start.y) * amount);
  477. return new Vector2(x, y);
  478. };
  479. Vector2.Dot = function (left, right) {
  480. return left.x * right.x + left.y * right.y;
  481. };
  482. Vector2.Normalize = function (vector) {
  483. var newVector = vector.clone();
  484. newVector.normalize();
  485. return newVector;
  486. };
  487. Vector2.Minimize = function (left, right) {
  488. var x = (left.x < right.x) ? left.x : right.x;
  489. var y = (left.y < right.y) ? left.y : right.y;
  490. return new Vector2(x, y);
  491. };
  492. Vector2.Maximize = function (left, right) {
  493. var x = (left.x > right.x) ? left.x : right.x;
  494. var y = (left.y > right.y) ? left.y : right.y;
  495. return new Vector2(x, y);
  496. };
  497. Vector2.Transform = function (vector, transformation) {
  498. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  499. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  500. return new Vector2(x, y);
  501. };
  502. Vector2.Distance = function (value1, value2) {
  503. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  504. };
  505. Vector2.DistanceSquared = function (value1, value2) {
  506. var x = value1.x - value2.x;
  507. var y = value1.y - value2.y;
  508. return (x * x) + (y * y);
  509. };
  510. return Vector2;
  511. })();
  512. BABYLON.Vector2 = Vector2;
  513. var Vector3 = (function () {
  514. function Vector3(x, y, z) {
  515. this.x = x;
  516. this.y = y;
  517. this.z = z;
  518. }
  519. Vector3.prototype.toString = function () {
  520. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  521. };
  522. // Operators
  523. Vector3.prototype.asArray = function () {
  524. var result = [];
  525. this.toArray(result, 0);
  526. return result;
  527. };
  528. Vector3.prototype.toArray = function (array, index) {
  529. if (index === void 0) { index = 0; }
  530. array[index] = this.x;
  531. array[index + 1] = this.y;
  532. array[index + 2] = this.z;
  533. return this;
  534. };
  535. Vector3.prototype.toQuaternion = function () {
  536. var result = new Quaternion(0, 0, 0, 1);
  537. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  538. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  539. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  540. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  541. var cosy = Math.cos(this.y * 0.5);
  542. var siny = Math.sin(this.y * 0.5);
  543. result.x = coszMinusx * siny;
  544. result.y = -sinzMinusx * siny;
  545. result.z = sinxPlusz * cosy;
  546. result.w = cosxPlusz * cosy;
  547. return result;
  548. };
  549. Vector3.prototype.addInPlace = function (otherVector) {
  550. this.x += otherVector.x;
  551. this.y += otherVector.y;
  552. this.z += otherVector.z;
  553. return this;
  554. };
  555. Vector3.prototype.add = function (otherVector) {
  556. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  557. };
  558. Vector3.prototype.addToRef = function (otherVector, result) {
  559. result.x = this.x + otherVector.x;
  560. result.y = this.y + otherVector.y;
  561. result.z = this.z + otherVector.z;
  562. return this;
  563. };
  564. Vector3.prototype.subtractInPlace = function (otherVector) {
  565. this.x -= otherVector.x;
  566. this.y -= otherVector.y;
  567. this.z -= otherVector.z;
  568. return this;
  569. };
  570. Vector3.prototype.subtract = function (otherVector) {
  571. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  572. };
  573. Vector3.prototype.subtractToRef = function (otherVector, result) {
  574. result.x = this.x - otherVector.x;
  575. result.y = this.y - otherVector.y;
  576. result.z = this.z - otherVector.z;
  577. return this;
  578. };
  579. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  580. return new Vector3(this.x - x, this.y - y, this.z - z);
  581. };
  582. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  583. result.x = this.x - x;
  584. result.y = this.y - y;
  585. result.z = this.z - z;
  586. return this;
  587. };
  588. Vector3.prototype.negate = function () {
  589. return new Vector3(-this.x, -this.y, -this.z);
  590. };
  591. Vector3.prototype.scaleInPlace = function (scale) {
  592. this.x *= scale;
  593. this.y *= scale;
  594. this.z *= scale;
  595. return this;
  596. };
  597. Vector3.prototype.scale = function (scale) {
  598. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  599. };
  600. Vector3.prototype.scaleToRef = function (scale, result) {
  601. result.x = this.x * scale;
  602. result.y = this.y * scale;
  603. result.z = this.z * scale;
  604. };
  605. Vector3.prototype.equals = function (otherVector) {
  606. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  607. };
  608. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  609. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  610. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  611. };
  612. Vector3.prototype.equalsToFloats = function (x, y, z) {
  613. return this.x === x && this.y === y && this.z === z;
  614. };
  615. Vector3.prototype.multiplyInPlace = function (otherVector) {
  616. this.x *= otherVector.x;
  617. this.y *= otherVector.y;
  618. this.z *= otherVector.z;
  619. return this;
  620. };
  621. Vector3.prototype.multiply = function (otherVector) {
  622. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  623. };
  624. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  625. result.x = this.x * otherVector.x;
  626. result.y = this.y * otherVector.y;
  627. result.z = this.z * otherVector.z;
  628. return this;
  629. };
  630. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  631. return new Vector3(this.x * x, this.y * y, this.z * z);
  632. };
  633. Vector3.prototype.divide = function (otherVector) {
  634. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  635. };
  636. Vector3.prototype.divideToRef = function (otherVector, result) {
  637. result.x = this.x / otherVector.x;
  638. result.y = this.y / otherVector.y;
  639. result.z = this.z / otherVector.z;
  640. return this;
  641. };
  642. Vector3.prototype.MinimizeInPlace = function (other) {
  643. if (other.x < this.x)
  644. this.x = other.x;
  645. if (other.y < this.y)
  646. this.y = other.y;
  647. if (other.z < this.z)
  648. this.z = other.z;
  649. return this;
  650. };
  651. Vector3.prototype.MaximizeInPlace = function (other) {
  652. if (other.x > this.x)
  653. this.x = other.x;
  654. if (other.y > this.y)
  655. this.y = other.y;
  656. if (other.z > this.z)
  657. this.z = other.z;
  658. return this;
  659. };
  660. // Properties
  661. Vector3.prototype.length = function () {
  662. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  663. };
  664. Vector3.prototype.lengthSquared = function () {
  665. return (this.x * this.x + this.y * this.y + this.z * this.z);
  666. };
  667. // Methods
  668. Vector3.prototype.normalize = function () {
  669. var len = this.length();
  670. if (len === 0 || len === 1.0)
  671. return this;
  672. var num = 1.0 / len;
  673. this.x *= num;
  674. this.y *= num;
  675. this.z *= num;
  676. return this;
  677. };
  678. Vector3.prototype.clone = function () {
  679. return new Vector3(this.x, this.y, this.z);
  680. };
  681. Vector3.prototype.copyFrom = function (source) {
  682. this.x = source.x;
  683. this.y = source.y;
  684. this.z = source.z;
  685. return this;
  686. };
  687. Vector3.prototype.copyFromFloats = function (x, y, z) {
  688. this.x = x;
  689. this.y = y;
  690. this.z = z;
  691. return this;
  692. };
  693. // Statics
  694. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  695. var d0 = Vector3.Dot(vector0, axis) - size;
  696. var d1 = Vector3.Dot(vector1, axis) - size;
  697. var s = d0 / (d0 - d1);
  698. return s;
  699. };
  700. Vector3.FromArray = function (array, offset) {
  701. if (!offset) {
  702. offset = 0;
  703. }
  704. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  705. };
  706. Vector3.FromFloatArray = function (array, offset) {
  707. if (!offset) {
  708. offset = 0;
  709. }
  710. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  711. };
  712. Vector3.FromArrayToRef = function (array, offset, result) {
  713. result.x = array[offset];
  714. result.y = array[offset + 1];
  715. result.z = array[offset + 2];
  716. };
  717. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  718. result.x = array[offset];
  719. result.y = array[offset + 1];
  720. result.z = array[offset + 2];
  721. };
  722. Vector3.FromFloatsToRef = function (x, y, z, result) {
  723. result.x = x;
  724. result.y = y;
  725. result.z = z;
  726. };
  727. Vector3.Zero = function () {
  728. return new Vector3(0, 0, 0);
  729. };
  730. Vector3.Up = function () {
  731. return new Vector3(0, 1.0, 0);
  732. };
  733. Vector3.TransformCoordinates = function (vector, transformation) {
  734. var result = Vector3.Zero();
  735. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  736. return result;
  737. };
  738. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  739. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  740. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  741. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  742. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  743. result.x = x / w;
  744. result.y = y / w;
  745. result.z = z / w;
  746. };
  747. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  748. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  749. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  750. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  751. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  752. result.x = rx / rw;
  753. result.y = ry / rw;
  754. result.z = rz / rw;
  755. };
  756. Vector3.TransformNormal = function (vector, transformation) {
  757. var result = Vector3.Zero();
  758. Vector3.TransformNormalToRef(vector, transformation, result);
  759. return result;
  760. };
  761. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  762. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  763. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  764. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  765. };
  766. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  767. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  768. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  769. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  770. };
  771. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  772. var squared = amount * amount;
  773. var cubed = amount * squared;
  774. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  775. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  776. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  777. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  778. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  779. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  780. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  781. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  782. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  783. return new Vector3(x, y, z);
  784. };
  785. Vector3.Clamp = function (value, min, max) {
  786. var x = value.x;
  787. x = (x > max.x) ? max.x : x;
  788. x = (x < min.x) ? min.x : x;
  789. var y = value.y;
  790. y = (y > max.y) ? max.y : y;
  791. y = (y < min.y) ? min.y : y;
  792. var z = value.z;
  793. z = (z > max.z) ? max.z : z;
  794. z = (z < min.z) ? min.z : z;
  795. return new Vector3(x, y, z);
  796. };
  797. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  798. var squared = amount * amount;
  799. var cubed = amount * squared;
  800. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  801. var part2 = (-2.0 * cubed) + (3.0 * squared);
  802. var part3 = (cubed - (2.0 * squared)) + amount;
  803. var part4 = cubed - squared;
  804. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  805. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  806. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  807. return new Vector3(x, y, z);
  808. };
  809. Vector3.Lerp = function (start, end, amount) {
  810. var x = start.x + ((end.x - start.x) * amount);
  811. var y = start.y + ((end.y - start.y) * amount);
  812. var z = start.z + ((end.z - start.z) * amount);
  813. return new Vector3(x, y, z);
  814. };
  815. Vector3.Dot = function (left, right) {
  816. return (left.x * right.x + left.y * right.y + left.z * right.z);
  817. };
  818. Vector3.Cross = function (left, right) {
  819. var result = Vector3.Zero();
  820. Vector3.CrossToRef(left, right, result);
  821. return result;
  822. };
  823. Vector3.CrossToRef = function (left, right, result) {
  824. result.x = left.y * right.z - left.z * right.y;
  825. result.y = left.z * right.x - left.x * right.z;
  826. result.z = left.x * right.y - left.y * right.x;
  827. };
  828. Vector3.Normalize = function (vector) {
  829. var result = Vector3.Zero();
  830. Vector3.NormalizeToRef(vector, result);
  831. return result;
  832. };
  833. Vector3.NormalizeToRef = function (vector, result) {
  834. result.copyFrom(vector);
  835. result.normalize();
  836. };
  837. Vector3.Project = function (vector, world, transform, viewport) {
  838. var cw = viewport.width;
  839. var ch = viewport.height;
  840. var cx = viewport.x;
  841. var cy = viewport.y;
  842. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  843. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  844. return Vector3.TransformCoordinates(vector, finalMatrix);
  845. };
  846. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  847. var matrix = world.multiply(transform);
  848. matrix.invert();
  849. source.x = source.x / viewportWidth * 2 - 1;
  850. source.y = -(source.y / viewportHeight * 2 - 1);
  851. var vector = Vector3.TransformCoordinates(source, matrix);
  852. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  853. if (MathTools.WithinEpsilon(num, 1.0)) {
  854. vector = vector.scale(1.0 / num);
  855. }
  856. return vector;
  857. };
  858. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  859. var matrix = world.multiply(view).multiply(projection);
  860. matrix.invert();
  861. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  862. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  863. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  864. if (MathTools.WithinEpsilon(num, 1.0)) {
  865. vector = vector.scale(1.0 / num);
  866. }
  867. return vector;
  868. };
  869. Vector3.Minimize = function (left, right) {
  870. var min = left.clone();
  871. min.MinimizeInPlace(right);
  872. return min;
  873. };
  874. Vector3.Maximize = function (left, right) {
  875. var max = left.clone();
  876. max.MaximizeInPlace(right);
  877. return max;
  878. };
  879. Vector3.Distance = function (value1, value2) {
  880. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  881. };
  882. Vector3.DistanceSquared = function (value1, value2) {
  883. var x = value1.x - value2.x;
  884. var y = value1.y - value2.y;
  885. var z = value1.z - value2.z;
  886. return (x * x) + (y * y) + (z * z);
  887. };
  888. Vector3.Center = function (value1, value2) {
  889. var center = value1.add(value2);
  890. center.scaleInPlace(0.5);
  891. return center;
  892. };
  893. /**
  894. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  895. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  896. * to something in order to rotate it from its local system to the given target system.
  897. */
  898. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  899. var rotation = Vector3.Zero();
  900. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  901. return rotation;
  902. };
  903. /**
  904. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  905. */
  906. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  907. var u = axis1.normalize();
  908. var w = axis3.normalize();
  909. // world axis
  910. var X = Axis.X;
  911. var Y = Axis.Y;
  912. // equation unknowns and vars
  913. var yaw = 0.0;
  914. var pitch = 0.0;
  915. var roll = 0.0;
  916. var x = 0.0;
  917. var y = 0.0;
  918. var z = 0.0;
  919. var t = 0.0;
  920. var sign = -1.0;
  921. var nbRevert = 0;
  922. var cross = Tmp.Vector3[0];
  923. var dot = 0.0;
  924. // step 1 : rotation around w
  925. // Rv3(u) = u1, and u1 belongs to plane xOz
  926. // Rv3(w) = w1 = w invariant
  927. var u1 = Tmp.Vector3[1];
  928. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  929. z = 1.0;
  930. }
  931. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  932. x = 1.0;
  933. }
  934. else {
  935. t = w.z / w.x;
  936. x = -t * Math.sqrt(1 / (1 + t * t));
  937. z = Math.sqrt(1 / (1 + t * t));
  938. }
  939. u1.x = x;
  940. u1.y = y;
  941. u1.z = z;
  942. u1.normalize();
  943. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  944. cross.normalize();
  945. if (Vector3.Dot(w, cross) < 0) {
  946. sign = 1.0;
  947. }
  948. dot = Vector3.Dot(u, u1);
  949. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  950. roll = Math.acos(dot) * sign;
  951. if (Vector3.Dot(u1, X) < 0) {
  952. roll = Math.PI + roll;
  953. u1 = u1.scaleInPlace(-1);
  954. nbRevert++;
  955. }
  956. // step 2 : rotate around u1
  957. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  958. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  959. var w2 = Tmp.Vector3[2];
  960. var v2 = Tmp.Vector3[3];
  961. x = 0.0;
  962. y = 0.0;
  963. z = 0.0;
  964. sign = -1.0;
  965. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  966. x = 1.0;
  967. }
  968. else {
  969. t = u1.z / u1.x;
  970. x = -t * Math.sqrt(1 / (1 + t * t));
  971. z = Math.sqrt(1 / (1 + t * t));
  972. }
  973. w2.x = x;
  974. w2.y = y;
  975. w2.z = z;
  976. w2.normalize();
  977. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  978. v2.normalize();
  979. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  980. cross.normalize();
  981. if (Vector3.Dot(u1, cross) < 0) {
  982. sign = 1.0;
  983. }
  984. dot = Vector3.Dot(w, w2);
  985. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  986. pitch = Math.acos(dot) * sign;
  987. if (Vector3.Dot(v2, Y) < 0) {
  988. pitch = Math.PI + pitch;
  989. nbRevert++;
  990. }
  991. // step 3 : rotate around v2
  992. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  993. sign = -1.0;
  994. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  995. cross.normalize();
  996. if (Vector3.Dot(cross, Y) < 0) {
  997. sign = 1.0;
  998. }
  999. dot = Vector3.Dot(u1, X);
  1000. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1001. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1002. if (dot < 0 && nbRevert < 2) {
  1003. yaw = Math.PI + yaw;
  1004. }
  1005. ref.x = pitch;
  1006. ref.y = yaw;
  1007. ref.z = roll;
  1008. };
  1009. return Vector3;
  1010. })();
  1011. BABYLON.Vector3 = Vector3;
  1012. //Vector4 class created for EulerAngle class conversion to Quaternion
  1013. var Vector4 = (function () {
  1014. function Vector4(x, y, z, w) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. this.w = w;
  1019. }
  1020. Vector4.prototype.toString = function () {
  1021. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1022. };
  1023. // Operators
  1024. Vector4.prototype.asArray = function () {
  1025. var result = [];
  1026. this.toArray(result, 0);
  1027. return result;
  1028. };
  1029. Vector4.prototype.toArray = function (array, index) {
  1030. if (index === undefined) {
  1031. index = 0;
  1032. }
  1033. array[index] = this.x;
  1034. array[index + 1] = this.y;
  1035. array[index + 2] = this.z;
  1036. array[index + 3] = this.w;
  1037. return this;
  1038. };
  1039. Vector4.prototype.addInPlace = function (otherVector) {
  1040. this.x += otherVector.x;
  1041. this.y += otherVector.y;
  1042. this.z += otherVector.z;
  1043. this.w += otherVector.w;
  1044. return this;
  1045. };
  1046. Vector4.prototype.add = function (otherVector) {
  1047. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1048. };
  1049. Vector4.prototype.addToRef = function (otherVector, result) {
  1050. result.x = this.x + otherVector.x;
  1051. result.y = this.y + otherVector.y;
  1052. result.z = this.z + otherVector.z;
  1053. result.w = this.w + otherVector.w;
  1054. return this;
  1055. };
  1056. Vector4.prototype.subtractInPlace = function (otherVector) {
  1057. this.x -= otherVector.x;
  1058. this.y -= otherVector.y;
  1059. this.z -= otherVector.z;
  1060. this.w -= otherVector.w;
  1061. return this;
  1062. };
  1063. Vector4.prototype.subtract = function (otherVector) {
  1064. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1065. };
  1066. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1067. result.x = this.x - otherVector.x;
  1068. result.y = this.y - otherVector.y;
  1069. result.z = this.z - otherVector.z;
  1070. result.w = this.w - otherVector.w;
  1071. return this;
  1072. };
  1073. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1074. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1075. };
  1076. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1077. result.x = this.x - x;
  1078. result.y = this.y - y;
  1079. result.z = this.z - z;
  1080. result.w = this.w - w;
  1081. return this;
  1082. };
  1083. Vector4.prototype.negate = function () {
  1084. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1085. };
  1086. Vector4.prototype.scaleInPlace = function (scale) {
  1087. this.x *= scale;
  1088. this.y *= scale;
  1089. this.z *= scale;
  1090. this.w *= scale;
  1091. return this;
  1092. };
  1093. Vector4.prototype.scale = function (scale) {
  1094. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1095. };
  1096. Vector4.prototype.scaleToRef = function (scale, result) {
  1097. result.x = this.x * scale;
  1098. result.y = this.y * scale;
  1099. result.z = this.z * scale;
  1100. result.w = this.w * scale;
  1101. };
  1102. Vector4.prototype.equals = function (otherVector) {
  1103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1104. };
  1105. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1106. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1107. return otherVector
  1108. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1109. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1110. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1111. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1112. };
  1113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1114. return this.x === x && this.y === y && this.z === z && this.w === w;
  1115. };
  1116. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1117. this.x *= otherVector.x;
  1118. this.y *= otherVector.y;
  1119. this.z *= otherVector.z;
  1120. this.w *= otherVector.w;
  1121. return this;
  1122. };
  1123. Vector4.prototype.multiply = function (otherVector) {
  1124. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1125. };
  1126. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1127. result.x = this.x * otherVector.x;
  1128. result.y = this.y * otherVector.y;
  1129. result.z = this.z * otherVector.z;
  1130. result.w = this.w * otherVector.w;
  1131. return this;
  1132. };
  1133. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1134. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1135. };
  1136. Vector4.prototype.divide = function (otherVector) {
  1137. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1138. };
  1139. Vector4.prototype.divideToRef = function (otherVector, result) {
  1140. result.x = this.x / otherVector.x;
  1141. result.y = this.y / otherVector.y;
  1142. result.z = this.z / otherVector.z;
  1143. result.w = this.w / otherVector.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.MinimizeInPlace = function (other) {
  1147. if (other.x < this.x)
  1148. this.x = other.x;
  1149. if (other.y < this.y)
  1150. this.y = other.y;
  1151. if (other.z < this.z)
  1152. this.z = other.z;
  1153. if (other.w < this.w)
  1154. this.w = other.w;
  1155. return this;
  1156. };
  1157. Vector4.prototype.MaximizeInPlace = function (other) {
  1158. if (other.x > this.x)
  1159. this.x = other.x;
  1160. if (other.y > this.y)
  1161. this.y = other.y;
  1162. if (other.z > this.z)
  1163. this.z = other.z;
  1164. if (other.w > this.w)
  1165. this.w = other.w;
  1166. return this;
  1167. };
  1168. // Properties
  1169. Vector4.prototype.length = function () {
  1170. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1171. };
  1172. Vector4.prototype.lengthSquared = function () {
  1173. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1174. };
  1175. // Methods
  1176. Vector4.prototype.normalize = function () {
  1177. var len = this.length();
  1178. if (len === 0)
  1179. return this;
  1180. var num = 1.0 / len;
  1181. this.x *= num;
  1182. this.y *= num;
  1183. this.z *= num;
  1184. this.w *= num;
  1185. return this;
  1186. };
  1187. Vector4.prototype.clone = function () {
  1188. return new Vector4(this.x, this.y, this.z, this.w);
  1189. };
  1190. Vector4.prototype.copyFrom = function (source) {
  1191. this.x = source.x;
  1192. this.y = source.y;
  1193. this.z = source.z;
  1194. this.w = source.w;
  1195. return this;
  1196. };
  1197. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1198. this.x = x;
  1199. this.y = y;
  1200. this.z = z;
  1201. this.w = w;
  1202. return this;
  1203. };
  1204. // Statics
  1205. Vector4.FromArray = function (array, offset) {
  1206. if (!offset) {
  1207. offset = 0;
  1208. }
  1209. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1210. };
  1211. Vector4.FromArrayToRef = function (array, offset, result) {
  1212. result.x = array[offset];
  1213. result.y = array[offset + 1];
  1214. result.z = array[offset + 2];
  1215. result.w = array[offset + 3];
  1216. };
  1217. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1218. result.x = array[offset];
  1219. result.y = array[offset + 1];
  1220. result.z = array[offset + 2];
  1221. result.w = array[offset + 3];
  1222. };
  1223. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1224. result.x = x;
  1225. result.y = y;
  1226. result.z = z;
  1227. result.w = w;
  1228. };
  1229. Vector4.Zero = function () {
  1230. return new Vector4(0, 0, 0, 0);
  1231. };
  1232. Vector4.Normalize = function (vector) {
  1233. var result = Vector4.Zero();
  1234. Vector4.NormalizeToRef(vector, result);
  1235. return result;
  1236. };
  1237. Vector4.NormalizeToRef = function (vector, result) {
  1238. result.copyFrom(vector);
  1239. result.normalize();
  1240. };
  1241. Vector4.Minimize = function (left, right) {
  1242. var min = left.clone();
  1243. min.MinimizeInPlace(right);
  1244. return min;
  1245. };
  1246. Vector4.Maximize = function (left, right) {
  1247. var max = left.clone();
  1248. max.MaximizeInPlace(right);
  1249. return max;
  1250. };
  1251. Vector4.Distance = function (value1, value2) {
  1252. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1253. };
  1254. Vector4.DistanceSquared = function (value1, value2) {
  1255. var x = value1.x - value2.x;
  1256. var y = value1.y - value2.y;
  1257. var z = value1.z - value2.z;
  1258. var w = value1.w - value2.w;
  1259. return (x * x) + (y * y) + (z * z) + (w * w);
  1260. };
  1261. Vector4.Center = function (value1, value2) {
  1262. var center = value1.add(value2);
  1263. center.scaleInPlace(0.5);
  1264. return center;
  1265. };
  1266. return Vector4;
  1267. })();
  1268. BABYLON.Vector4 = Vector4;
  1269. var Quaternion = (function () {
  1270. function Quaternion(x, y, z, w) {
  1271. if (x === void 0) { x = 0; }
  1272. if (y === void 0) { y = 0; }
  1273. if (z === void 0) { z = 0; }
  1274. if (w === void 0) { w = 1; }
  1275. this.x = x;
  1276. this.y = y;
  1277. this.z = z;
  1278. this.w = w;
  1279. }
  1280. Quaternion.prototype.toString = function () {
  1281. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1282. };
  1283. Quaternion.prototype.asArray = function () {
  1284. return [this.x, this.y, this.z, this.w];
  1285. };
  1286. Quaternion.prototype.equals = function (otherQuaternion) {
  1287. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1288. };
  1289. Quaternion.prototype.clone = function () {
  1290. return new Quaternion(this.x, this.y, this.z, this.w);
  1291. };
  1292. Quaternion.prototype.copyFrom = function (other) {
  1293. this.x = other.x;
  1294. this.y = other.y;
  1295. this.z = other.z;
  1296. this.w = other.w;
  1297. return this;
  1298. };
  1299. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1300. this.x = x;
  1301. this.y = y;
  1302. this.z = z;
  1303. this.w = w;
  1304. return this;
  1305. };
  1306. Quaternion.prototype.add = function (other) {
  1307. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1308. };
  1309. Quaternion.prototype.subtract = function (other) {
  1310. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1311. };
  1312. Quaternion.prototype.scale = function (value) {
  1313. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1314. };
  1315. Quaternion.prototype.multiply = function (q1) {
  1316. var result = new Quaternion(0, 0, 0, 1.0);
  1317. this.multiplyToRef(q1, result);
  1318. return result;
  1319. };
  1320. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1321. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1322. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1323. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1324. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1325. result.copyFromFloats(x, y, z, w);
  1326. return this;
  1327. };
  1328. Quaternion.prototype.multiplyInPlace = function (q1) {
  1329. this.multiplyToRef(q1, this);
  1330. return this;
  1331. };
  1332. Quaternion.prototype.conjugateToRef = function (ref) {
  1333. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1334. return this;
  1335. };
  1336. Quaternion.prototype.conjugateInPlace = function () {
  1337. this.x *= -1;
  1338. this.y *= -1;
  1339. this.z *= -1;
  1340. return this;
  1341. };
  1342. Quaternion.prototype.conjugate = function () {
  1343. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1344. return result;
  1345. };
  1346. Quaternion.prototype.length = function () {
  1347. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1348. };
  1349. Quaternion.prototype.normalize = function () {
  1350. var length = 1.0 / this.length();
  1351. this.x *= length;
  1352. this.y *= length;
  1353. this.z *= length;
  1354. this.w *= length;
  1355. return this;
  1356. };
  1357. Quaternion.prototype.toEulerAngles = function (order) {
  1358. if (order === void 0) { order = "YZX"; }
  1359. var result = Vector3.Zero();
  1360. this.toEulerAnglesToRef(result, order);
  1361. return result;
  1362. };
  1363. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1364. if (order === void 0) { order = "YZX"; }
  1365. var heading, attitude, bank;
  1366. var x = this.x, y = this.y, z = this.z, w = this.w;
  1367. switch (order) {
  1368. case "YZX":
  1369. var test = x * y + z * w;
  1370. if (test > 0.499) {
  1371. heading = 2 * Math.atan2(x, w);
  1372. attitude = Math.PI / 2;
  1373. bank = 0;
  1374. }
  1375. if (test < -0.499) {
  1376. heading = -2 * Math.atan2(x, w);
  1377. attitude = -Math.PI / 2;
  1378. bank = 0;
  1379. }
  1380. if (isNaN(heading)) {
  1381. var sqx = x * x;
  1382. var sqy = y * y;
  1383. var sqz = z * z;
  1384. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1385. attitude = Math.asin(2 * test); // attitude
  1386. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1387. }
  1388. break;
  1389. default:
  1390. throw new Error("Euler order " + order + " not supported yet.");
  1391. }
  1392. result.y = heading;
  1393. result.z = attitude;
  1394. result.x = bank;
  1395. return this;
  1396. };
  1397. ;
  1398. Quaternion.prototype.toRotationMatrix = function (result) {
  1399. var xx = this.x * this.x;
  1400. var yy = this.y * this.y;
  1401. var zz = this.z * this.z;
  1402. var xy = this.x * this.y;
  1403. var zw = this.z * this.w;
  1404. var zx = this.z * this.x;
  1405. var yw = this.y * this.w;
  1406. var yz = this.y * this.z;
  1407. var xw = this.x * this.w;
  1408. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1409. result.m[1] = 2.0 * (xy + zw);
  1410. result.m[2] = 2.0 * (zx - yw);
  1411. result.m[3] = 0;
  1412. result.m[4] = 2.0 * (xy - zw);
  1413. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1414. result.m[6] = 2.0 * (yz + xw);
  1415. result.m[7] = 0;
  1416. result.m[8] = 2.0 * (zx + yw);
  1417. result.m[9] = 2.0 * (yz - xw);
  1418. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1419. result.m[11] = 0;
  1420. result.m[12] = 0;
  1421. result.m[13] = 0;
  1422. result.m[14] = 0;
  1423. result.m[15] = 1.0;
  1424. return this;
  1425. };
  1426. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1427. Quaternion.FromRotationMatrixToRef(matrix, this);
  1428. return this;
  1429. };
  1430. // Statics
  1431. Quaternion.FromRotationMatrix = function (matrix) {
  1432. var result = new Quaternion();
  1433. Quaternion.FromRotationMatrixToRef(matrix, result);
  1434. return result;
  1435. };
  1436. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1437. var data = matrix.m;
  1438. var m11 = data[0], m12 = data[4], m13 = data[8];
  1439. var m21 = data[1], m22 = data[5], m23 = data[9];
  1440. var m31 = data[2], m32 = data[6], m33 = data[10];
  1441. var trace = m11 + m22 + m33;
  1442. var s;
  1443. if (trace > 0) {
  1444. s = 0.5 / Math.sqrt(trace + 1.0);
  1445. result.w = 0.25 / s;
  1446. result.x = (m32 - m23) * s;
  1447. result.y = (m13 - m31) * s;
  1448. result.z = (m21 - m12) * s;
  1449. }
  1450. else if (m11 > m22 && m11 > m33) {
  1451. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1452. result.w = (m32 - m23) / s;
  1453. result.x = 0.25 * s;
  1454. result.y = (m12 + m21) / s;
  1455. result.z = (m13 + m31) / s;
  1456. }
  1457. else if (m22 > m33) {
  1458. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1459. result.w = (m13 - m31) / s;
  1460. result.x = (m12 + m21) / s;
  1461. result.y = 0.25 * s;
  1462. result.z = (m23 + m32) / s;
  1463. }
  1464. else {
  1465. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1466. result.w = (m21 - m12) / s;
  1467. result.x = (m13 + m31) / s;
  1468. result.y = (m23 + m32) / s;
  1469. result.z = 0.25 * s;
  1470. }
  1471. };
  1472. Quaternion.Inverse = function (q) {
  1473. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1474. };
  1475. Quaternion.Identity = function () {
  1476. return new Quaternion(0, 0, 0, 1);
  1477. };
  1478. Quaternion.RotationAxis = function (axis, angle) {
  1479. var result = new Quaternion();
  1480. var sin = Math.sin(angle / 2);
  1481. axis.normalize();
  1482. result.w = Math.cos(angle / 2);
  1483. result.x = axis.x * sin;
  1484. result.y = axis.y * sin;
  1485. result.z = axis.z * sin;
  1486. return result;
  1487. };
  1488. Quaternion.FromArray = function (array, offset) {
  1489. if (!offset) {
  1490. offset = 0;
  1491. }
  1492. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1493. };
  1494. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1495. var result = new Quaternion();
  1496. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1497. return result;
  1498. };
  1499. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1500. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1501. var halfRoll = roll * 0.5;
  1502. var halfPitch = pitch * 0.5;
  1503. var halfYaw = yaw * 0.5;
  1504. var sinRoll = Math.sin(halfRoll);
  1505. var cosRoll = Math.cos(halfRoll);
  1506. var sinPitch = Math.sin(halfPitch);
  1507. var cosPitch = Math.cos(halfPitch);
  1508. var sinYaw = Math.sin(halfYaw);
  1509. var cosYaw = Math.cos(halfYaw);
  1510. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1511. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1512. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1513. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1514. };
  1515. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1516. var result = new Quaternion();
  1517. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1518. return result;
  1519. };
  1520. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1521. // Produces a quaternion from Euler angles in the z-x-z orientation
  1522. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1523. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1524. var halfBeta = beta * 0.5;
  1525. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1526. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1527. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1528. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1529. };
  1530. Quaternion.Slerp = function (left, right, amount) {
  1531. var num2;
  1532. var num3;
  1533. var num = amount;
  1534. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1535. var flag = false;
  1536. if (num4 < 0) {
  1537. flag = true;
  1538. num4 = -num4;
  1539. }
  1540. if (num4 > 0.999999) {
  1541. num3 = 1 - num;
  1542. num2 = flag ? -num : num;
  1543. }
  1544. else {
  1545. var num5 = Math.acos(num4);
  1546. var num6 = (1.0 / Math.sin(num5));
  1547. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1548. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1549. }
  1550. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1551. };
  1552. return Quaternion;
  1553. })();
  1554. BABYLON.Quaternion = Quaternion;
  1555. var Matrix = (function () {
  1556. function Matrix() {
  1557. this.m = new Float32Array(16);
  1558. }
  1559. // Properties
  1560. Matrix.prototype.isIdentity = function () {
  1561. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1562. return false;
  1563. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1564. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1565. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1566. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1567. return false;
  1568. return true;
  1569. };
  1570. Matrix.prototype.determinant = function () {
  1571. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1572. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1573. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1574. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1575. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1576. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1577. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1578. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1579. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1580. };
  1581. // Methods
  1582. Matrix.prototype.toArray = function () {
  1583. return this.m;
  1584. };
  1585. Matrix.prototype.asArray = function () {
  1586. return this.toArray();
  1587. };
  1588. Matrix.prototype.invert = function () {
  1589. this.invertToRef(this);
  1590. return this;
  1591. };
  1592. Matrix.prototype.reset = function () {
  1593. for (var index = 0; index < 16; index++) {
  1594. this.m[index] = 0;
  1595. }
  1596. return this;
  1597. };
  1598. Matrix.prototype.add = function (other) {
  1599. var result = new Matrix();
  1600. this.addToRef(other, result);
  1601. return result;
  1602. };
  1603. Matrix.prototype.addToRef = function (other, result) {
  1604. for (var index = 0; index < 16; index++) {
  1605. result.m[index] = this.m[index] + other.m[index];
  1606. }
  1607. return this;
  1608. };
  1609. Matrix.prototype.addToSelf = function (other) {
  1610. for (var index = 0; index < 16; index++) {
  1611. this.m[index] += other.m[index];
  1612. }
  1613. return this;
  1614. };
  1615. Matrix.prototype.invertToRef = function (other) {
  1616. var l1 = this.m[0];
  1617. var l2 = this.m[1];
  1618. var l3 = this.m[2];
  1619. var l4 = this.m[3];
  1620. var l5 = this.m[4];
  1621. var l6 = this.m[5];
  1622. var l7 = this.m[6];
  1623. var l8 = this.m[7];
  1624. var l9 = this.m[8];
  1625. var l10 = this.m[9];
  1626. var l11 = this.m[10];
  1627. var l12 = this.m[11];
  1628. var l13 = this.m[12];
  1629. var l14 = this.m[13];
  1630. var l15 = this.m[14];
  1631. var l16 = this.m[15];
  1632. var l17 = (l11 * l16) - (l12 * l15);
  1633. var l18 = (l10 * l16) - (l12 * l14);
  1634. var l19 = (l10 * l15) - (l11 * l14);
  1635. var l20 = (l9 * l16) - (l12 * l13);
  1636. var l21 = (l9 * l15) - (l11 * l13);
  1637. var l22 = (l9 * l14) - (l10 * l13);
  1638. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1639. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1640. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1641. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1642. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1643. var l28 = (l7 * l16) - (l8 * l15);
  1644. var l29 = (l6 * l16) - (l8 * l14);
  1645. var l30 = (l6 * l15) - (l7 * l14);
  1646. var l31 = (l5 * l16) - (l8 * l13);
  1647. var l32 = (l5 * l15) - (l7 * l13);
  1648. var l33 = (l5 * l14) - (l6 * l13);
  1649. var l34 = (l7 * l12) - (l8 * l11);
  1650. var l35 = (l6 * l12) - (l8 * l10);
  1651. var l36 = (l6 * l11) - (l7 * l10);
  1652. var l37 = (l5 * l12) - (l8 * l9);
  1653. var l38 = (l5 * l11) - (l7 * l9);
  1654. var l39 = (l5 * l10) - (l6 * l9);
  1655. other.m[0] = l23 * l27;
  1656. other.m[4] = l24 * l27;
  1657. other.m[8] = l25 * l27;
  1658. other.m[12] = l26 * l27;
  1659. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1660. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1661. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1662. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1663. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1664. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1665. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1666. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1667. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1668. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1669. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1670. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1671. return this;
  1672. };
  1673. Matrix.prototype.setTranslation = function (vector3) {
  1674. this.m[12] = vector3.x;
  1675. this.m[13] = vector3.y;
  1676. this.m[14] = vector3.z;
  1677. return this;
  1678. };
  1679. Matrix.prototype.multiply = function (other) {
  1680. var result = new Matrix();
  1681. this.multiplyToRef(other, result);
  1682. return result;
  1683. };
  1684. Matrix.prototype.copyFrom = function (other) {
  1685. for (var index = 0; index < 16; index++) {
  1686. this.m[index] = other.m[index];
  1687. }
  1688. return this;
  1689. };
  1690. Matrix.prototype.copyToArray = function (array, offset) {
  1691. if (offset === void 0) { offset = 0; }
  1692. for (var index = 0; index < 16; index++) {
  1693. array[offset + index] = this.m[index];
  1694. }
  1695. return this;
  1696. };
  1697. Matrix.prototype.multiplyToRef = function (other, result) {
  1698. this.multiplyToArray(other, result.m, 0);
  1699. return this;
  1700. };
  1701. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1702. var tm0 = this.m[0];
  1703. var tm1 = this.m[1];
  1704. var tm2 = this.m[2];
  1705. var tm3 = this.m[3];
  1706. var tm4 = this.m[4];
  1707. var tm5 = this.m[5];
  1708. var tm6 = this.m[6];
  1709. var tm7 = this.m[7];
  1710. var tm8 = this.m[8];
  1711. var tm9 = this.m[9];
  1712. var tm10 = this.m[10];
  1713. var tm11 = this.m[11];
  1714. var tm12 = this.m[12];
  1715. var tm13 = this.m[13];
  1716. var tm14 = this.m[14];
  1717. var tm15 = this.m[15];
  1718. var om0 = other.m[0];
  1719. var om1 = other.m[1];
  1720. var om2 = other.m[2];
  1721. var om3 = other.m[3];
  1722. var om4 = other.m[4];
  1723. var om5 = other.m[5];
  1724. var om6 = other.m[6];
  1725. var om7 = other.m[7];
  1726. var om8 = other.m[8];
  1727. var om9 = other.m[9];
  1728. var om10 = other.m[10];
  1729. var om11 = other.m[11];
  1730. var om12 = other.m[12];
  1731. var om13 = other.m[13];
  1732. var om14 = other.m[14];
  1733. var om15 = other.m[15];
  1734. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1735. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1736. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1737. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1738. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1739. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1740. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1741. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1742. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1743. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1744. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1745. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1746. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1747. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1748. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1749. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1750. return this;
  1751. };
  1752. Matrix.prototype.equals = function (value) {
  1753. return value &&
  1754. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1755. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1756. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1757. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1758. };
  1759. Matrix.prototype.clone = function () {
  1760. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1761. };
  1762. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1763. translation.x = this.m[12];
  1764. translation.y = this.m[13];
  1765. translation.z = this.m[14];
  1766. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1767. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1768. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1769. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1770. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1771. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1772. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1773. rotation.x = 0;
  1774. rotation.y = 0;
  1775. rotation.z = 0;
  1776. rotation.w = 1;
  1777. return false;
  1778. }
  1779. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1780. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1781. return true;
  1782. };
  1783. // Statics
  1784. Matrix.FromArray = function (array, offset) {
  1785. var result = new Matrix();
  1786. if (!offset) {
  1787. offset = 0;
  1788. }
  1789. Matrix.FromArrayToRef(array, offset, result);
  1790. return result;
  1791. };
  1792. Matrix.FromArrayToRef = function (array, offset, result) {
  1793. for (var index = 0; index < 16; index++) {
  1794. result.m[index] = array[index + offset];
  1795. }
  1796. };
  1797. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = array[index + offset] * scale;
  1800. }
  1801. };
  1802. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1803. result.m[0] = initialM11;
  1804. result.m[1] = initialM12;
  1805. result.m[2] = initialM13;
  1806. result.m[3] = initialM14;
  1807. result.m[4] = initialM21;
  1808. result.m[5] = initialM22;
  1809. result.m[6] = initialM23;
  1810. result.m[7] = initialM24;
  1811. result.m[8] = initialM31;
  1812. result.m[9] = initialM32;
  1813. result.m[10] = initialM33;
  1814. result.m[11] = initialM34;
  1815. result.m[12] = initialM41;
  1816. result.m[13] = initialM42;
  1817. result.m[14] = initialM43;
  1818. result.m[15] = initialM44;
  1819. };
  1820. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1821. var result = new Matrix();
  1822. result.m[0] = initialM11;
  1823. result.m[1] = initialM12;
  1824. result.m[2] = initialM13;
  1825. result.m[3] = initialM14;
  1826. result.m[4] = initialM21;
  1827. result.m[5] = initialM22;
  1828. result.m[6] = initialM23;
  1829. result.m[7] = initialM24;
  1830. result.m[8] = initialM31;
  1831. result.m[9] = initialM32;
  1832. result.m[10] = initialM33;
  1833. result.m[11] = initialM34;
  1834. result.m[12] = initialM41;
  1835. result.m[13] = initialM42;
  1836. result.m[14] = initialM43;
  1837. result.m[15] = initialM44;
  1838. return result;
  1839. };
  1840. Matrix.Compose = function (scale, rotation, translation) {
  1841. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1842. var rotationMatrix = Matrix.Identity();
  1843. rotation.toRotationMatrix(rotationMatrix);
  1844. result = result.multiply(rotationMatrix);
  1845. result.setTranslation(translation);
  1846. return result;
  1847. };
  1848. Matrix.Identity = function () {
  1849. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1850. };
  1851. Matrix.IdentityToRef = function (result) {
  1852. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1853. };
  1854. Matrix.Zero = function () {
  1855. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1856. };
  1857. Matrix.RotationX = function (angle) {
  1858. var result = new Matrix();
  1859. Matrix.RotationXToRef(angle, result);
  1860. return result;
  1861. };
  1862. Matrix.Invert = function (source) {
  1863. var result = new Matrix();
  1864. source.invertToRef(result);
  1865. return result;
  1866. };
  1867. Matrix.RotationXToRef = function (angle, result) {
  1868. var s = Math.sin(angle);
  1869. var c = Math.cos(angle);
  1870. result.m[0] = 1.0;
  1871. result.m[15] = 1.0;
  1872. result.m[5] = c;
  1873. result.m[10] = c;
  1874. result.m[9] = -s;
  1875. result.m[6] = s;
  1876. result.m[1] = 0;
  1877. result.m[2] = 0;
  1878. result.m[3] = 0;
  1879. result.m[4] = 0;
  1880. result.m[7] = 0;
  1881. result.m[8] = 0;
  1882. result.m[11] = 0;
  1883. result.m[12] = 0;
  1884. result.m[13] = 0;
  1885. result.m[14] = 0;
  1886. };
  1887. Matrix.RotationY = function (angle) {
  1888. var result = new Matrix();
  1889. Matrix.RotationYToRef(angle, result);
  1890. return result;
  1891. };
  1892. Matrix.RotationYToRef = function (angle, result) {
  1893. var s = Math.sin(angle);
  1894. var c = Math.cos(angle);
  1895. result.m[5] = 1.0;
  1896. result.m[15] = 1.0;
  1897. result.m[0] = c;
  1898. result.m[2] = -s;
  1899. result.m[8] = s;
  1900. result.m[10] = c;
  1901. result.m[1] = 0;
  1902. result.m[3] = 0;
  1903. result.m[4] = 0;
  1904. result.m[6] = 0;
  1905. result.m[7] = 0;
  1906. result.m[9] = 0;
  1907. result.m[11] = 0;
  1908. result.m[12] = 0;
  1909. result.m[13] = 0;
  1910. result.m[14] = 0;
  1911. };
  1912. Matrix.RotationZ = function (angle) {
  1913. var result = new Matrix();
  1914. Matrix.RotationZToRef(angle, result);
  1915. return result;
  1916. };
  1917. Matrix.RotationZToRef = function (angle, result) {
  1918. var s = Math.sin(angle);
  1919. var c = Math.cos(angle);
  1920. result.m[10] = 1.0;
  1921. result.m[15] = 1.0;
  1922. result.m[0] = c;
  1923. result.m[1] = s;
  1924. result.m[4] = -s;
  1925. result.m[5] = c;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[6] = 0;
  1929. result.m[7] = 0;
  1930. result.m[8] = 0;
  1931. result.m[9] = 0;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. };
  1937. Matrix.RotationAxis = function (axis, angle) {
  1938. var result = Matrix.Zero();
  1939. Matrix.RotationAxisToRef(axis, angle, result);
  1940. return result;
  1941. };
  1942. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1943. var s = Math.sin(-angle);
  1944. var c = Math.cos(-angle);
  1945. var c1 = 1 - c;
  1946. axis.normalize();
  1947. result.m[0] = (axis.x * axis.x) * c1 + c;
  1948. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1949. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1950. result.m[3] = 0.0;
  1951. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1952. result.m[5] = (axis.y * axis.y) * c1 + c;
  1953. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1954. result.m[7] = 0.0;
  1955. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1956. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1957. result.m[10] = (axis.z * axis.z) * c1 + c;
  1958. result.m[11] = 0.0;
  1959. result.m[15] = 1.0;
  1960. };
  1961. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1962. var result = new Matrix();
  1963. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1964. return result;
  1965. };
  1966. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1967. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1968. this._tempQuaternion.toRotationMatrix(result);
  1969. };
  1970. Matrix.Scaling = function (x, y, z) {
  1971. var result = Matrix.Zero();
  1972. Matrix.ScalingToRef(x, y, z, result);
  1973. return result;
  1974. };
  1975. Matrix.ScalingToRef = function (x, y, z, result) {
  1976. result.m[0] = x;
  1977. result.m[1] = 0;
  1978. result.m[2] = 0;
  1979. result.m[3] = 0;
  1980. result.m[4] = 0;
  1981. result.m[5] = y;
  1982. result.m[6] = 0;
  1983. result.m[7] = 0;
  1984. result.m[8] = 0;
  1985. result.m[9] = 0;
  1986. result.m[10] = z;
  1987. result.m[11] = 0;
  1988. result.m[12] = 0;
  1989. result.m[13] = 0;
  1990. result.m[14] = 0;
  1991. result.m[15] = 1.0;
  1992. };
  1993. Matrix.Translation = function (x, y, z) {
  1994. var result = Matrix.Identity();
  1995. Matrix.TranslationToRef(x, y, z, result);
  1996. return result;
  1997. };
  1998. Matrix.TranslationToRef = function (x, y, z, result) {
  1999. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2000. };
  2001. Matrix.Lerp = function (startValue, endValue, gradient) {
  2002. var startScale = new Vector3(0, 0, 0);
  2003. var startRotation = new Quaternion();
  2004. var startTranslation = new Vector3(0, 0, 0);
  2005. startValue.decompose(startScale, startRotation, startTranslation);
  2006. var endScale = new Vector3(0, 0, 0);
  2007. var endRotation = new Quaternion();
  2008. var endTranslation = new Vector3(0, 0, 0);
  2009. endValue.decompose(endScale, endRotation, endTranslation);
  2010. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2011. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2012. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2013. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2014. };
  2015. Matrix.LookAtLH = function (eye, target, up) {
  2016. var result = Matrix.Zero();
  2017. Matrix.LookAtLHToRef(eye, target, up, result);
  2018. return result;
  2019. };
  2020. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2021. // Z axis
  2022. target.subtractToRef(eye, this._zAxis);
  2023. this._zAxis.normalize();
  2024. // X axis
  2025. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2026. if (this._xAxis.lengthSquared() === 0) {
  2027. this._xAxis.x = 1.0;
  2028. }
  2029. else {
  2030. this._xAxis.normalize();
  2031. }
  2032. // Y axis
  2033. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2034. this._yAxis.normalize();
  2035. // Eye angles
  2036. var ex = -Vector3.Dot(this._xAxis, eye);
  2037. var ey = -Vector3.Dot(this._yAxis, eye);
  2038. var ez = -Vector3.Dot(this._zAxis, eye);
  2039. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2040. };
  2041. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2042. var matrix = Matrix.Zero();
  2043. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2044. return matrix;
  2045. };
  2046. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2047. var hw = 2.0 / width;
  2048. var hh = 2.0 / height;
  2049. var id = 1.0 / (zfar - znear);
  2050. var nid = znear / (znear - zfar);
  2051. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2052. };
  2053. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2054. var matrix = Matrix.Zero();
  2055. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2056. return matrix;
  2057. };
  2058. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2059. result.m[0] = 2.0 / (right - left);
  2060. result.m[1] = result.m[2] = result.m[3] = 0;
  2061. result.m[5] = 2.0 / (top - bottom);
  2062. result.m[4] = result.m[6] = result.m[7] = 0;
  2063. result.m[10] = -1.0 / (znear - zfar);
  2064. result.m[8] = result.m[9] = result.m[11] = 0;
  2065. result.m[12] = (left + right) / (left - right);
  2066. result.m[13] = (top + bottom) / (bottom - top);
  2067. result.m[14] = znear / (znear - zfar);
  2068. result.m[15] = 1.0;
  2069. };
  2070. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2071. var matrix = Matrix.Zero();
  2072. matrix.m[0] = (2.0 * znear) / width;
  2073. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2074. matrix.m[5] = (2.0 * znear) / height;
  2075. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2076. matrix.m[10] = -zfar / (znear - zfar);
  2077. matrix.m[8] = matrix.m[9] = 0.0;
  2078. matrix.m[11] = 1.0;
  2079. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2080. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2081. return matrix;
  2082. };
  2083. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2084. var matrix = Matrix.Zero();
  2085. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2086. return matrix;
  2087. };
  2088. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2089. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2090. var tan = 1.0 / (Math.tan(fov * 0.5));
  2091. if (isVerticalFovFixed) {
  2092. result.m[0] = tan / aspect;
  2093. }
  2094. else {
  2095. result.m[0] = tan;
  2096. }
  2097. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2098. if (isVerticalFovFixed) {
  2099. result.m[5] = tan;
  2100. }
  2101. else {
  2102. result.m[5] = tan * aspect;
  2103. }
  2104. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2105. result.m[8] = result.m[9] = 0.0;
  2106. result.m[10] = -zfar / (znear - zfar);
  2107. result.m[11] = 1.0;
  2108. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2109. result.m[14] = (znear * zfar) / (znear - zfar);
  2110. };
  2111. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2112. var cw = viewport.width;
  2113. var ch = viewport.height;
  2114. var cx = viewport.x;
  2115. var cy = viewport.y;
  2116. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2117. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2118. };
  2119. Matrix.GetAsMatrix2x2 = function (matrix) {
  2120. return new Float32Array([
  2121. matrix.m[0], matrix.m[1],
  2122. matrix.m[4], matrix.m[5]
  2123. ]);
  2124. };
  2125. Matrix.GetAsMatrix3x3 = function (matrix) {
  2126. return new Float32Array([
  2127. matrix.m[0], matrix.m[1], matrix.m[2],
  2128. matrix.m[4], matrix.m[5], matrix.m[6],
  2129. matrix.m[8], matrix.m[9], matrix.m[10]
  2130. ]);
  2131. };
  2132. Matrix.Transpose = function (matrix) {
  2133. var result = new Matrix();
  2134. result.m[0] = matrix.m[0];
  2135. result.m[1] = matrix.m[4];
  2136. result.m[2] = matrix.m[8];
  2137. result.m[3] = matrix.m[12];
  2138. result.m[4] = matrix.m[1];
  2139. result.m[5] = matrix.m[5];
  2140. result.m[6] = matrix.m[9];
  2141. result.m[7] = matrix.m[13];
  2142. result.m[8] = matrix.m[2];
  2143. result.m[9] = matrix.m[6];
  2144. result.m[10] = matrix.m[10];
  2145. result.m[11] = matrix.m[14];
  2146. result.m[12] = matrix.m[3];
  2147. result.m[13] = matrix.m[7];
  2148. result.m[14] = matrix.m[11];
  2149. result.m[15] = matrix.m[15];
  2150. return result;
  2151. };
  2152. Matrix.Reflection = function (plane) {
  2153. var matrix = new Matrix();
  2154. Matrix.ReflectionToRef(plane, matrix);
  2155. return matrix;
  2156. };
  2157. Matrix.ReflectionToRef = function (plane, result) {
  2158. plane.normalize();
  2159. var x = plane.normal.x;
  2160. var y = plane.normal.y;
  2161. var z = plane.normal.z;
  2162. var temp = -2 * x;
  2163. var temp2 = -2 * y;
  2164. var temp3 = -2 * z;
  2165. result.m[0] = (temp * x) + 1;
  2166. result.m[1] = temp2 * x;
  2167. result.m[2] = temp3 * x;
  2168. result.m[3] = 0.0;
  2169. result.m[4] = temp * y;
  2170. result.m[5] = (temp2 * y) + 1;
  2171. result.m[6] = temp3 * y;
  2172. result.m[7] = 0.0;
  2173. result.m[8] = temp * z;
  2174. result.m[9] = temp2 * z;
  2175. result.m[10] = (temp3 * z) + 1;
  2176. result.m[11] = 0.0;
  2177. result.m[12] = temp * plane.d;
  2178. result.m[13] = temp2 * plane.d;
  2179. result.m[14] = temp3 * plane.d;
  2180. result.m[15] = 1.0;
  2181. };
  2182. Matrix._tempQuaternion = new Quaternion();
  2183. Matrix._xAxis = Vector3.Zero();
  2184. Matrix._yAxis = Vector3.Zero();
  2185. Matrix._zAxis = Vector3.Zero();
  2186. return Matrix;
  2187. })();
  2188. BABYLON.Matrix = Matrix;
  2189. var Plane = (function () {
  2190. function Plane(a, b, c, d) {
  2191. this.normal = new Vector3(a, b, c);
  2192. this.d = d;
  2193. }
  2194. Plane.prototype.asArray = function () {
  2195. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2196. };
  2197. // Methods
  2198. Plane.prototype.clone = function () {
  2199. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2200. };
  2201. Plane.prototype.normalize = function () {
  2202. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2203. var magnitude = 0;
  2204. if (norm !== 0) {
  2205. magnitude = 1.0 / norm;
  2206. }
  2207. this.normal.x *= magnitude;
  2208. this.normal.y *= magnitude;
  2209. this.normal.z *= magnitude;
  2210. this.d *= magnitude;
  2211. return this;
  2212. };
  2213. Plane.prototype.transform = function (transformation) {
  2214. var transposedMatrix = Matrix.Transpose(transformation);
  2215. var x = this.normal.x;
  2216. var y = this.normal.y;
  2217. var z = this.normal.z;
  2218. var d = this.d;
  2219. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2220. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2221. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2222. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2223. return new Plane(normalX, normalY, normalZ, finalD);
  2224. };
  2225. Plane.prototype.dotCoordinate = function (point) {
  2226. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2227. };
  2228. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2229. var x1 = point2.x - point1.x;
  2230. var y1 = point2.y - point1.y;
  2231. var z1 = point2.z - point1.z;
  2232. var x2 = point3.x - point1.x;
  2233. var y2 = point3.y - point1.y;
  2234. var z2 = point3.z - point1.z;
  2235. var yz = (y1 * z2) - (z1 * y2);
  2236. var xz = (z1 * x2) - (x1 * z2);
  2237. var xy = (x1 * y2) - (y1 * x2);
  2238. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2239. var invPyth;
  2240. if (pyth !== 0) {
  2241. invPyth = 1.0 / pyth;
  2242. }
  2243. else {
  2244. invPyth = 0;
  2245. }
  2246. this.normal.x = yz * invPyth;
  2247. this.normal.y = xz * invPyth;
  2248. this.normal.z = xy * invPyth;
  2249. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2250. return this;
  2251. };
  2252. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2253. var dot = Vector3.Dot(this.normal, direction);
  2254. return (dot <= epsilon);
  2255. };
  2256. Plane.prototype.signedDistanceTo = function (point) {
  2257. return Vector3.Dot(point, this.normal) + this.d;
  2258. };
  2259. // Statics
  2260. Plane.FromArray = function (array) {
  2261. return new Plane(array[0], array[1], array[2], array[3]);
  2262. };
  2263. Plane.FromPoints = function (point1, point2, point3) {
  2264. var result = new Plane(0, 0, 0, 0);
  2265. result.copyFromPoints(point1, point2, point3);
  2266. return result;
  2267. };
  2268. Plane.FromPositionAndNormal = function (origin, normal) {
  2269. var result = new Plane(0, 0, 0, 0);
  2270. normal.normalize();
  2271. result.normal = normal;
  2272. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2273. return result;
  2274. };
  2275. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2276. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2277. return Vector3.Dot(point, normal) + d;
  2278. };
  2279. return Plane;
  2280. })();
  2281. BABYLON.Plane = Plane;
  2282. var Viewport = (function () {
  2283. function Viewport(x, y, width, height) {
  2284. this.x = x;
  2285. this.y = y;
  2286. this.width = width;
  2287. this.height = height;
  2288. }
  2289. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2290. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2291. };
  2292. return Viewport;
  2293. })();
  2294. BABYLON.Viewport = Viewport;
  2295. var Frustum = (function () {
  2296. function Frustum() {
  2297. }
  2298. Frustum.GetPlanes = function (transform) {
  2299. var frustumPlanes = [];
  2300. for (var index = 0; index < 6; index++) {
  2301. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2302. }
  2303. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2304. return frustumPlanes;
  2305. };
  2306. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2307. // Near
  2308. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2309. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2310. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2311. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2312. frustumPlanes[0].normalize();
  2313. // Far
  2314. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2315. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2316. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2317. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2318. frustumPlanes[1].normalize();
  2319. // Left
  2320. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2321. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2322. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2323. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2324. frustumPlanes[2].normalize();
  2325. // Right
  2326. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2327. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2328. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2329. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2330. frustumPlanes[3].normalize();
  2331. // Top
  2332. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2333. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2334. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2335. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2336. frustumPlanes[4].normalize();
  2337. // Bottom
  2338. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2339. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2340. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2341. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2342. frustumPlanes[5].normalize();
  2343. };
  2344. return Frustum;
  2345. })();
  2346. BABYLON.Frustum = Frustum;
  2347. (function (Space) {
  2348. Space[Space["LOCAL"] = 0] = "LOCAL";
  2349. Space[Space["WORLD"] = 1] = "WORLD";
  2350. })(BABYLON.Space || (BABYLON.Space = {}));
  2351. var Space = BABYLON.Space;
  2352. var Axis = (function () {
  2353. function Axis() {
  2354. }
  2355. Axis.X = new Vector3(1, 0, 0);
  2356. Axis.Y = new Vector3(0, 1, 0);
  2357. Axis.Z = new Vector3(0, 0, 1);
  2358. return Axis;
  2359. })();
  2360. BABYLON.Axis = Axis;
  2361. ;
  2362. var BezierCurve = (function () {
  2363. function BezierCurve() {
  2364. }
  2365. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2366. // Extract X (which is equal to time here)
  2367. var f0 = 1 - 3 * x2 + 3 * x1;
  2368. var f1 = 3 * x2 - 6 * x1;
  2369. var f2 = 3 * x1;
  2370. var refinedT = t;
  2371. for (var i = 0; i < 5; i++) {
  2372. var refinedT2 = refinedT * refinedT;
  2373. var refinedT3 = refinedT2 * refinedT;
  2374. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2375. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2376. refinedT -= (x - t) * slope;
  2377. refinedT = Math.min(1, Math.max(0, refinedT));
  2378. }
  2379. // Resolve cubic bezier for the given x
  2380. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2381. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2382. Math.pow(refinedT, 3);
  2383. };
  2384. return BezierCurve;
  2385. })();
  2386. BABYLON.BezierCurve = BezierCurve;
  2387. (function (Orientation) {
  2388. Orientation[Orientation["CW"] = 0] = "CW";
  2389. Orientation[Orientation["CCW"] = 1] = "CCW";
  2390. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2391. var Orientation = BABYLON.Orientation;
  2392. var Angle = (function () {
  2393. function Angle(radians) {
  2394. var _this = this;
  2395. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2396. this.radians = function () { return _this._radians; };
  2397. this._radians = radians;
  2398. if (this._radians < 0)
  2399. this._radians += (2 * Math.PI);
  2400. }
  2401. Angle.BetweenTwoPoints = function (a, b) {
  2402. var delta = b.subtract(a);
  2403. var theta = Math.atan2(delta.y, delta.x);
  2404. return new Angle(theta);
  2405. };
  2406. Angle.FromRadians = function (radians) {
  2407. return new Angle(radians);
  2408. };
  2409. Angle.FromDegrees = function (degrees) {
  2410. return new Angle(degrees * Math.PI / 180);
  2411. };
  2412. return Angle;
  2413. })();
  2414. BABYLON.Angle = Angle;
  2415. var Arc2 = (function () {
  2416. function Arc2(startPoint, midPoint, endPoint) {
  2417. this.startPoint = startPoint;
  2418. this.midPoint = midPoint;
  2419. this.endPoint = endPoint;
  2420. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2421. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2422. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2423. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2424. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2425. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2426. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2427. var a1 = this.startAngle.degrees();
  2428. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2429. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2430. // angles correction
  2431. if (a2 - a1 > +180.0)
  2432. a2 -= 360.0;
  2433. if (a2 - a1 < -180.0)
  2434. a2 += 360.0;
  2435. if (a3 - a2 > +180.0)
  2436. a3 -= 360.0;
  2437. if (a3 - a2 < -180.0)
  2438. a3 += 360.0;
  2439. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2440. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2441. }
  2442. return Arc2;
  2443. })();
  2444. BABYLON.Arc2 = Arc2;
  2445. var Path2 = (function () {
  2446. function Path2(x, y) {
  2447. this._points = new Array();
  2448. this._length = 0;
  2449. this.closed = false;
  2450. this._points.push(new Vector2(x, y));
  2451. }
  2452. Path2.prototype.addLineTo = function (x, y) {
  2453. if (closed) {
  2454. //Tools.Error("cannot add lines to closed paths");
  2455. return this;
  2456. }
  2457. var newPoint = new Vector2(x, y);
  2458. var previousPoint = this._points[this._points.length - 1];
  2459. this._points.push(newPoint);
  2460. this._length += newPoint.subtract(previousPoint).length();
  2461. return this;
  2462. };
  2463. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2464. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2465. if (closed) {
  2466. //Tools.Error("cannot add arcs to closed paths");
  2467. return this;
  2468. }
  2469. var startPoint = this._points[this._points.length - 1];
  2470. var midPoint = new Vector2(midX, midY);
  2471. var endPoint = new Vector2(endX, endY);
  2472. var arc = new Arc2(startPoint, midPoint, endPoint);
  2473. var increment = arc.angle.radians() / numberOfSegments;
  2474. if (arc.orientation === Orientation.CW)
  2475. increment *= -1;
  2476. var currentAngle = arc.startAngle.radians() + increment;
  2477. for (var i = 0; i < numberOfSegments; i++) {
  2478. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2479. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2480. this.addLineTo(x, y);
  2481. currentAngle += increment;
  2482. }
  2483. return this;
  2484. };
  2485. Path2.prototype.close = function () {
  2486. this.closed = true;
  2487. return this;
  2488. };
  2489. Path2.prototype.length = function () {
  2490. var result = this._length;
  2491. if (!this.closed) {
  2492. var lastPoint = this._points[this._points.length - 1];
  2493. var firstPoint = this._points[0];
  2494. result += (firstPoint.subtract(lastPoint).length());
  2495. }
  2496. return result;
  2497. };
  2498. Path2.prototype.getPoints = function () {
  2499. return this._points;
  2500. };
  2501. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2502. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2503. //Tools.Error("normalized length position should be between 0 and 1.");
  2504. return Vector2.Zero();
  2505. }
  2506. var lengthPosition = normalizedLengthPosition * this.length();
  2507. var previousOffset = 0;
  2508. for (var i = 0; i < this._points.length; i++) {
  2509. var j = (i + 1) % this._points.length;
  2510. var a = this._points[i];
  2511. var b = this._points[j];
  2512. var bToA = b.subtract(a);
  2513. var nextOffset = (bToA.length() + previousOffset);
  2514. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2515. var dir = bToA.normalize();
  2516. var localOffset = lengthPosition - previousOffset;
  2517. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2518. }
  2519. previousOffset = nextOffset;
  2520. }
  2521. //Tools.Error("internal error");
  2522. return Vector2.Zero();
  2523. };
  2524. Path2.StartingAt = function (x, y) {
  2525. return new Path2(x, y);
  2526. };
  2527. return Path2;
  2528. })();
  2529. BABYLON.Path2 = Path2;
  2530. var Path3D = (function () {
  2531. /**
  2532. * new Path3D(path, normal, raw)
  2533. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2534. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2535. * path : an array of Vector3, the curve axis of the Path3D
  2536. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2537. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2538. */
  2539. function Path3D(path, firstNormal, raw) {
  2540. this.path = path;
  2541. this._curve = new Array();
  2542. this._distances = new Array();
  2543. this._tangents = new Array();
  2544. this._normals = new Array();
  2545. this._binormals = new Array();
  2546. for (var p = 0; p < path.length; p++) {
  2547. this._curve[p] = path[p].clone(); // hard copy
  2548. }
  2549. this._raw = raw || false;
  2550. this._compute(firstNormal);
  2551. }
  2552. /**
  2553. * Returns the Path3D array of successive Vector3 designing its curve.
  2554. */
  2555. Path3D.prototype.getCurve = function () {
  2556. return this._curve;
  2557. };
  2558. /**
  2559. * Returns an array populated with tangent vectors on each Path3D curve point.
  2560. */
  2561. Path3D.prototype.getTangents = function () {
  2562. return this._tangents;
  2563. };
  2564. /**
  2565. * Returns an array populated with normal vectors on each Path3D curve point.
  2566. */
  2567. Path3D.prototype.getNormals = function () {
  2568. return this._normals;
  2569. };
  2570. /**
  2571. * Returns an array populated with binormal vectors on each Path3D curve point.
  2572. */
  2573. Path3D.prototype.getBinormals = function () {
  2574. return this._binormals;
  2575. };
  2576. /**
  2577. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2578. */
  2579. Path3D.prototype.getDistances = function () {
  2580. return this._distances;
  2581. };
  2582. /**
  2583. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2584. * Returns the same object updated.
  2585. */
  2586. Path3D.prototype.update = function (path, firstNormal) {
  2587. for (var p = 0; p < path.length; p++) {
  2588. this._curve[p].x = path[p].x;
  2589. this._curve[p].y = path[p].y;
  2590. this._curve[p].z = path[p].z;
  2591. }
  2592. this._compute(firstNormal);
  2593. return this;
  2594. };
  2595. // private function compute() : computes tangents, normals and binormals
  2596. Path3D.prototype._compute = function (firstNormal) {
  2597. var l = this._curve.length;
  2598. // first and last tangents
  2599. this._tangents[0] = this._getFirstNonNullVector(0);
  2600. if (!this._raw) {
  2601. this._tangents[0].normalize();
  2602. }
  2603. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2604. if (!this._raw) {
  2605. this._tangents[l - 1].normalize();
  2606. }
  2607. // normals and binormals at first point : arbitrary vector with _normalVector()
  2608. var tg0 = this._tangents[0];
  2609. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2610. this._normals[0] = pp0;
  2611. if (!this._raw) {
  2612. this._normals[0].normalize();
  2613. }
  2614. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2615. if (!this._raw) {
  2616. this._binormals[0].normalize();
  2617. }
  2618. this._distances[0] = 0;
  2619. // normals and binormals : next points
  2620. var prev; // previous vector (segment)
  2621. var cur; // current vector (segment)
  2622. var curTang; // current tangent
  2623. // previous normal
  2624. var prevBinor; // previous binormal
  2625. for (var i = 1; i < l; i++) {
  2626. // tangents
  2627. prev = this._getLastNonNullVector(i);
  2628. if (i < l - 1) {
  2629. cur = this._getFirstNonNullVector(i);
  2630. this._tangents[i] = prev.add(cur);
  2631. this._tangents[i].normalize();
  2632. }
  2633. this._distances[i] = this._distances[i - 1] + prev.length();
  2634. // normals and binormals
  2635. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2636. curTang = this._tangents[i];
  2637. prevBinor = this._binormals[i - 1];
  2638. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2639. if (!this._raw) {
  2640. this._normals[i].normalize();
  2641. }
  2642. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2643. if (!this._raw) {
  2644. this._binormals[i].normalize();
  2645. }
  2646. }
  2647. };
  2648. // private function getFirstNonNullVector(index)
  2649. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2650. Path3D.prototype._getFirstNonNullVector = function (index) {
  2651. var i = 1;
  2652. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2653. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2654. i++;
  2655. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2656. }
  2657. return nNVector;
  2658. };
  2659. // private function getLastNonNullVector(index)
  2660. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2661. Path3D.prototype._getLastNonNullVector = function (index) {
  2662. var i = 1;
  2663. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2664. while (nLVector.length() === 0 && index > i + 1) {
  2665. i++;
  2666. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2667. }
  2668. return nLVector;
  2669. };
  2670. // private function normalVector(v0, vt, va) :
  2671. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2672. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2673. Path3D.prototype._normalVector = function (v0, vt, va) {
  2674. var normal0;
  2675. if (va === undefined || va === null) {
  2676. var point;
  2677. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2678. point = new Vector3(0, -1, 0);
  2679. }
  2680. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2681. point = new Vector3(1, 0, 0);
  2682. }
  2683. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2684. point = new Vector3(0, 0, 1);
  2685. }
  2686. normal0 = Vector3.Cross(vt, point);
  2687. }
  2688. else {
  2689. normal0 = Vector3.Cross(vt, va);
  2690. Vector3.CrossToRef(normal0, vt, normal0);
  2691. }
  2692. normal0.normalize();
  2693. return normal0;
  2694. };
  2695. return Path3D;
  2696. })();
  2697. BABYLON.Path3D = Path3D;
  2698. var Curve3 = (function () {
  2699. /**
  2700. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2701. * A Curve3 is designed from a series of successive Vector3.
  2702. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2703. */
  2704. function Curve3(points) {
  2705. this._length = 0;
  2706. this._points = points;
  2707. this._length = this._computeLength(points);
  2708. }
  2709. /**
  2710. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2711. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2712. * @param v1 (Vector3) the control point
  2713. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2714. * @param nbPoints (integer) the wanted number of points in the curve
  2715. */
  2716. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2717. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2718. var bez = new Array();
  2719. var equation = function (t, val0, val1, val2) {
  2720. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2721. return res;
  2722. };
  2723. for (var i = 0; i <= nbPoints; i++) {
  2724. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2725. }
  2726. return new Curve3(bez);
  2727. };
  2728. /**
  2729. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2730. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2731. * @param v1 (Vector3) the first control point
  2732. * @param v2 (Vector3) the second control point
  2733. * @param v3 (Vector3) the end point of the Cubic Bezier
  2734. * @param nbPoints (integer) the wanted number of points in the curve
  2735. */
  2736. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2737. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2738. var bez = new Array();
  2739. var equation = function (t, val0, val1, val2, val3) {
  2740. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2741. return res;
  2742. };
  2743. for (var i = 0; i <= nbPoints; i++) {
  2744. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2745. }
  2746. return new Curve3(bez);
  2747. };
  2748. /**
  2749. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2750. * @param p1 (Vector3) the origin point of the Hermite Spline
  2751. * @param t1 (Vector3) the tangent vector at the origin point
  2752. * @param p2 (Vector3) the end point of the Hermite Spline
  2753. * @param t2 (Vector3) the tangent vector at the end point
  2754. * @param nbPoints (integer) the wanted number of points in the curve
  2755. */
  2756. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2757. var hermite = new Array();
  2758. var step = 1 / nbPoints;
  2759. for (var i = 0; i <= nbPoints; i++) {
  2760. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2761. }
  2762. return new Curve3(hermite);
  2763. };
  2764. /**
  2765. * Returns the Curve3 stored array of successive Vector3
  2766. */
  2767. Curve3.prototype.getPoints = function () {
  2768. return this._points;
  2769. };
  2770. /**
  2771. * Returns the computed length (float) of the curve.
  2772. */
  2773. Curve3.prototype.length = function () {
  2774. return this._length;
  2775. };
  2776. /**
  2777. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2778. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2779. * curveA and curveB keep unchanged.
  2780. */
  2781. Curve3.prototype.continue = function (curve) {
  2782. var lastPoint = this._points[this._points.length - 1];
  2783. var continuedPoints = this._points.slice();
  2784. var curvePoints = curve.getPoints();
  2785. for (var i = 1; i < curvePoints.length; i++) {
  2786. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2787. }
  2788. var continuedCurve = new Curve3(continuedPoints);
  2789. return continuedCurve;
  2790. };
  2791. Curve3.prototype._computeLength = function (path) {
  2792. var l = 0;
  2793. for (var i = 1; i < path.length; i++) {
  2794. l += (path[i].subtract(path[i - 1])).length();
  2795. }
  2796. return l;
  2797. };
  2798. return Curve3;
  2799. })();
  2800. BABYLON.Curve3 = Curve3;
  2801. // SphericalHarmonics
  2802. var SphericalHarmonics = (function () {
  2803. function SphericalHarmonics() {
  2804. this.L00 = Vector3.Zero();
  2805. this.L1_1 = Vector3.Zero();
  2806. this.L10 = Vector3.Zero();
  2807. this.L11 = Vector3.Zero();
  2808. this.L2_2 = Vector3.Zero();
  2809. this.L2_1 = Vector3.Zero();
  2810. this.L20 = Vector3.Zero();
  2811. this.L21 = Vector3.Zero();
  2812. this.L22 = Vector3.Zero();
  2813. }
  2814. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2815. var colorVector = new Vector3(color.r, color.g, color.b);
  2816. var c = colorVector.scale(deltaSolidAngle);
  2817. this.L00 = this.L00.add(c.scale(0.282095));
  2818. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2819. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2820. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2821. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2822. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2823. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2824. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2825. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2826. };
  2827. SphericalHarmonics.prototype.scale = function (scale) {
  2828. this.L00 = this.L00.scale(scale);
  2829. this.L1_1 = this.L1_1.scale(scale);
  2830. this.L10 = this.L10.scale(scale);
  2831. this.L11 = this.L11.scale(scale);
  2832. this.L2_2 = this.L2_2.scale(scale);
  2833. this.L2_1 = this.L2_1.scale(scale);
  2834. this.L20 = this.L20.scale(scale);
  2835. this.L21 = this.L21.scale(scale);
  2836. this.L22 = this.L22.scale(scale);
  2837. };
  2838. return SphericalHarmonics;
  2839. })();
  2840. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2841. // SphericalPolynomial
  2842. var SphericalPolynomial = (function () {
  2843. function SphericalPolynomial() {
  2844. this.x = Vector3.Zero();
  2845. this.y = Vector3.Zero();
  2846. this.z = Vector3.Zero();
  2847. this.xx = Vector3.Zero();
  2848. this.yy = Vector3.Zero();
  2849. this.zz = Vector3.Zero();
  2850. this.xy = Vector3.Zero();
  2851. this.yz = Vector3.Zero();
  2852. this.zx = Vector3.Zero();
  2853. }
  2854. SphericalPolynomial.prototype.addAmbient = function (color) {
  2855. var colorVector = new Vector3(color.r, color.g, color.b);
  2856. this.xx = this.xx.add(colorVector);
  2857. this.yy = this.yy.add(colorVector);
  2858. this.zz = this.zz.add(colorVector);
  2859. };
  2860. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2861. var result = new SphericalPolynomial();
  2862. result.x = harmonics.L11.scale(1.02333);
  2863. result.y = harmonics.L1_1.scale(1.02333);
  2864. result.z = harmonics.L10.scale(1.02333);
  2865. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2866. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2867. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2868. result.yz = harmonics.L2_1.scale(0.858086);
  2869. result.zx = harmonics.L21.scale(0.858086);
  2870. result.xy = harmonics.L2_2.scale(0.858086);
  2871. return result;
  2872. };
  2873. return SphericalPolynomial;
  2874. })();
  2875. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2876. // Vertex formats
  2877. var PositionNormalVertex = (function () {
  2878. function PositionNormalVertex(position, normal) {
  2879. if (position === void 0) { position = Vector3.Zero(); }
  2880. if (normal === void 0) { normal = Vector3.Up(); }
  2881. this.position = position;
  2882. this.normal = normal;
  2883. }
  2884. PositionNormalVertex.prototype.clone = function () {
  2885. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2886. };
  2887. return PositionNormalVertex;
  2888. })();
  2889. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2890. var PositionNormalTextureVertex = (function () {
  2891. function PositionNormalTextureVertex(position, normal, uv) {
  2892. if (position === void 0) { position = Vector3.Zero(); }
  2893. if (normal === void 0) { normal = Vector3.Up(); }
  2894. if (uv === void 0) { uv = Vector2.Zero(); }
  2895. this.position = position;
  2896. this.normal = normal;
  2897. this.uv = uv;
  2898. }
  2899. PositionNormalTextureVertex.prototype.clone = function () {
  2900. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2901. };
  2902. return PositionNormalTextureVertex;
  2903. })();
  2904. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2905. // Temporary pre-allocated objects for engine internal use
  2906. // usage in any internal function :
  2907. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2908. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2909. var Tmp = (function () {
  2910. function Tmp() {
  2911. }
  2912. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2913. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2914. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2915. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2916. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2917. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2918. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2919. Matrix.Zero(), Matrix.Zero(),
  2920. Matrix.Zero(), Matrix.Zero(),
  2921. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2922. return Tmp;
  2923. })();
  2924. BABYLON.Tmp = Tmp;
  2925. })(BABYLON || (BABYLON = {}));
  2926. var BABYLON;
  2927. (function (BABYLON) {
  2928. function generateSerializableMember(type, sourceName) {
  2929. return function (target, propertyKey) {
  2930. if (!target.__serializableMembers) {
  2931. target.__serializableMembers = {};
  2932. }
  2933. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2934. };
  2935. }
  2936. function serialize(sourceName) {
  2937. return generateSerializableMember(0, sourceName); // value member
  2938. }
  2939. BABYLON.serialize = serialize;
  2940. function serializeAsTexture(sourceName) {
  2941. return generateSerializableMember(1, sourceName); // texture member
  2942. }
  2943. BABYLON.serializeAsTexture = serializeAsTexture;
  2944. function serializeAsColor3(sourceName) {
  2945. return generateSerializableMember(2, sourceName); // color3 member
  2946. }
  2947. BABYLON.serializeAsColor3 = serializeAsColor3;
  2948. function serializeAsFresnelParameters(sourceName) {
  2949. return generateSerializableMember(3, sourceName); // fresnel parameters member
  2950. }
  2951. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  2952. function serializeAsVector2(sourceName) {
  2953. return generateSerializableMember(4, sourceName); // vector2 member
  2954. }
  2955. BABYLON.serializeAsVector2 = serializeAsVector2;
  2956. function serializeAsVector3(sourceName) {
  2957. return generateSerializableMember(5, sourceName); // vector3 member
  2958. }
  2959. BABYLON.serializeAsVector3 = serializeAsVector3;
  2960. function serializeAsMeshReference(sourceName) {
  2961. return generateSerializableMember(6, sourceName); // mesh reference member
  2962. }
  2963. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  2964. var SerializationHelper = (function () {
  2965. function SerializationHelper() {
  2966. }
  2967. SerializationHelper.Serialize = function (entity, serializationObject) {
  2968. if (!serializationObject) {
  2969. serializationObject = {};
  2970. }
  2971. // Tags
  2972. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  2973. // Properties
  2974. for (var property in entity.__serializableMembers) {
  2975. var propertyDescriptor = entity.__serializableMembers[property];
  2976. var targetPropertyName = propertyDescriptor.sourceName || property;
  2977. var propertyType = propertyDescriptor.type;
  2978. var sourceProperty = entity[property];
  2979. if (sourceProperty !== undefined && sourceProperty !== null) {
  2980. switch (propertyType) {
  2981. case 0:
  2982. serializationObject[targetPropertyName] = sourceProperty;
  2983. break;
  2984. case 1:
  2985. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2986. break;
  2987. case 2:
  2988. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2989. break;
  2990. case 3:
  2991. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2992. break;
  2993. case 4:
  2994. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2995. break;
  2996. case 5:
  2997. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2998. break;
  2999. case 6:
  3000. serializationObject[targetPropertyName] = sourceProperty.id;
  3001. break;
  3002. }
  3003. }
  3004. }
  3005. return serializationObject;
  3006. };
  3007. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3008. var destination = creationFunction();
  3009. // Tags
  3010. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3011. // Properties
  3012. for (var property in destination.__serializableMembers) {
  3013. var propertyDescriptor = destination.__serializableMembers[property];
  3014. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3015. var propertyType = propertyDescriptor.type;
  3016. if (sourceProperty !== undefined && sourceProperty !== null) {
  3017. switch (propertyType) {
  3018. case 0:
  3019. destination[property] = sourceProperty;
  3020. break;
  3021. case 1:
  3022. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3023. break;
  3024. case 2:
  3025. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3026. break;
  3027. case 3:
  3028. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3029. break;
  3030. case 4:
  3031. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3032. break;
  3033. case 5:
  3034. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3035. break;
  3036. case 6:
  3037. destination[property] = scene.getLastMeshByID(sourceProperty);
  3038. break;
  3039. }
  3040. }
  3041. }
  3042. return destination;
  3043. };
  3044. SerializationHelper.Clone = function (creationFunction, source) {
  3045. var destination = creationFunction();
  3046. // Tags
  3047. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3048. // Properties
  3049. for (var property in destination.__serializableMembers) {
  3050. var propertyDescriptor = destination.__serializableMembers[property];
  3051. var sourceProperty = source[property];
  3052. var propertyType = propertyDescriptor.type;
  3053. if (sourceProperty !== undefined && sourceProperty !== null) {
  3054. switch (propertyType) {
  3055. case 0: // Value
  3056. case 6:
  3057. destination[property] = sourceProperty;
  3058. break;
  3059. case 1: // Texture
  3060. case 2: // Color3
  3061. case 3: // FresnelParameters
  3062. case 4: // Vector2
  3063. case 5:
  3064. destination[property] = sourceProperty.clone();
  3065. break;
  3066. }
  3067. }
  3068. }
  3069. return destination;
  3070. };
  3071. return SerializationHelper;
  3072. })();
  3073. BABYLON.SerializationHelper = SerializationHelper;
  3074. })(BABYLON || (BABYLON = {}));
  3075. var BABYLON;
  3076. (function (BABYLON) {
  3077. var Database = (function () {
  3078. function Database(urlToScene, callbackManifestChecked) {
  3079. // Handling various flavors of prefixed version of IndexedDB
  3080. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3081. this.callbackManifestChecked = callbackManifestChecked;
  3082. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3083. this.db = null;
  3084. this.enableSceneOffline = false;
  3085. this.enableTexturesOffline = false;
  3086. this.manifestVersionFound = 0;
  3087. this.mustUpdateRessources = false;
  3088. this.hasReachedQuota = false;
  3089. if (!Database.IDBStorageEnabled) {
  3090. this.callbackManifestChecked(true);
  3091. }
  3092. else {
  3093. this.checkManifestFile();
  3094. }
  3095. }
  3096. Database.prototype.checkManifestFile = function () {
  3097. var _this = this;
  3098. function noManifestFile() {
  3099. that.enableSceneOffline = false;
  3100. that.enableTexturesOffline = false;
  3101. that.callbackManifestChecked(false);
  3102. }
  3103. var that = this;
  3104. var timeStampUsed = false;
  3105. var manifestURL = this.currentSceneUrl + ".manifest";
  3106. var xhr = new XMLHttpRequest();
  3107. if (navigator.onLine) {
  3108. // Adding a timestamp to by-pass browsers' cache
  3109. timeStampUsed = true;
  3110. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3111. }
  3112. xhr.open("GET", manifestURL, true);
  3113. xhr.addEventListener("load", function () {
  3114. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3115. try {
  3116. var manifestFile = JSON.parse(xhr.response);
  3117. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3118. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3119. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3120. _this.manifestVersionFound = manifestFile.version;
  3121. }
  3122. if (_this.callbackManifestChecked) {
  3123. _this.callbackManifestChecked(true);
  3124. }
  3125. }
  3126. catch (ex) {
  3127. noManifestFile();
  3128. }
  3129. }
  3130. else {
  3131. noManifestFile();
  3132. }
  3133. }, false);
  3134. xhr.addEventListener("error", function (event) {
  3135. if (timeStampUsed) {
  3136. timeStampUsed = false;
  3137. // Let's retry without the timeStamp
  3138. // It could fail when coupled with HTML5 Offline API
  3139. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3140. xhr.open("GET", retryManifestURL, true);
  3141. xhr.send();
  3142. }
  3143. else {
  3144. noManifestFile();
  3145. }
  3146. }, false);
  3147. try {
  3148. xhr.send();
  3149. }
  3150. catch (ex) {
  3151. BABYLON.Tools.Error("Error on XHR send request.");
  3152. that.callbackManifestChecked(false);
  3153. }
  3154. };
  3155. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3156. var _this = this;
  3157. function handleError() {
  3158. that.isSupported = false;
  3159. if (errorCallback)
  3160. errorCallback();
  3161. }
  3162. var that = this;
  3163. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3164. // Your browser doesn't support IndexedDB
  3165. this.isSupported = false;
  3166. if (errorCallback)
  3167. errorCallback();
  3168. }
  3169. else {
  3170. // If the DB hasn't been opened or created yet
  3171. if (!this.db) {
  3172. this.hasReachedQuota = false;
  3173. this.isSupported = true;
  3174. var request = this.idbFactory.open("babylonjs", 1);
  3175. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3176. request.onerror = function (event) {
  3177. handleError();
  3178. };
  3179. // executes when a version change transaction cannot complete due to other active transactions
  3180. request.onblocked = function (event) {
  3181. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3182. handleError();
  3183. };
  3184. // DB has been opened successfully
  3185. request.onsuccess = function (event) {
  3186. _this.db = request.result;
  3187. successCallback();
  3188. };
  3189. // Initialization of the DB. Creating Scenes & Textures stores
  3190. request.onupgradeneeded = function (event) {
  3191. _this.db = (event.target).result;
  3192. try {
  3193. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3194. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3195. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3196. }
  3197. catch (ex) {
  3198. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3199. handleError();
  3200. }
  3201. };
  3202. }
  3203. else {
  3204. if (successCallback)
  3205. successCallback();
  3206. }
  3207. }
  3208. };
  3209. Database.prototype.loadImageFromDB = function (url, image) {
  3210. var _this = this;
  3211. var completeURL = Database.ReturnFullUrlLocation(url);
  3212. var saveAndLoadImage = function () {
  3213. if (!_this.hasReachedQuota && _this.db !== null) {
  3214. // the texture is not yet in the DB, let's try to save it
  3215. _this._saveImageIntoDBAsync(completeURL, image);
  3216. }
  3217. else {
  3218. image.src = url;
  3219. }
  3220. };
  3221. if (!this.mustUpdateRessources) {
  3222. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3223. }
  3224. else {
  3225. saveAndLoadImage();
  3226. }
  3227. };
  3228. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3229. if (this.isSupported && this.db !== null) {
  3230. var texture;
  3231. var transaction = this.db.transaction(["textures"]);
  3232. transaction.onabort = function (event) {
  3233. image.src = url;
  3234. };
  3235. transaction.oncomplete = function (event) {
  3236. var blobTextureURL;
  3237. if (texture) {
  3238. var URL = window.URL || window.webkitURL;
  3239. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3240. image.onerror = function () {
  3241. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3242. image.src = url;
  3243. };
  3244. image.src = blobTextureURL;
  3245. }
  3246. else {
  3247. notInDBCallback();
  3248. }
  3249. };
  3250. var getRequest = transaction.objectStore("textures").get(url);
  3251. getRequest.onsuccess = function (event) {
  3252. texture = (event.target).result;
  3253. };
  3254. getRequest.onerror = function (event) {
  3255. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3256. image.src = url;
  3257. };
  3258. }
  3259. else {
  3260. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3261. image.src = url;
  3262. }
  3263. };
  3264. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3265. var _this = this;
  3266. if (this.isSupported) {
  3267. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3268. var generateBlobUrl = function () {
  3269. var blobTextureURL;
  3270. if (blob) {
  3271. var URL = window.URL || window.webkitURL;
  3272. try {
  3273. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3274. }
  3275. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3276. catch (ex) {
  3277. blobTextureURL = URL.createObjectURL(blob);
  3278. }
  3279. }
  3280. image.src = blobTextureURL;
  3281. };
  3282. if (Database.IsUASupportingBlobStorage) {
  3283. var xhr = new XMLHttpRequest(), blob;
  3284. xhr.open("GET", url, true);
  3285. xhr.responseType = "blob";
  3286. xhr.addEventListener("load", function () {
  3287. if (xhr.status === 200) {
  3288. // Blob as response (XHR2)
  3289. blob = xhr.response;
  3290. var transaction = _this.db.transaction(["textures"], "readwrite");
  3291. // the transaction could abort because of a QuotaExceededError error
  3292. transaction.onabort = function (event) {
  3293. try {
  3294. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3295. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3296. this.hasReachedQuota = true;
  3297. }
  3298. }
  3299. catch (ex) { }
  3300. generateBlobUrl();
  3301. };
  3302. transaction.oncomplete = function (event) {
  3303. generateBlobUrl();
  3304. };
  3305. var newTexture = { textureUrl: url, data: blob };
  3306. try {
  3307. // Put the blob into the dabase
  3308. var addRequest = transaction.objectStore("textures").put(newTexture);
  3309. addRequest.onsuccess = function (event) {
  3310. };
  3311. addRequest.onerror = function (event) {
  3312. generateBlobUrl();
  3313. };
  3314. }
  3315. catch (ex) {
  3316. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3317. if (ex.code === 25) {
  3318. Database.IsUASupportingBlobStorage = false;
  3319. }
  3320. image.src = url;
  3321. }
  3322. }
  3323. else {
  3324. image.src = url;
  3325. }
  3326. }, false);
  3327. xhr.addEventListener("error", function (event) {
  3328. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3329. image.src = url;
  3330. }, false);
  3331. xhr.send();
  3332. }
  3333. else {
  3334. image.src = url;
  3335. }
  3336. }
  3337. else {
  3338. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3339. image.src = url;
  3340. }
  3341. };
  3342. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3343. var _this = this;
  3344. var updateVersion = function (event) {
  3345. // the version is not yet in the DB or we need to update it
  3346. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3347. };
  3348. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3349. };
  3350. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3351. var _this = this;
  3352. if (this.isSupported) {
  3353. var version;
  3354. try {
  3355. var transaction = this.db.transaction(["versions"]);
  3356. transaction.oncomplete = function (event) {
  3357. if (version) {
  3358. // If the version in the JSON file is > than the version in DB
  3359. if (_this.manifestVersionFound > version.data) {
  3360. _this.mustUpdateRessources = true;
  3361. updateInDBCallback();
  3362. }
  3363. else {
  3364. callback(version.data);
  3365. }
  3366. }
  3367. else {
  3368. _this.mustUpdateRessources = true;
  3369. updateInDBCallback();
  3370. }
  3371. };
  3372. transaction.onabort = function (event) {
  3373. callback(-1);
  3374. };
  3375. var getRequest = transaction.objectStore("versions").get(url);
  3376. getRequest.onsuccess = function (event) {
  3377. version = (event.target).result;
  3378. };
  3379. getRequest.onerror = function (event) {
  3380. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3381. callback(-1);
  3382. };
  3383. }
  3384. catch (ex) {
  3385. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3386. callback(-1);
  3387. }
  3388. }
  3389. else {
  3390. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3391. callback(-1);
  3392. }
  3393. };
  3394. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3395. var _this = this;
  3396. if (this.isSupported && !this.hasReachedQuota) {
  3397. try {
  3398. // Open a transaction to the database
  3399. var transaction = this.db.transaction(["versions"], "readwrite");
  3400. // the transaction could abort because of a QuotaExceededError error
  3401. transaction.onabort = function (event) {
  3402. try {
  3403. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3404. _this.hasReachedQuota = true;
  3405. }
  3406. }
  3407. catch (ex) { }
  3408. callback(-1);
  3409. };
  3410. transaction.oncomplete = function (event) {
  3411. callback(_this.manifestVersionFound);
  3412. };
  3413. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3414. // Put the scene into the database
  3415. var addRequest = transaction.objectStore("versions").put(newVersion);
  3416. addRequest.onsuccess = function (event) {
  3417. };
  3418. addRequest.onerror = function (event) {
  3419. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3420. };
  3421. }
  3422. catch (ex) {
  3423. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3424. callback(-1);
  3425. }
  3426. }
  3427. else {
  3428. callback(-1);
  3429. }
  3430. };
  3431. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3432. var _this = this;
  3433. var completeUrl = Database.ReturnFullUrlLocation(url);
  3434. var saveAndLoadFile = function (event) {
  3435. // the scene is not yet in the DB, let's try to save it
  3436. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3437. };
  3438. this._checkVersionFromDB(completeUrl, function (version) {
  3439. if (version !== -1) {
  3440. if (!_this.mustUpdateRessources) {
  3441. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3442. }
  3443. else {
  3444. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3445. }
  3446. }
  3447. else {
  3448. errorCallback();
  3449. }
  3450. });
  3451. };
  3452. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3453. if (this.isSupported) {
  3454. var targetStore;
  3455. if (url.indexOf(".babylon") !== -1) {
  3456. targetStore = "scenes";
  3457. }
  3458. else {
  3459. targetStore = "textures";
  3460. }
  3461. var file;
  3462. var transaction = this.db.transaction([targetStore]);
  3463. transaction.oncomplete = function (event) {
  3464. if (file) {
  3465. callback(file.data);
  3466. }
  3467. else {
  3468. notInDBCallback();
  3469. }
  3470. };
  3471. transaction.onabort = function (event) {
  3472. notInDBCallback();
  3473. };
  3474. var getRequest = transaction.objectStore(targetStore).get(url);
  3475. getRequest.onsuccess = function (event) {
  3476. file = (event.target).result;
  3477. };
  3478. getRequest.onerror = function (event) {
  3479. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3480. notInDBCallback();
  3481. };
  3482. }
  3483. else {
  3484. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3485. callback();
  3486. }
  3487. };
  3488. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3489. var _this = this;
  3490. if (this.isSupported) {
  3491. var targetStore;
  3492. if (url.indexOf(".babylon") !== -1) {
  3493. targetStore = "scenes";
  3494. }
  3495. else {
  3496. targetStore = "textures";
  3497. }
  3498. // Create XHR
  3499. var xhr = new XMLHttpRequest(), fileData;
  3500. xhr.open("GET", url, true);
  3501. if (useArrayBuffer) {
  3502. xhr.responseType = "arraybuffer";
  3503. }
  3504. xhr.onprogress = progressCallback;
  3505. xhr.addEventListener("load", function () {
  3506. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3507. // Blob as response (XHR2)
  3508. //fileData = xhr.responseText;
  3509. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3510. if (!_this.hasReachedQuota) {
  3511. // Open a transaction to the database
  3512. var transaction = _this.db.transaction([targetStore], "readwrite");
  3513. // the transaction could abort because of a QuotaExceededError error
  3514. transaction.onabort = function (event) {
  3515. try {
  3516. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3517. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3518. this.hasReachedQuota = true;
  3519. }
  3520. }
  3521. catch (ex) { }
  3522. callback(fileData);
  3523. };
  3524. transaction.oncomplete = function (event) {
  3525. callback(fileData);
  3526. };
  3527. var newFile;
  3528. if (targetStore === "scenes") {
  3529. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3530. }
  3531. else {
  3532. newFile = { textureUrl: url, data: fileData };
  3533. }
  3534. try {
  3535. // Put the scene into the database
  3536. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3537. addRequest.onsuccess = function (event) {
  3538. };
  3539. addRequest.onerror = function (event) {
  3540. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3541. };
  3542. }
  3543. catch (ex) {
  3544. callback(fileData);
  3545. }
  3546. }
  3547. else {
  3548. callback(fileData);
  3549. }
  3550. }
  3551. else {
  3552. callback();
  3553. }
  3554. }, false);
  3555. xhr.addEventListener("error", function (event) {
  3556. BABYLON.Tools.Error("error on XHR request.");
  3557. callback();
  3558. }, false);
  3559. xhr.send();
  3560. }
  3561. else {
  3562. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3563. callback();
  3564. }
  3565. };
  3566. Database.IsUASupportingBlobStorage = true;
  3567. Database.IDBStorageEnabled = true;
  3568. Database.parseURL = function (url) {
  3569. var a = document.createElement('a');
  3570. a.href = url;
  3571. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3572. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3573. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3574. return absLocation;
  3575. };
  3576. Database.ReturnFullUrlLocation = function (url) {
  3577. if (url.indexOf("http:/") === -1) {
  3578. return (Database.parseURL(window.location.href) + url);
  3579. }
  3580. else {
  3581. return url;
  3582. }
  3583. };
  3584. return Database;
  3585. })();
  3586. BABYLON.Database = Database;
  3587. })(BABYLON || (BABYLON = {}));
  3588. var BABYLON;
  3589. (function (BABYLON) {
  3590. var Internals;
  3591. (function (Internals) {
  3592. /*
  3593. * Based on jsTGALoader - Javascript loader for TGA file
  3594. * By Vincent Thibault
  3595. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3596. */
  3597. var TGATools = (function () {
  3598. function TGATools() {
  3599. }
  3600. TGATools.GetTGAHeader = function (data) {
  3601. var offset = 0;
  3602. var header = {
  3603. id_length: data[offset++],
  3604. colormap_type: data[offset++],
  3605. image_type: data[offset++],
  3606. colormap_index: data[offset++] | data[offset++] << 8,
  3607. colormap_length: data[offset++] | data[offset++] << 8,
  3608. colormap_size: data[offset++],
  3609. origin: [
  3610. data[offset++] | data[offset++] << 8,
  3611. data[offset++] | data[offset++] << 8
  3612. ],
  3613. width: data[offset++] | data[offset++] << 8,
  3614. height: data[offset++] | data[offset++] << 8,
  3615. pixel_size: data[offset++],
  3616. flags: data[offset++]
  3617. };
  3618. return header;
  3619. };
  3620. TGATools.UploadContent = function (gl, data) {
  3621. // Not enough data to contain header ?
  3622. if (data.length < 19) {
  3623. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3624. return;
  3625. }
  3626. // Read Header
  3627. var offset = 18;
  3628. var header = TGATools.GetTGAHeader(data);
  3629. // Assume it's a valid Targa file.
  3630. if (header.id_length + offset > data.length) {
  3631. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3632. return;
  3633. }
  3634. // Skip not needed data
  3635. offset += header.id_length;
  3636. var use_rle = false;
  3637. var use_pal = false;
  3638. var use_rgb = false;
  3639. var use_grey = false;
  3640. // Get some informations.
  3641. switch (header.image_type) {
  3642. case TGATools._TYPE_RLE_INDEXED:
  3643. use_rle = true;
  3644. case TGATools._TYPE_INDEXED:
  3645. use_pal = true;
  3646. break;
  3647. case TGATools._TYPE_RLE_RGB:
  3648. use_rle = true;
  3649. case TGATools._TYPE_RGB:
  3650. use_rgb = true;
  3651. break;
  3652. case TGATools._TYPE_RLE_GREY:
  3653. use_rle = true;
  3654. case TGATools._TYPE_GREY:
  3655. use_grey = true;
  3656. break;
  3657. }
  3658. var pixel_data;
  3659. var numAlphaBits = header.flags & 0xf;
  3660. var pixel_size = header.pixel_size >> 3;
  3661. var pixel_total = header.width * header.height * pixel_size;
  3662. // Read palettes
  3663. var palettes;
  3664. if (use_pal) {
  3665. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3666. }
  3667. // Read LRE
  3668. if (use_rle) {
  3669. pixel_data = new Uint8Array(pixel_total);
  3670. var c, count, i;
  3671. var localOffset = 0;
  3672. var pixels = new Uint8Array(pixel_size);
  3673. while (offset < pixel_total && localOffset < pixel_total) {
  3674. c = data[offset++];
  3675. count = (c & 0x7f) + 1;
  3676. // RLE pixels
  3677. if (c & 0x80) {
  3678. // Bind pixel tmp array
  3679. for (i = 0; i < pixel_size; ++i) {
  3680. pixels[i] = data[offset++];
  3681. }
  3682. // Copy pixel array
  3683. for (i = 0; i < count; ++i) {
  3684. pixel_data.set(pixels, localOffset + i * pixel_size);
  3685. }
  3686. localOffset += pixel_size * count;
  3687. }
  3688. else {
  3689. count *= pixel_size;
  3690. for (i = 0; i < count; ++i) {
  3691. pixel_data[localOffset + i] = data[offset++];
  3692. }
  3693. localOffset += count;
  3694. }
  3695. }
  3696. }
  3697. else {
  3698. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3699. }
  3700. // Load to texture
  3701. var x_start, y_start, x_step, y_step, y_end, x_end;
  3702. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3703. default:
  3704. case TGATools._ORIGIN_UL:
  3705. x_start = 0;
  3706. x_step = 1;
  3707. x_end = header.width;
  3708. y_start = 0;
  3709. y_step = 1;
  3710. y_end = header.height;
  3711. break;
  3712. case TGATools._ORIGIN_BL:
  3713. x_start = 0;
  3714. x_step = 1;
  3715. x_end = header.width;
  3716. y_start = header.height - 1;
  3717. y_step = -1;
  3718. y_end = -1;
  3719. break;
  3720. case TGATools._ORIGIN_UR:
  3721. x_start = header.width - 1;
  3722. x_step = -1;
  3723. x_end = -1;
  3724. y_start = 0;
  3725. y_step = 1;
  3726. y_end = header.height;
  3727. break;
  3728. case TGATools._ORIGIN_BR:
  3729. x_start = header.width - 1;
  3730. x_step = -1;
  3731. x_end = -1;
  3732. y_start = header.height - 1;
  3733. y_step = -1;
  3734. y_end = -1;
  3735. break;
  3736. }
  3737. // Load the specify method
  3738. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3739. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3740. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3741. };
  3742. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3743. var image = pixel_data, colormap = palettes;
  3744. var width = header.width, height = header.height;
  3745. var color, i = 0, x, y;
  3746. var imageData = new Uint8Array(width * height * 4);
  3747. for (y = y_start; y !== y_end; y += y_step) {
  3748. for (x = x_start; x !== x_end; x += x_step, i++) {
  3749. color = image[i];
  3750. imageData[(x + width * y) * 4 + 3] = 255;
  3751. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3752. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3753. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3754. }
  3755. }
  3756. return imageData;
  3757. };
  3758. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3759. var image = pixel_data;
  3760. var width = header.width, height = header.height;
  3761. var color, i = 0, x, y;
  3762. var imageData = new Uint8Array(width * height * 4);
  3763. for (y = y_start; y !== y_end; y += y_step) {
  3764. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3765. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3766. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3767. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3768. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3769. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3770. }
  3771. }
  3772. return imageData;
  3773. };
  3774. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3775. var image = pixel_data;
  3776. var width = header.width, height = header.height;
  3777. var i = 0, x, y;
  3778. var imageData = new Uint8Array(width * height * 4);
  3779. for (y = y_start; y !== y_end; y += y_step) {
  3780. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3781. imageData[(x + width * y) * 4 + 3] = 255;
  3782. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3783. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3784. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3785. }
  3786. }
  3787. return imageData;
  3788. };
  3789. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3790. var image = pixel_data;
  3791. var width = header.width, height = header.height;
  3792. var i = 0, x, y;
  3793. var imageData = new Uint8Array(width * height * 4);
  3794. for (y = y_start; y !== y_end; y += y_step) {
  3795. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3796. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3797. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3798. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3799. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3800. }
  3801. }
  3802. return imageData;
  3803. };
  3804. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3805. var image = pixel_data;
  3806. var width = header.width, height = header.height;
  3807. var color, i = 0, x, y;
  3808. var imageData = new Uint8Array(width * height * 4);
  3809. for (y = y_start; y !== y_end; y += y_step) {
  3810. for (x = x_start; x !== x_end; x += x_step, i++) {
  3811. color = image[i];
  3812. imageData[(x + width * y) * 4 + 0] = color;
  3813. imageData[(x + width * y) * 4 + 1] = color;
  3814. imageData[(x + width * y) * 4 + 2] = color;
  3815. imageData[(x + width * y) * 4 + 3] = 255;
  3816. }
  3817. }
  3818. return imageData;
  3819. };
  3820. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3821. var image = pixel_data;
  3822. var width = header.width, height = header.height;
  3823. var i = 0, x, y;
  3824. var imageData = new Uint8Array(width * height * 4);
  3825. for (y = y_start; y !== y_end; y += y_step) {
  3826. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3827. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3828. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3829. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3830. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3831. }
  3832. }
  3833. return imageData;
  3834. };
  3835. TGATools._TYPE_NO_DATA = 0;
  3836. TGATools._TYPE_INDEXED = 1;
  3837. TGATools._TYPE_RGB = 2;
  3838. TGATools._TYPE_GREY = 3;
  3839. TGATools._TYPE_RLE_INDEXED = 9;
  3840. TGATools._TYPE_RLE_RGB = 10;
  3841. TGATools._TYPE_RLE_GREY = 11;
  3842. TGATools._ORIGIN_MASK = 0x30;
  3843. TGATools._ORIGIN_SHIFT = 0x04;
  3844. TGATools._ORIGIN_BL = 0x00;
  3845. TGATools._ORIGIN_BR = 0x01;
  3846. TGATools._ORIGIN_UL = 0x02;
  3847. TGATools._ORIGIN_UR = 0x03;
  3848. return TGATools;
  3849. })();
  3850. Internals.TGATools = TGATools;
  3851. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3852. })(BABYLON || (BABYLON = {}));
  3853. var BABYLON;
  3854. (function (BABYLON) {
  3855. var SmartArray = (function () {
  3856. function SmartArray(capacity) {
  3857. this.length = 0;
  3858. this._duplicateId = 0;
  3859. this.data = new Array(capacity);
  3860. this._id = SmartArray._GlobalId++;
  3861. }
  3862. SmartArray.prototype.push = function (value) {
  3863. this.data[this.length++] = value;
  3864. if (this.length > this.data.length) {
  3865. this.data.length *= 2;
  3866. }
  3867. if (!value.__smartArrayFlags) {
  3868. value.__smartArrayFlags = {};
  3869. }
  3870. value.__smartArrayFlags[this._id] = this._duplicateId;
  3871. };
  3872. SmartArray.prototype.pushNoDuplicate = function (value) {
  3873. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3874. return;
  3875. }
  3876. this.push(value);
  3877. };
  3878. SmartArray.prototype.sort = function (compareFn) {
  3879. this.data.sort(compareFn);
  3880. };
  3881. SmartArray.prototype.reset = function () {
  3882. this.length = 0;
  3883. this._duplicateId++;
  3884. };
  3885. SmartArray.prototype.concat = function (array) {
  3886. if (array.length === 0) {
  3887. return;
  3888. }
  3889. if (this.length + array.length > this.data.length) {
  3890. this.data.length = (this.length + array.length) * 2;
  3891. }
  3892. for (var index = 0; index < array.length; index++) {
  3893. this.data[this.length++] = (array.data || array)[index];
  3894. }
  3895. };
  3896. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3897. if (array.length === 0) {
  3898. return;
  3899. }
  3900. if (this.length + array.length > this.data.length) {
  3901. this.data.length = (this.length + array.length) * 2;
  3902. }
  3903. for (var index = 0; index < array.length; index++) {
  3904. var item = (array.data || array)[index];
  3905. this.pushNoDuplicate(item);
  3906. }
  3907. };
  3908. SmartArray.prototype.indexOf = function (value) {
  3909. var position = this.data.indexOf(value);
  3910. if (position >= this.length) {
  3911. return -1;
  3912. }
  3913. return position;
  3914. };
  3915. // Statics
  3916. SmartArray._GlobalId = 0;
  3917. return SmartArray;
  3918. })();
  3919. BABYLON.SmartArray = SmartArray;
  3920. })(BABYLON || (BABYLON = {}));
  3921. var BABYLON;
  3922. (function (BABYLON) {
  3923. var SmartCollection = (function () {
  3924. function SmartCollection(capacity) {
  3925. if (capacity === void 0) { capacity = 10; }
  3926. this.count = 0;
  3927. this._initialCapacity = capacity;
  3928. this.items = {};
  3929. this._keys = new Array(this._initialCapacity);
  3930. }
  3931. SmartCollection.prototype.add = function (key, item) {
  3932. if (this.items[key] != undefined) {
  3933. return -1;
  3934. }
  3935. this.items[key] = item;
  3936. //literal keys are always strings, but we keep source type of key in _keys array
  3937. this._keys[this.count++] = key;
  3938. if (this.count > this._keys.length) {
  3939. this._keys.length *= 2;
  3940. }
  3941. return this.count;
  3942. };
  3943. SmartCollection.prototype.remove = function (key) {
  3944. if (this.items[key] == undefined) {
  3945. return -1;
  3946. }
  3947. return this.removeItemOfIndex(this.indexOf(key));
  3948. };
  3949. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3950. if (index < this.count && index > -1) {
  3951. delete this.items[this._keys[index]];
  3952. //here, shifting by hand is better optimised than .splice
  3953. while (index < this.count) {
  3954. this._keys[index] = this._keys[index + 1];
  3955. index++;
  3956. }
  3957. }
  3958. else {
  3959. return -1;
  3960. }
  3961. return --this.count;
  3962. };
  3963. SmartCollection.prototype.indexOf = function (key) {
  3964. for (var i = 0; i !== this.count; i++) {
  3965. if (this._keys[i] === key) {
  3966. return i;
  3967. }
  3968. }
  3969. return -1;
  3970. };
  3971. SmartCollection.prototype.item = function (key) {
  3972. return this.items[key];
  3973. };
  3974. SmartCollection.prototype.getAllKeys = function () {
  3975. if (this.count > 0) {
  3976. var keys = new Array(this.count);
  3977. for (var i = 0; i < this.count; i++) {
  3978. keys[i] = this._keys[i];
  3979. }
  3980. return keys;
  3981. }
  3982. else {
  3983. return undefined;
  3984. }
  3985. };
  3986. SmartCollection.prototype.getKeyByIndex = function (index) {
  3987. if (index < this.count && index > -1) {
  3988. return this._keys[index];
  3989. }
  3990. else {
  3991. return undefined;
  3992. }
  3993. };
  3994. SmartCollection.prototype.getItemByIndex = function (index) {
  3995. if (index < this.count && index > -1) {
  3996. return this.items[this._keys[index]];
  3997. }
  3998. else {
  3999. return undefined;
  4000. }
  4001. };
  4002. SmartCollection.prototype.empty = function () {
  4003. if (this.count > 0) {
  4004. this.count = 0;
  4005. this.items = {};
  4006. this._keys = new Array(this._initialCapacity);
  4007. }
  4008. };
  4009. SmartCollection.prototype.forEach = function (block) {
  4010. var key;
  4011. for (key in this.items) {
  4012. if (this.items.hasOwnProperty(key)) {
  4013. block(this.items[key]);
  4014. }
  4015. }
  4016. };
  4017. return SmartCollection;
  4018. })();
  4019. BABYLON.SmartCollection = SmartCollection;
  4020. })(BABYLON || (BABYLON = {}));
  4021. var BABYLON;
  4022. (function (BABYLON) {
  4023. // Screenshots
  4024. var screenshotCanvas;
  4025. var cloneValue = function (source, destinationObject) {
  4026. if (!source)
  4027. return null;
  4028. if (source instanceof BABYLON.Mesh) {
  4029. return null;
  4030. }
  4031. if (source instanceof BABYLON.SubMesh) {
  4032. return source.clone(destinationObject);
  4033. }
  4034. else if (source.clone) {
  4035. return source.clone();
  4036. }
  4037. return null;
  4038. };
  4039. var Tools = (function () {
  4040. function Tools() {
  4041. }
  4042. Tools.Instantiate = function (className) {
  4043. var arr = className.split(".");
  4044. var fn = (window || this);
  4045. for (var i = 0, len = arr.length; i < len; i++) {
  4046. fn = fn[arr[i]];
  4047. }
  4048. if (typeof fn !== "function") {
  4049. return null;
  4050. }
  4051. return fn;
  4052. };
  4053. Tools.SetImmediate = function (action) {
  4054. if (window.setImmediate) {
  4055. window.setImmediate(action);
  4056. }
  4057. else {
  4058. setTimeout(action, 1);
  4059. }
  4060. };
  4061. Tools.IsExponentOfTwo = function (value) {
  4062. var count = 1;
  4063. do {
  4064. count *= 2;
  4065. } while (count < value);
  4066. return count === value;
  4067. };
  4068. Tools.GetExponentOfTwo = function (value, max) {
  4069. var count = 1;
  4070. do {
  4071. count *= 2;
  4072. } while (count < value);
  4073. if (count > max)
  4074. count = max;
  4075. return count;
  4076. };
  4077. Tools.GetFilename = function (path) {
  4078. var index = path.lastIndexOf("/");
  4079. if (index < 0)
  4080. return path;
  4081. return path.substring(index + 1);
  4082. };
  4083. Tools.GetDOMTextContent = function (element) {
  4084. var result = "";
  4085. var child = element.firstChild;
  4086. while (child) {
  4087. if (child.nodeType === 3) {
  4088. result += child.textContent;
  4089. }
  4090. child = child.nextSibling;
  4091. }
  4092. return result;
  4093. };
  4094. Tools.ToDegrees = function (angle) {
  4095. return angle * 180 / Math.PI;
  4096. };
  4097. Tools.ToRadians = function (angle) {
  4098. return angle * Math.PI / 180;
  4099. };
  4100. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4101. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4102. var output = "";
  4103. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4104. var i = 0;
  4105. var bytes = new Uint8Array(buffer);
  4106. while (i < bytes.length) {
  4107. chr1 = bytes[i++];
  4108. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4109. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4110. enc1 = chr1 >> 2;
  4111. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4112. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4113. enc4 = chr3 & 63;
  4114. if (isNaN(chr2)) {
  4115. enc3 = enc4 = 64;
  4116. }
  4117. else if (isNaN(chr3)) {
  4118. enc4 = 64;
  4119. }
  4120. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4121. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4122. }
  4123. return "data:image/png;base64," + output;
  4124. };
  4125. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4126. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4127. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4128. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4129. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4130. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4131. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4132. }
  4133. return {
  4134. minimum: minimum,
  4135. maximum: maximum
  4136. };
  4137. };
  4138. Tools.ExtractMinAndMax = function (positions, start, count) {
  4139. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4140. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4141. for (var index = start; index < start + count; index++) {
  4142. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4143. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4144. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4145. }
  4146. return {
  4147. minimum: minimum,
  4148. maximum: maximum
  4149. };
  4150. };
  4151. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4152. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4153. return undefined;
  4154. return Array.isArray(obj) ? obj : [obj];
  4155. };
  4156. // Misc.
  4157. Tools.GetPointerPrefix = function () {
  4158. var eventPrefix = "pointer";
  4159. // Check if pointer events are supported
  4160. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4161. eventPrefix = "mouse";
  4162. }
  4163. return eventPrefix;
  4164. };
  4165. Tools.QueueNewFrame = function (func) {
  4166. if (window.requestAnimationFrame)
  4167. window.requestAnimationFrame(func);
  4168. else if (window.msRequestAnimationFrame)
  4169. window.msRequestAnimationFrame(func);
  4170. else if (window.webkitRequestAnimationFrame)
  4171. window.webkitRequestAnimationFrame(func);
  4172. else if (window.mozRequestAnimationFrame)
  4173. window.mozRequestAnimationFrame(func);
  4174. else if (window.oRequestAnimationFrame)
  4175. window.oRequestAnimationFrame(func);
  4176. else {
  4177. window.setTimeout(func, 16);
  4178. }
  4179. };
  4180. Tools.RequestFullscreen = function (element) {
  4181. if (element.requestFullscreen)
  4182. element.requestFullscreen();
  4183. else if (element.msRequestFullscreen)
  4184. element.msRequestFullscreen();
  4185. else if (element.webkitRequestFullscreen)
  4186. element.webkitRequestFullscreen();
  4187. else if (element.mozRequestFullScreen)
  4188. element.mozRequestFullScreen();
  4189. };
  4190. Tools.ExitFullscreen = function () {
  4191. if (document.exitFullscreen) {
  4192. document.exitFullscreen();
  4193. }
  4194. else if (document.mozCancelFullScreen) {
  4195. document.mozCancelFullScreen();
  4196. }
  4197. else if (document.webkitCancelFullScreen) {
  4198. document.webkitCancelFullScreen();
  4199. }
  4200. else if (document.msCancelFullScreen) {
  4201. document.msCancelFullScreen();
  4202. }
  4203. };
  4204. // External files
  4205. Tools.CleanUrl = function (url) {
  4206. url = url.replace(/#/mg, "%23");
  4207. return url;
  4208. };
  4209. Tools.LoadImage = function (url, onload, onerror, database) {
  4210. if (url instanceof ArrayBuffer) {
  4211. url = Tools.EncodeArrayBufferTobase64(url);
  4212. }
  4213. url = Tools.CleanUrl(url);
  4214. var img = new Image();
  4215. if (url.substr(0, 5) !== "data:") {
  4216. if (Tools.CorsBehavior) {
  4217. switch (typeof (Tools.CorsBehavior)) {
  4218. case "function":
  4219. var result = Tools.CorsBehavior(url);
  4220. if (result) {
  4221. img.crossOrigin = result;
  4222. }
  4223. break;
  4224. case "string":
  4225. default:
  4226. img.crossOrigin = Tools.CorsBehavior;
  4227. break;
  4228. }
  4229. }
  4230. }
  4231. img.onload = function () {
  4232. onload(img);
  4233. };
  4234. img.onerror = function (err) {
  4235. Tools.Error("Error while trying to load texture: " + url);
  4236. if (Tools.UseFallbackTexture) {
  4237. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4238. onload(img);
  4239. }
  4240. else {
  4241. onerror();
  4242. }
  4243. };
  4244. var noIndexedDB = function () {
  4245. img.src = url;
  4246. };
  4247. var loadFromIndexedDB = function () {
  4248. database.loadImageFromDB(url, img);
  4249. };
  4250. //ANY database to do!
  4251. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4252. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4253. }
  4254. else {
  4255. if (url.indexOf("file:") === -1) {
  4256. noIndexedDB();
  4257. }
  4258. else {
  4259. try {
  4260. var textureName = url.substring(5);
  4261. var blobURL;
  4262. try {
  4263. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4264. }
  4265. catch (ex) {
  4266. // Chrome doesn't support oneTimeOnly parameter
  4267. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4268. }
  4269. img.src = blobURL;
  4270. }
  4271. catch (e) {
  4272. img.src = null;
  4273. }
  4274. }
  4275. }
  4276. return img;
  4277. };
  4278. //ANY
  4279. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4280. url = Tools.CleanUrl(url);
  4281. var noIndexedDB = function () {
  4282. var request = new XMLHttpRequest();
  4283. var loadUrl = Tools.BaseUrl + url;
  4284. request.open('GET', loadUrl, true);
  4285. if (useArrayBuffer) {
  4286. request.responseType = "arraybuffer";
  4287. }
  4288. request.onprogress = progressCallBack;
  4289. request.onreadystatechange = function () {
  4290. if (request.readyState === 4) {
  4291. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4292. callback(!useArrayBuffer ? request.responseText : request.response);
  4293. }
  4294. else {
  4295. if (onError) {
  4296. onError();
  4297. }
  4298. else {
  4299. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4300. }
  4301. }
  4302. }
  4303. };
  4304. request.send(null);
  4305. };
  4306. var loadFromIndexedDB = function () {
  4307. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4308. };
  4309. if (url.indexOf("file:") !== -1) {
  4310. var fileName = url.substring(5);
  4311. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4312. }
  4313. else {
  4314. // Caching all files
  4315. if (database && database.enableSceneOffline) {
  4316. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4317. }
  4318. else {
  4319. noIndexedDB();
  4320. }
  4321. }
  4322. };
  4323. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4324. var reader = new FileReader();
  4325. reader.onload = function (e) {
  4326. //target doesn't have result from ts 1.3
  4327. callback(e.target['result']);
  4328. };
  4329. reader.onprogress = progressCallback;
  4330. reader.readAsDataURL(fileToLoad);
  4331. };
  4332. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4333. var reader = new FileReader();
  4334. reader.onerror = function (e) {
  4335. Tools.Log("Error while reading file: " + fileToLoad.name);
  4336. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4337. };
  4338. reader.onload = function (e) {
  4339. //target doesn't have result from ts 1.3
  4340. callback(e.target['result']);
  4341. };
  4342. reader.onprogress = progressCallBack;
  4343. if (!useArrayBuffer) {
  4344. // Asynchronous read
  4345. reader.readAsText(fileToLoad);
  4346. }
  4347. else {
  4348. reader.readAsArrayBuffer(fileToLoad);
  4349. }
  4350. };
  4351. //returns a downloadable url to a file content.
  4352. Tools.FileAsURL = function (content) {
  4353. var fileBlob = new Blob([content]);
  4354. var url = window.URL || window.webkitURL;
  4355. var link = url.createObjectURL(fileBlob);
  4356. return link;
  4357. };
  4358. // Misc.
  4359. Tools.Format = function (value, decimals) {
  4360. if (decimals === void 0) { decimals = 2; }
  4361. return value.toFixed(decimals);
  4362. };
  4363. Tools.CheckExtends = function (v, min, max) {
  4364. if (v.x < min.x)
  4365. min.x = v.x;
  4366. if (v.y < min.y)
  4367. min.y = v.y;
  4368. if (v.z < min.z)
  4369. min.z = v.z;
  4370. if (v.x > max.x)
  4371. max.x = v.x;
  4372. if (v.y > max.y)
  4373. max.y = v.y;
  4374. if (v.z > max.z)
  4375. max.z = v.z;
  4376. };
  4377. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4378. for (var prop in source) {
  4379. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4380. continue;
  4381. }
  4382. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4383. continue;
  4384. }
  4385. var sourceValue = source[prop];
  4386. var typeOfSourceValue = typeof sourceValue;
  4387. if (typeOfSourceValue === "function") {
  4388. continue;
  4389. }
  4390. if (typeOfSourceValue === "object") {
  4391. if (sourceValue instanceof Array) {
  4392. destination[prop] = [];
  4393. if (sourceValue.length > 0) {
  4394. if (typeof sourceValue[0] == "object") {
  4395. for (var index = 0; index < sourceValue.length; index++) {
  4396. var clonedValue = cloneValue(sourceValue[index], destination);
  4397. if (destination[prop].indexOf(clonedValue) === -1) {
  4398. destination[prop].push(clonedValue);
  4399. }
  4400. }
  4401. }
  4402. else {
  4403. destination[prop] = sourceValue.slice(0);
  4404. }
  4405. }
  4406. }
  4407. else {
  4408. destination[prop] = cloneValue(sourceValue, destination);
  4409. }
  4410. }
  4411. else {
  4412. destination[prop] = sourceValue;
  4413. }
  4414. }
  4415. };
  4416. Tools.IsEmpty = function (obj) {
  4417. for (var i in obj) {
  4418. return false;
  4419. }
  4420. return true;
  4421. };
  4422. Tools.RegisterTopRootEvents = function (events) {
  4423. for (var index = 0; index < events.length; index++) {
  4424. var event = events[index];
  4425. window.addEventListener(event.name, event.handler, false);
  4426. try {
  4427. if (window.parent) {
  4428. window.parent.addEventListener(event.name, event.handler, false);
  4429. }
  4430. }
  4431. catch (e) {
  4432. }
  4433. }
  4434. };
  4435. Tools.UnregisterTopRootEvents = function (events) {
  4436. for (var index = 0; index < events.length; index++) {
  4437. var event = events[index];
  4438. window.removeEventListener(event.name, event.handler);
  4439. try {
  4440. if (window.parent) {
  4441. window.parent.removeEventListener(event.name, event.handler);
  4442. }
  4443. }
  4444. catch (e) {
  4445. }
  4446. }
  4447. };
  4448. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4449. // Read the contents of the framebuffer
  4450. var numberOfChannelsByLine = width * 4;
  4451. var halfHeight = height / 2;
  4452. //Reading datas from WebGL
  4453. var data = engine.readPixels(0, 0, width, height);
  4454. //To flip image on Y axis.
  4455. for (var i = 0; i < halfHeight; i++) {
  4456. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4457. var currentCell = j + i * numberOfChannelsByLine;
  4458. var targetLine = height - i - 1;
  4459. var targetCell = j + targetLine * numberOfChannelsByLine;
  4460. var temp = data[currentCell];
  4461. data[currentCell] = data[targetCell];
  4462. data[targetCell] = temp;
  4463. }
  4464. }
  4465. // Create a 2D canvas to store the result
  4466. if (!screenshotCanvas) {
  4467. screenshotCanvas = document.createElement('canvas');
  4468. }
  4469. screenshotCanvas.width = width;
  4470. screenshotCanvas.height = height;
  4471. var context = screenshotCanvas.getContext('2d');
  4472. // Copy the pixels to a 2D canvas
  4473. var imageData = context.createImageData(width, height);
  4474. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4475. var castData = imageData.data;
  4476. castData.set(data);
  4477. context.putImageData(imageData, 0, 0);
  4478. var base64Image = screenshotCanvas.toDataURL();
  4479. if (successCallback) {
  4480. successCallback(base64Image);
  4481. }
  4482. else {
  4483. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4484. if (("download" in document.createElement("a"))) {
  4485. var a = window.document.createElement("a");
  4486. a.href = base64Image;
  4487. var date = new Date();
  4488. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4489. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4490. window.document.body.appendChild(a);
  4491. a.addEventListener("click", function () {
  4492. a.parentElement.removeChild(a);
  4493. });
  4494. a.click();
  4495. }
  4496. else {
  4497. var newWindow = window.open("");
  4498. var img = newWindow.document.createElement("img");
  4499. img.src = base64Image;
  4500. newWindow.document.body.appendChild(img);
  4501. }
  4502. }
  4503. };
  4504. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4505. var width;
  4506. var height;
  4507. //If a precision value is specified
  4508. if (size.precision) {
  4509. width = Math.round(engine.getRenderWidth() * size.precision);
  4510. height = Math.round(width / engine.getAspectRatio(camera));
  4511. size = { width: width, height: height };
  4512. }
  4513. else if (size.width && size.height) {
  4514. width = size.width;
  4515. height = size.height;
  4516. }
  4517. else if (size.width && !size.height) {
  4518. width = size.width;
  4519. height = Math.round(width / engine.getAspectRatio(camera));
  4520. size = { width: width, height: height };
  4521. }
  4522. else if (size.height && !size.width) {
  4523. height = size.height;
  4524. width = Math.round(height * engine.getAspectRatio(camera));
  4525. size = { width: width, height: height };
  4526. }
  4527. else if (!isNaN(size)) {
  4528. height = size;
  4529. width = size;
  4530. }
  4531. else {
  4532. Tools.Error("Invalid 'size' parameter !");
  4533. return;
  4534. }
  4535. var scene = camera.getScene();
  4536. var previousCamera = null;
  4537. if (scene.activeCamera !== camera) {
  4538. previousCamera = scene.activeCamera;
  4539. scene.activeCamera = camera;
  4540. }
  4541. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4542. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4543. texture.renderList = scene.meshes;
  4544. texture.onAfterRender = function () {
  4545. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4546. };
  4547. scene.incrementRenderId();
  4548. texture.render(true);
  4549. texture.dispose();
  4550. if (previousCamera) {
  4551. scene.activeCamera = previousCamera;
  4552. }
  4553. camera.getProjectionMatrix(true); // Force cache refresh;
  4554. };
  4555. // XHR response validator for local file scenario
  4556. Tools.ValidateXHRData = function (xhr, dataType) {
  4557. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4558. if (dataType === void 0) { dataType = 7; }
  4559. try {
  4560. if (dataType & 1) {
  4561. if (xhr.responseText && xhr.responseText.length > 0) {
  4562. return true;
  4563. }
  4564. else if (dataType === 1) {
  4565. return false;
  4566. }
  4567. }
  4568. if (dataType & 2) {
  4569. // Check header width and height since there is no "TGA" magic number
  4570. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4571. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4572. return true;
  4573. }
  4574. else if (dataType === 2) {
  4575. return false;
  4576. }
  4577. }
  4578. if (dataType & 4) {
  4579. // Check for the "DDS" magic number
  4580. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4581. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4582. return true;
  4583. }
  4584. else {
  4585. return false;
  4586. }
  4587. }
  4588. }
  4589. catch (e) {
  4590. }
  4591. return false;
  4592. };
  4593. Object.defineProperty(Tools, "NoneLogLevel", {
  4594. get: function () {
  4595. return Tools._NoneLogLevel;
  4596. },
  4597. enumerable: true,
  4598. configurable: true
  4599. });
  4600. Object.defineProperty(Tools, "MessageLogLevel", {
  4601. get: function () {
  4602. return Tools._MessageLogLevel;
  4603. },
  4604. enumerable: true,
  4605. configurable: true
  4606. });
  4607. Object.defineProperty(Tools, "WarningLogLevel", {
  4608. get: function () {
  4609. return Tools._WarningLogLevel;
  4610. },
  4611. enumerable: true,
  4612. configurable: true
  4613. });
  4614. Object.defineProperty(Tools, "ErrorLogLevel", {
  4615. get: function () {
  4616. return Tools._ErrorLogLevel;
  4617. },
  4618. enumerable: true,
  4619. configurable: true
  4620. });
  4621. Object.defineProperty(Tools, "AllLogLevel", {
  4622. get: function () {
  4623. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4624. },
  4625. enumerable: true,
  4626. configurable: true
  4627. });
  4628. Tools._AddLogEntry = function (entry) {
  4629. Tools._LogCache = entry + Tools._LogCache;
  4630. if (Tools.OnNewCacheEntry) {
  4631. Tools.OnNewCacheEntry(entry);
  4632. }
  4633. };
  4634. Tools._FormatMessage = function (message) {
  4635. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4636. var date = new Date();
  4637. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4638. };
  4639. Tools._LogDisabled = function (message) {
  4640. // nothing to do
  4641. };
  4642. Tools._LogEnabled = function (message) {
  4643. var formattedMessage = Tools._FormatMessage(message);
  4644. console.log("BJS - " + formattedMessage);
  4645. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4646. Tools._AddLogEntry(entry);
  4647. };
  4648. Tools._WarnDisabled = function (message) {
  4649. // nothing to do
  4650. };
  4651. Tools._WarnEnabled = function (message) {
  4652. var formattedMessage = Tools._FormatMessage(message);
  4653. console.warn("BJS - " + formattedMessage);
  4654. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4655. Tools._AddLogEntry(entry);
  4656. };
  4657. Tools._ErrorDisabled = function (message) {
  4658. // nothing to do
  4659. };
  4660. Tools._ErrorEnabled = function (message) {
  4661. Tools.errorsCount++;
  4662. var formattedMessage = Tools._FormatMessage(message);
  4663. console.error("BJS - " + formattedMessage);
  4664. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4665. Tools._AddLogEntry(entry);
  4666. };
  4667. Object.defineProperty(Tools, "LogCache", {
  4668. get: function () {
  4669. return Tools._LogCache;
  4670. },
  4671. enumerable: true,
  4672. configurable: true
  4673. });
  4674. Tools.ClearLogCache = function () {
  4675. Tools._LogCache = "";
  4676. Tools.errorsCount = 0;
  4677. };
  4678. Object.defineProperty(Tools, "LogLevels", {
  4679. set: function (level) {
  4680. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4681. Tools.Log = Tools._LogEnabled;
  4682. }
  4683. else {
  4684. Tools.Log = Tools._LogDisabled;
  4685. }
  4686. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4687. Tools.Warn = Tools._WarnEnabled;
  4688. }
  4689. else {
  4690. Tools.Warn = Tools._WarnDisabled;
  4691. }
  4692. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4693. Tools.Error = Tools._ErrorEnabled;
  4694. }
  4695. else {
  4696. Tools.Error = Tools._ErrorDisabled;
  4697. }
  4698. },
  4699. enumerable: true,
  4700. configurable: true
  4701. });
  4702. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4703. get: function () {
  4704. return Tools._PerformanceNoneLogLevel;
  4705. },
  4706. enumerable: true,
  4707. configurable: true
  4708. });
  4709. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4710. get: function () {
  4711. return Tools._PerformanceUserMarkLogLevel;
  4712. },
  4713. enumerable: true,
  4714. configurable: true
  4715. });
  4716. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4717. get: function () {
  4718. return Tools._PerformanceConsoleLogLevel;
  4719. },
  4720. enumerable: true,
  4721. configurable: true
  4722. });
  4723. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4724. set: function (level) {
  4725. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4726. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4727. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4728. return;
  4729. }
  4730. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4731. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4732. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4733. return;
  4734. }
  4735. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4736. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4737. },
  4738. enumerable: true,
  4739. configurable: true
  4740. });
  4741. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4742. };
  4743. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4744. };
  4745. Tools._StartUserMark = function (counterName, condition) {
  4746. if (condition === void 0) { condition = true; }
  4747. if (!condition || !Tools._performance.mark) {
  4748. return;
  4749. }
  4750. Tools._performance.mark(counterName + "-Begin");
  4751. };
  4752. Tools._EndUserMark = function (counterName, condition) {
  4753. if (condition === void 0) { condition = true; }
  4754. if (!condition || !Tools._performance.mark) {
  4755. return;
  4756. }
  4757. Tools._performance.mark(counterName + "-End");
  4758. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4759. };
  4760. Tools._StartPerformanceConsole = function (counterName, condition) {
  4761. if (condition === void 0) { condition = true; }
  4762. if (!condition) {
  4763. return;
  4764. }
  4765. Tools._StartUserMark(counterName, condition);
  4766. if (console.time) {
  4767. console.time(counterName);
  4768. }
  4769. };
  4770. Tools._EndPerformanceConsole = function (counterName, condition) {
  4771. if (condition === void 0) { condition = true; }
  4772. if (!condition) {
  4773. return;
  4774. }
  4775. Tools._EndUserMark(counterName, condition);
  4776. if (console.time) {
  4777. console.timeEnd(counterName);
  4778. }
  4779. };
  4780. Object.defineProperty(Tools, "Now", {
  4781. get: function () {
  4782. if (window.performance && window.performance.now) {
  4783. return window.performance.now();
  4784. }
  4785. return new Date().getTime();
  4786. },
  4787. enumerable: true,
  4788. configurable: true
  4789. });
  4790. Tools.BaseUrl = "";
  4791. Tools.CorsBehavior = "anonymous";
  4792. Tools.UseFallbackTexture = true;
  4793. // Logs
  4794. Tools._NoneLogLevel = 0;
  4795. Tools._MessageLogLevel = 1;
  4796. Tools._WarningLogLevel = 2;
  4797. Tools._ErrorLogLevel = 4;
  4798. Tools._LogCache = "";
  4799. Tools.errorsCount = 0;
  4800. Tools.Log = Tools._LogEnabled;
  4801. Tools.Warn = Tools._WarnEnabled;
  4802. Tools.Error = Tools._ErrorEnabled;
  4803. // Performances
  4804. Tools._PerformanceNoneLogLevel = 0;
  4805. Tools._PerformanceUserMarkLogLevel = 1;
  4806. Tools._PerformanceConsoleLogLevel = 2;
  4807. Tools._performance = window.performance;
  4808. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4809. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4810. return Tools;
  4811. })();
  4812. BABYLON.Tools = Tools;
  4813. /**
  4814. * An implementation of a loop for asynchronous functions.
  4815. */
  4816. var AsyncLoop = (function () {
  4817. /**
  4818. * Constroctor.
  4819. * @param iterations the number of iterations.
  4820. * @param _fn the function to run each iteration
  4821. * @param _successCallback the callback that will be called upon succesful execution
  4822. * @param offset starting offset.
  4823. */
  4824. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4825. if (offset === void 0) { offset = 0; }
  4826. this.iterations = iterations;
  4827. this._fn = _fn;
  4828. this._successCallback = _successCallback;
  4829. this.index = offset - 1;
  4830. this._done = false;
  4831. }
  4832. /**
  4833. * Execute the next iteration. Must be called after the last iteration was finished.
  4834. */
  4835. AsyncLoop.prototype.executeNext = function () {
  4836. if (!this._done) {
  4837. if (this.index + 1 < this.iterations) {
  4838. ++this.index;
  4839. this._fn(this);
  4840. }
  4841. else {
  4842. this.breakLoop();
  4843. }
  4844. }
  4845. };
  4846. /**
  4847. * Break the loop and run the success callback.
  4848. */
  4849. AsyncLoop.prototype.breakLoop = function () {
  4850. this._done = true;
  4851. this._successCallback();
  4852. };
  4853. /**
  4854. * Helper function
  4855. */
  4856. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4857. if (offset === void 0) { offset = 0; }
  4858. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4859. loop.executeNext();
  4860. return loop;
  4861. };
  4862. /**
  4863. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4864. * @param iterations total number of iterations
  4865. * @param syncedIterations number of synchronous iterations in each async iteration.
  4866. * @param fn the function to call each iteration.
  4867. * @param callback a success call back that will be called when iterating stops.
  4868. * @param breakFunction a break condition (optional)
  4869. * @param timeout timeout settings for the setTimeout function. default - 0.
  4870. * @constructor
  4871. */
  4872. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4873. if (timeout === void 0) { timeout = 0; }
  4874. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4875. if (breakFunction && breakFunction())
  4876. loop.breakLoop();
  4877. else {
  4878. setTimeout(function () {
  4879. for (var i = 0; i < syncedIterations; ++i) {
  4880. var iteration = (loop.index * syncedIterations) + i;
  4881. if (iteration >= iterations)
  4882. break;
  4883. fn(iteration);
  4884. if (breakFunction && breakFunction()) {
  4885. loop.breakLoop();
  4886. break;
  4887. }
  4888. }
  4889. loop.executeNext();
  4890. }, timeout);
  4891. }
  4892. }, callback);
  4893. };
  4894. return AsyncLoop;
  4895. })();
  4896. BABYLON.AsyncLoop = AsyncLoop;
  4897. })(BABYLON || (BABYLON = {}));
  4898. var BABYLON;
  4899. (function (BABYLON) {
  4900. var Internals;
  4901. (function (Internals) {
  4902. var _AlphaState = (function () {
  4903. function _AlphaState() {
  4904. this._isAlphaBlendDirty = false;
  4905. this._isBlendFunctionParametersDirty = false;
  4906. this._alphaBlend = false;
  4907. this._blendFunctionParameters = new Array(4);
  4908. }
  4909. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4910. get: function () {
  4911. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4912. },
  4913. enumerable: true,
  4914. configurable: true
  4915. });
  4916. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4917. get: function () {
  4918. return this._alphaBlend;
  4919. },
  4920. set: function (value) {
  4921. if (this._alphaBlend === value) {
  4922. return;
  4923. }
  4924. this._alphaBlend = value;
  4925. this._isAlphaBlendDirty = true;
  4926. },
  4927. enumerable: true,
  4928. configurable: true
  4929. });
  4930. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4931. if (this._blendFunctionParameters[0] === value0 &&
  4932. this._blendFunctionParameters[1] === value1 &&
  4933. this._blendFunctionParameters[2] === value2 &&
  4934. this._blendFunctionParameters[3] === value3) {
  4935. return;
  4936. }
  4937. this._blendFunctionParameters[0] = value0;
  4938. this._blendFunctionParameters[1] = value1;
  4939. this._blendFunctionParameters[2] = value2;
  4940. this._blendFunctionParameters[3] = value3;
  4941. this._isBlendFunctionParametersDirty = true;
  4942. };
  4943. _AlphaState.prototype.reset = function () {
  4944. this._alphaBlend = false;
  4945. this._blendFunctionParameters[0] = null;
  4946. this._blendFunctionParameters[1] = null;
  4947. this._blendFunctionParameters[2] = null;
  4948. this._blendFunctionParameters[3] = null;
  4949. this._isAlphaBlendDirty = true;
  4950. this._isBlendFunctionParametersDirty = false;
  4951. };
  4952. _AlphaState.prototype.apply = function (gl) {
  4953. if (!this.isDirty) {
  4954. return;
  4955. }
  4956. // Alpha blend
  4957. if (this._isAlphaBlendDirty) {
  4958. if (this._alphaBlend) {
  4959. gl.enable(gl.BLEND);
  4960. }
  4961. else {
  4962. gl.disable(gl.BLEND);
  4963. }
  4964. this._isAlphaBlendDirty = false;
  4965. }
  4966. // Alpha function
  4967. if (this._isBlendFunctionParametersDirty) {
  4968. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4969. this._isBlendFunctionParametersDirty = false;
  4970. }
  4971. };
  4972. return _AlphaState;
  4973. })();
  4974. Internals._AlphaState = _AlphaState;
  4975. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4976. })(BABYLON || (BABYLON = {}));
  4977. var BABYLON;
  4978. (function (BABYLON) {
  4979. var Internals;
  4980. (function (Internals) {
  4981. var _DepthCullingState = (function () {
  4982. function _DepthCullingState() {
  4983. this._isDepthTestDirty = false;
  4984. this._isDepthMaskDirty = false;
  4985. this._isDepthFuncDirty = false;
  4986. this._isCullFaceDirty = false;
  4987. this._isCullDirty = false;
  4988. this._isZOffsetDirty = false;
  4989. }
  4990. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4991. get: function () {
  4992. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4993. },
  4994. enumerable: true,
  4995. configurable: true
  4996. });
  4997. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4998. get: function () {
  4999. return this._zOffset;
  5000. },
  5001. set: function (value) {
  5002. if (this._zOffset === value) {
  5003. return;
  5004. }
  5005. this._zOffset = value;
  5006. this._isZOffsetDirty = true;
  5007. },
  5008. enumerable: true,
  5009. configurable: true
  5010. });
  5011. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5012. get: function () {
  5013. return this._cullFace;
  5014. },
  5015. set: function (value) {
  5016. if (this._cullFace === value) {
  5017. return;
  5018. }
  5019. this._cullFace = value;
  5020. this._isCullFaceDirty = true;
  5021. },
  5022. enumerable: true,
  5023. configurable: true
  5024. });
  5025. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5026. get: function () {
  5027. return this._cull;
  5028. },
  5029. set: function (value) {
  5030. if (this._cull === value) {
  5031. return;
  5032. }
  5033. this._cull = value;
  5034. this._isCullDirty = true;
  5035. },
  5036. enumerable: true,
  5037. configurable: true
  5038. });
  5039. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5040. get: function () {
  5041. return this._depthFunc;
  5042. },
  5043. set: function (value) {
  5044. if (this._depthFunc === value) {
  5045. return;
  5046. }
  5047. this._depthFunc = value;
  5048. this._isDepthFuncDirty = true;
  5049. },
  5050. enumerable: true,
  5051. configurable: true
  5052. });
  5053. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5054. get: function () {
  5055. return this._depthMask;
  5056. },
  5057. set: function (value) {
  5058. if (this._depthMask === value) {
  5059. return;
  5060. }
  5061. this._depthMask = value;
  5062. this._isDepthMaskDirty = true;
  5063. },
  5064. enumerable: true,
  5065. configurable: true
  5066. });
  5067. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5068. get: function () {
  5069. return this._depthTest;
  5070. },
  5071. set: function (value) {
  5072. if (this._depthTest === value) {
  5073. return;
  5074. }
  5075. this._depthTest = value;
  5076. this._isDepthTestDirty = true;
  5077. },
  5078. enumerable: true,
  5079. configurable: true
  5080. });
  5081. _DepthCullingState.prototype.reset = function () {
  5082. this._depthMask = true;
  5083. this._depthTest = true;
  5084. this._depthFunc = null;
  5085. this._cull = null;
  5086. this._cullFace = null;
  5087. this._zOffset = 0;
  5088. this._isDepthTestDirty = true;
  5089. this._isDepthMaskDirty = true;
  5090. this._isDepthFuncDirty = false;
  5091. this._isCullFaceDirty = false;
  5092. this._isCullDirty = false;
  5093. this._isZOffsetDirty = false;
  5094. };
  5095. _DepthCullingState.prototype.apply = function (gl) {
  5096. if (!this.isDirty) {
  5097. return;
  5098. }
  5099. // Cull
  5100. if (this._isCullDirty) {
  5101. if (this.cull) {
  5102. gl.enable(gl.CULL_FACE);
  5103. }
  5104. else {
  5105. gl.disable(gl.CULL_FACE);
  5106. }
  5107. this._isCullDirty = false;
  5108. }
  5109. // Cull face
  5110. if (this._isCullFaceDirty) {
  5111. gl.cullFace(this.cullFace);
  5112. this._isCullFaceDirty = false;
  5113. }
  5114. // Depth mask
  5115. if (this._isDepthMaskDirty) {
  5116. gl.depthMask(this.depthMask);
  5117. this._isDepthMaskDirty = false;
  5118. }
  5119. // Depth test
  5120. if (this._isDepthTestDirty) {
  5121. if (this.depthTest) {
  5122. gl.enable(gl.DEPTH_TEST);
  5123. }
  5124. else {
  5125. gl.disable(gl.DEPTH_TEST);
  5126. }
  5127. this._isDepthTestDirty = false;
  5128. }
  5129. // Depth func
  5130. if (this._isDepthFuncDirty) {
  5131. gl.depthFunc(this.depthFunc);
  5132. this._isDepthFuncDirty = false;
  5133. }
  5134. // zOffset
  5135. if (this._isZOffsetDirty) {
  5136. if (this.zOffset) {
  5137. gl.enable(gl.POLYGON_OFFSET_FILL);
  5138. gl.polygonOffset(this.zOffset, 0);
  5139. }
  5140. else {
  5141. gl.disable(gl.POLYGON_OFFSET_FILL);
  5142. }
  5143. this._isZOffsetDirty = false;
  5144. }
  5145. };
  5146. return _DepthCullingState;
  5147. })();
  5148. Internals._DepthCullingState = _DepthCullingState;
  5149. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5150. })(BABYLON || (BABYLON = {}));
  5151. var BABYLON;
  5152. (function (BABYLON) {
  5153. var compileShader = function (gl, source, type, defines) {
  5154. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5155. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5156. gl.compileShader(shader);
  5157. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5158. throw new Error(gl.getShaderInfoLog(shader));
  5159. }
  5160. return shader;
  5161. };
  5162. var getWebGLTextureType = function (gl, type) {
  5163. var textureType = gl.UNSIGNED_BYTE;
  5164. if (type === Engine.TEXTURETYPE_FLOAT)
  5165. textureType = gl.FLOAT;
  5166. return textureType;
  5167. };
  5168. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5169. var magFilter = gl.NEAREST;
  5170. var minFilter = gl.NEAREST;
  5171. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5172. magFilter = gl.LINEAR;
  5173. if (generateMipMaps) {
  5174. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5175. }
  5176. else {
  5177. minFilter = gl.LINEAR;
  5178. }
  5179. }
  5180. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5181. magFilter = gl.LINEAR;
  5182. if (generateMipMaps) {
  5183. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5184. }
  5185. else {
  5186. minFilter = gl.LINEAR;
  5187. }
  5188. }
  5189. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5190. magFilter = gl.NEAREST;
  5191. if (generateMipMaps) {
  5192. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5193. }
  5194. else {
  5195. minFilter = gl.NEAREST;
  5196. }
  5197. }
  5198. return {
  5199. min: minFilter,
  5200. mag: magFilter
  5201. };
  5202. };
  5203. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5204. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5205. var engine = scene.getEngine();
  5206. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5207. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5208. gl.bindTexture(gl.TEXTURE_2D, texture);
  5209. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5210. texture._baseWidth = width;
  5211. texture._baseHeight = height;
  5212. texture._width = potWidth;
  5213. texture._height = potHeight;
  5214. texture.isReady = true;
  5215. processFunction(potWidth, potHeight);
  5216. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5219. if (!noMipmap && !isCompressed) {
  5220. gl.generateMipmap(gl.TEXTURE_2D);
  5221. }
  5222. gl.bindTexture(gl.TEXTURE_2D, null);
  5223. engine.resetTextureCache();
  5224. scene._removePendingData(texture);
  5225. if (onLoad) {
  5226. onLoad();
  5227. }
  5228. };
  5229. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5230. var img;
  5231. var onload = function () {
  5232. loadedImages[index] = img;
  5233. loadedImages._internalCount++;
  5234. scene._removePendingData(img);
  5235. if (loadedImages._internalCount === 6) {
  5236. onfinish(loadedImages);
  5237. }
  5238. };
  5239. var onerror = function () {
  5240. scene._removePendingData(img);
  5241. };
  5242. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5243. scene._addPendingData(img);
  5244. };
  5245. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5246. var loadedImages = [];
  5247. loadedImages._internalCount = 0;
  5248. for (var index = 0; index < 6; index++) {
  5249. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5250. }
  5251. };
  5252. var EngineCapabilities = (function () {
  5253. function EngineCapabilities() {
  5254. }
  5255. return EngineCapabilities;
  5256. })();
  5257. BABYLON.EngineCapabilities = EngineCapabilities;
  5258. /**
  5259. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5260. */
  5261. var Engine = (function () {
  5262. /**
  5263. * @constructor
  5264. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5265. * @param {boolean} [antialias] - enable antialias
  5266. * @param options - further options to be sent to the getContext function
  5267. */
  5268. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5269. var _this = this;
  5270. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5271. // Public members
  5272. this.isFullscreen = false;
  5273. this.isPointerLock = false;
  5274. this.cullBackFaces = true;
  5275. this.renderEvenInBackground = true;
  5276. // To enable/disable IDB support and avoid XHR on .manifest
  5277. this.enableOfflineSupport = true;
  5278. this.scenes = new Array();
  5279. this._windowIsBackground = false;
  5280. this._webGLVersion = "1.0";
  5281. this._drawCalls = 0;
  5282. this._renderingQueueLaunched = false;
  5283. this._activeRenderLoops = [];
  5284. // FPS
  5285. this.fpsRange = 60;
  5286. this.previousFramesDuration = [];
  5287. this.fps = 60;
  5288. this.deltaTime = 0;
  5289. // States
  5290. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5291. this._alphaState = new BABYLON.Internals._AlphaState();
  5292. this._alphaMode = Engine.ALPHA_DISABLE;
  5293. // Cache
  5294. this._loadedTexturesCache = new Array();
  5295. this._maxTextureChannels = 16;
  5296. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5297. this._compiledEffects = {};
  5298. this._uintIndicesCurrentlySet = false;
  5299. this._renderingCanvas = canvas;
  5300. options = options || {};
  5301. options.antialias = antialias;
  5302. if (options.preserveDrawingBuffer === undefined) {
  5303. options.preserveDrawingBuffer = false;
  5304. }
  5305. // GL
  5306. //try {
  5307. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5308. // if (this._gl) {
  5309. // this._webGLVersion = "2.0";
  5310. // }
  5311. //} catch (e) {
  5312. // // Do nothing
  5313. //}
  5314. if (!this._gl) {
  5315. try {
  5316. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5317. }
  5318. catch (e) {
  5319. throw new Error("WebGL not supported");
  5320. }
  5321. }
  5322. if (!this._gl) {
  5323. throw new Error("WebGL not supported");
  5324. }
  5325. this._onBlur = function () {
  5326. _this._windowIsBackground = true;
  5327. };
  5328. this._onFocus = function () {
  5329. _this._windowIsBackground = false;
  5330. };
  5331. window.addEventListener("blur", this._onBlur);
  5332. window.addEventListener("focus", this._onFocus);
  5333. // Viewport
  5334. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5335. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5336. this.resize();
  5337. // Caps
  5338. this._caps = new EngineCapabilities();
  5339. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5340. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5341. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5342. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5343. // Infos
  5344. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5345. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5346. if (rendererInfo != null) {
  5347. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5348. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5349. }
  5350. if (!this._glVendor) {
  5351. this._glVendor = "Unknown vendor";
  5352. }
  5353. if (!this._glRenderer) {
  5354. this._glRenderer = "Unknown renderer";
  5355. }
  5356. // Extensions
  5357. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5358. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5359. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5360. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  5361. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5362. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5363. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5364. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5365. this._caps.highPrecisionShaderSupported = true;
  5366. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5367. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5368. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5369. if (this._gl.getShaderPrecisionFormat) {
  5370. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5371. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5372. }
  5373. // Depth buffer
  5374. this.setDepthBuffer(true);
  5375. this.setDepthFunctionToLessOrEqual();
  5376. this.setDepthWrite(true);
  5377. // Fullscreen
  5378. this._onFullscreenChange = function () {
  5379. if (document.fullscreen !== undefined) {
  5380. _this.isFullscreen = document.fullscreen;
  5381. }
  5382. else if (document.mozFullScreen !== undefined) {
  5383. _this.isFullscreen = document.mozFullScreen;
  5384. }
  5385. else if (document.webkitIsFullScreen !== undefined) {
  5386. _this.isFullscreen = document.webkitIsFullScreen;
  5387. }
  5388. else if (document.msIsFullScreen !== undefined) {
  5389. _this.isFullscreen = document.msIsFullScreen;
  5390. }
  5391. // Pointer lock
  5392. if (_this.isFullscreen && _this._pointerLockRequested) {
  5393. canvas.requestPointerLock = canvas.requestPointerLock ||
  5394. canvas.msRequestPointerLock ||
  5395. canvas.mozRequestPointerLock ||
  5396. canvas.webkitRequestPointerLock;
  5397. if (canvas.requestPointerLock) {
  5398. canvas.requestPointerLock();
  5399. }
  5400. }
  5401. };
  5402. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5403. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5404. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5405. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5406. // Pointer lock
  5407. this._onPointerLockChange = function () {
  5408. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5409. document.webkitPointerLockElement === canvas ||
  5410. document.msPointerLockElement === canvas ||
  5411. document.pointerLockElement === canvas);
  5412. };
  5413. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5414. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5415. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5416. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5417. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5418. Engine.audioEngine = new BABYLON.AudioEngine();
  5419. }
  5420. //default loading screen
  5421. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5422. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5423. }
  5424. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5425. get: function () {
  5426. return Engine._ALPHA_DISABLE;
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5432. get: function () {
  5433. return Engine._ALPHA_ONEONE;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. Object.defineProperty(Engine, "ALPHA_ADD", {
  5439. get: function () {
  5440. return Engine._ALPHA_ADD;
  5441. },
  5442. enumerable: true,
  5443. configurable: true
  5444. });
  5445. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5446. get: function () {
  5447. return Engine._ALPHA_COMBINE;
  5448. },
  5449. enumerable: true,
  5450. configurable: true
  5451. });
  5452. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5453. get: function () {
  5454. return Engine._ALPHA_SUBTRACT;
  5455. },
  5456. enumerable: true,
  5457. configurable: true
  5458. });
  5459. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5460. get: function () {
  5461. return Engine._ALPHA_MULTIPLY;
  5462. },
  5463. enumerable: true,
  5464. configurable: true
  5465. });
  5466. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5467. get: function () {
  5468. return Engine._ALPHA_MAXIMIZED;
  5469. },
  5470. enumerable: true,
  5471. configurable: true
  5472. });
  5473. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5474. get: function () {
  5475. return Engine._DELAYLOADSTATE_NONE;
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5481. get: function () {
  5482. return Engine._DELAYLOADSTATE_LOADED;
  5483. },
  5484. enumerable: true,
  5485. configurable: true
  5486. });
  5487. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5488. get: function () {
  5489. return Engine._DELAYLOADSTATE_LOADING;
  5490. },
  5491. enumerable: true,
  5492. configurable: true
  5493. });
  5494. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5495. get: function () {
  5496. return Engine._DELAYLOADSTATE_NOTLOADED;
  5497. },
  5498. enumerable: true,
  5499. configurable: true
  5500. });
  5501. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5502. get: function () {
  5503. return Engine._TEXTUREFORMAT_ALPHA;
  5504. },
  5505. enumerable: true,
  5506. configurable: true
  5507. });
  5508. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5509. get: function () {
  5510. return Engine._TEXTUREFORMAT_LUMINANCE;
  5511. },
  5512. enumerable: true,
  5513. configurable: true
  5514. });
  5515. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5516. get: function () {
  5517. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5518. },
  5519. enumerable: true,
  5520. configurable: true
  5521. });
  5522. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5523. get: function () {
  5524. return Engine._TEXTUREFORMAT_RGB;
  5525. },
  5526. enumerable: true,
  5527. configurable: true
  5528. });
  5529. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5530. get: function () {
  5531. return Engine._TEXTUREFORMAT_RGBA;
  5532. },
  5533. enumerable: true,
  5534. configurable: true
  5535. });
  5536. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5537. get: function () {
  5538. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5539. },
  5540. enumerable: true,
  5541. configurable: true
  5542. });
  5543. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5544. get: function () {
  5545. return Engine._TEXTURETYPE_FLOAT;
  5546. },
  5547. enumerable: true,
  5548. configurable: true
  5549. });
  5550. Object.defineProperty(Engine, "Version", {
  5551. get: function () {
  5552. return "2.4.0-alpha";
  5553. },
  5554. enumerable: true,
  5555. configurable: true
  5556. });
  5557. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5558. get: function () {
  5559. return this._webGLVersion;
  5560. },
  5561. enumerable: true,
  5562. configurable: true
  5563. });
  5564. Engine.prototype._prepareWorkingCanvas = function () {
  5565. if (this._workingCanvas) {
  5566. return;
  5567. }
  5568. this._workingCanvas = document.createElement("canvas");
  5569. this._workingContext = this._workingCanvas.getContext("2d");
  5570. };
  5571. Engine.prototype.resetTextureCache = function () {
  5572. for (var index = 0; index < this._maxTextureChannels; index++) {
  5573. this._activeTexturesCache[index] = null;
  5574. }
  5575. };
  5576. Engine.prototype.getGlInfo = function () {
  5577. return {
  5578. vendor: this._glVendor,
  5579. renderer: this._glRenderer,
  5580. version: this._glVersion
  5581. };
  5582. };
  5583. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5584. if (useScreen === void 0) { useScreen = false; }
  5585. var viewport = camera.viewport;
  5586. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5587. };
  5588. Engine.prototype.getRenderWidth = function (useScreen) {
  5589. if (useScreen === void 0) { useScreen = false; }
  5590. if (!useScreen && this._currentRenderTarget) {
  5591. return this._currentRenderTarget._width;
  5592. }
  5593. return this._renderingCanvas.width;
  5594. };
  5595. Engine.prototype.getRenderHeight = function (useScreen) {
  5596. if (useScreen === void 0) { useScreen = false; }
  5597. if (!useScreen && this._currentRenderTarget) {
  5598. return this._currentRenderTarget._height;
  5599. }
  5600. return this._renderingCanvas.height;
  5601. };
  5602. Engine.prototype.getRenderingCanvas = function () {
  5603. return this._renderingCanvas;
  5604. };
  5605. Engine.prototype.getRenderingCanvasClientRect = function () {
  5606. return this._renderingCanvas.getBoundingClientRect();
  5607. };
  5608. Engine.prototype.setHardwareScalingLevel = function (level) {
  5609. this._hardwareScalingLevel = level;
  5610. this.resize();
  5611. };
  5612. Engine.prototype.getHardwareScalingLevel = function () {
  5613. return this._hardwareScalingLevel;
  5614. };
  5615. Engine.prototype.getLoadedTexturesCache = function () {
  5616. return this._loadedTexturesCache;
  5617. };
  5618. Engine.prototype.getCaps = function () {
  5619. return this._caps;
  5620. };
  5621. Object.defineProperty(Engine.prototype, "drawCalls", {
  5622. get: function () {
  5623. return this._drawCalls;
  5624. },
  5625. enumerable: true,
  5626. configurable: true
  5627. });
  5628. // Methods
  5629. Engine.prototype.resetDrawCalls = function () {
  5630. this._drawCalls = 0;
  5631. };
  5632. Engine.prototype.setDepthFunctionToGreater = function () {
  5633. this._depthCullingState.depthFunc = this._gl.GREATER;
  5634. };
  5635. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5636. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5637. };
  5638. Engine.prototype.setDepthFunctionToLess = function () {
  5639. this._depthCullingState.depthFunc = this._gl.LESS;
  5640. };
  5641. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5642. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5643. };
  5644. /**
  5645. * stop executing a render loop function and remove it from the execution array
  5646. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5647. */
  5648. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5649. if (!renderFunction) {
  5650. this._activeRenderLoops = [];
  5651. return;
  5652. }
  5653. var index = this._activeRenderLoops.indexOf(renderFunction);
  5654. if (index >= 0) {
  5655. this._activeRenderLoops.splice(index, 1);
  5656. }
  5657. };
  5658. Engine.prototype._renderLoop = function () {
  5659. var shouldRender = true;
  5660. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5661. shouldRender = false;
  5662. }
  5663. if (shouldRender) {
  5664. // Start new frame
  5665. this.beginFrame();
  5666. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5667. var renderFunction = this._activeRenderLoops[index];
  5668. renderFunction();
  5669. }
  5670. // Present
  5671. this.endFrame();
  5672. }
  5673. if (this._activeRenderLoops.length > 0) {
  5674. // Register new frame
  5675. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5676. }
  5677. else {
  5678. this._renderingQueueLaunched = false;
  5679. }
  5680. };
  5681. /**
  5682. * Register and execute a render loop. The engine can have more than one render function.
  5683. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5684. * @example
  5685. * engine.runRenderLoop(function () {
  5686. * scene.render()
  5687. * })
  5688. */
  5689. Engine.prototype.runRenderLoop = function (renderFunction) {
  5690. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5691. return;
  5692. }
  5693. this._activeRenderLoops.push(renderFunction);
  5694. if (!this._renderingQueueLaunched) {
  5695. this._renderingQueueLaunched = true;
  5696. this._bindedRenderFunction = this._renderLoop.bind(this);
  5697. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5698. }
  5699. };
  5700. /**
  5701. * Toggle full screen mode.
  5702. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5703. */
  5704. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5705. if (this.isFullscreen) {
  5706. BABYLON.Tools.ExitFullscreen();
  5707. }
  5708. else {
  5709. this._pointerLockRequested = requestPointerLock;
  5710. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5711. }
  5712. };
  5713. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5714. this.applyStates();
  5715. if (backBuffer) {
  5716. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5717. }
  5718. if (depthStencil && this._depthCullingState.depthMask) {
  5719. this._gl.clearDepth(1.0);
  5720. }
  5721. var mode = 0;
  5722. if (backBuffer) {
  5723. mode |= this._gl.COLOR_BUFFER_BIT;
  5724. }
  5725. if (depthStencil && this._depthCullingState.depthMask) {
  5726. mode |= this._gl.DEPTH_BUFFER_BIT;
  5727. }
  5728. this._gl.clear(mode);
  5729. };
  5730. /**
  5731. * Set the WebGL's viewport
  5732. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5733. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5734. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5735. */
  5736. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5737. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5738. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5739. var x = viewport.x || 0;
  5740. var y = viewport.y || 0;
  5741. this._cachedViewport = viewport;
  5742. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5743. };
  5744. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5745. this._cachedViewport = null;
  5746. this._gl.viewport(x, y, width, height);
  5747. };
  5748. Engine.prototype.beginFrame = function () {
  5749. this._measureFps();
  5750. };
  5751. Engine.prototype.endFrame = function () {
  5752. //this.flushFramebuffer();
  5753. };
  5754. /**
  5755. * resize the view according to the canvas' size.
  5756. * @example
  5757. * window.addEventListener("resize", function () {
  5758. * engine.resize();
  5759. * });
  5760. */
  5761. Engine.prototype.resize = function () {
  5762. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5763. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5764. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5765. for (var index = 0; index < this.scenes.length; index++) {
  5766. var scene = this.scenes[index];
  5767. if (scene.debugLayer.isVisible()) {
  5768. scene.debugLayer._syncPositions();
  5769. }
  5770. }
  5771. };
  5772. /**
  5773. * force a specific size of the canvas
  5774. * @param {number} width - the new canvas' width
  5775. * @param {number} height - the new canvas' height
  5776. */
  5777. Engine.prototype.setSize = function (width, height) {
  5778. this._renderingCanvas.width = width;
  5779. this._renderingCanvas.height = height;
  5780. for (var index = 0; index < this.scenes.length; index++) {
  5781. var scene = this.scenes[index];
  5782. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5783. var cam = scene.cameras[camIndex];
  5784. cam._currentRenderId = 0;
  5785. }
  5786. }
  5787. };
  5788. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5789. this._currentRenderTarget = texture;
  5790. var gl = this._gl;
  5791. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5792. if (texture.isCube) {
  5793. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5794. }
  5795. else {
  5796. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5797. }
  5798. this._gl.viewport(0, 0, texture._width, texture._height);
  5799. this.wipeCaches();
  5800. };
  5801. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5802. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5803. this._currentRenderTarget = null;
  5804. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5805. var gl = this._gl;
  5806. gl.bindTexture(gl.TEXTURE_2D, texture);
  5807. gl.generateMipmap(gl.TEXTURE_2D);
  5808. gl.bindTexture(gl.TEXTURE_2D, null);
  5809. }
  5810. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5811. };
  5812. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5813. if (texture.generateMipMaps) {
  5814. var gl = this._gl;
  5815. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5816. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5817. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5818. }
  5819. };
  5820. Engine.prototype.flushFramebuffer = function () {
  5821. this._gl.flush();
  5822. };
  5823. Engine.prototype.restoreDefaultFramebuffer = function () {
  5824. this._currentRenderTarget = null;
  5825. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5826. this.setViewport(this._cachedViewport);
  5827. this.wipeCaches();
  5828. };
  5829. // VBOs
  5830. Engine.prototype._resetVertexBufferBinding = function () {
  5831. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5832. this._cachedVertexBuffers = null;
  5833. };
  5834. Engine.prototype.createVertexBuffer = function (vertices) {
  5835. var vbo = this._gl.createBuffer();
  5836. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5837. if (vertices instanceof Float32Array) {
  5838. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5839. }
  5840. else {
  5841. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5842. }
  5843. this._resetVertexBufferBinding();
  5844. vbo.references = 1;
  5845. return vbo;
  5846. };
  5847. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5848. var vbo = this._gl.createBuffer();
  5849. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5850. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5851. this._resetVertexBufferBinding();
  5852. vbo.references = 1;
  5853. return vbo;
  5854. };
  5855. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5856. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5857. if (offset === undefined) {
  5858. offset = 0;
  5859. }
  5860. if (vertices instanceof Float32Array) {
  5861. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5862. }
  5863. else {
  5864. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5865. }
  5866. this._resetVertexBufferBinding();
  5867. };
  5868. Engine.prototype._resetIndexBufferBinding = function () {
  5869. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5870. this._cachedIndexBuffer = null;
  5871. };
  5872. Engine.prototype.createIndexBuffer = function (indices) {
  5873. var vbo = this._gl.createBuffer();
  5874. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5875. // Check for 32 bits indices
  5876. var arrayBuffer;
  5877. var need32Bits = false;
  5878. if (this._caps.uintIndices) {
  5879. for (var index = 0; index < indices.length; index++) {
  5880. if (indices[index] > 65535) {
  5881. need32Bits = true;
  5882. break;
  5883. }
  5884. }
  5885. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5886. }
  5887. else {
  5888. arrayBuffer = new Uint16Array(indices);
  5889. }
  5890. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5891. this._resetIndexBufferBinding();
  5892. vbo.references = 1;
  5893. vbo.is32Bits = need32Bits;
  5894. return vbo;
  5895. };
  5896. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5897. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5898. this._cachedVertexBuffers = vertexBuffer;
  5899. this._cachedEffectForVertexBuffers = effect;
  5900. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5901. var offset = 0;
  5902. for (var index = 0; index < vertexDeclaration.length; index++) {
  5903. var order = effect.getAttributeLocation(index);
  5904. if (order >= 0) {
  5905. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5906. }
  5907. offset += vertexDeclaration[index] * 4;
  5908. }
  5909. }
  5910. if (this._cachedIndexBuffer !== indexBuffer) {
  5911. this._cachedIndexBuffer = indexBuffer;
  5912. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5913. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5914. }
  5915. };
  5916. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5917. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5918. this._cachedVertexBuffers = vertexBuffers;
  5919. this._cachedEffectForVertexBuffers = effect;
  5920. var attributes = effect.getAttributesNames();
  5921. for (var index = 0; index < attributes.length; index++) {
  5922. var order = effect.getAttributeLocation(index);
  5923. if (order >= 0) {
  5924. var vertexBuffer = vertexBuffers[attributes[index]];
  5925. if (!vertexBuffer) {
  5926. continue;
  5927. }
  5928. var stride = vertexBuffer.getStrideSize();
  5929. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5930. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5931. }
  5932. }
  5933. }
  5934. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5935. this._cachedIndexBuffer = indexBuffer;
  5936. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5937. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5938. }
  5939. };
  5940. Engine.prototype._releaseBuffer = function (buffer) {
  5941. buffer.references--;
  5942. if (buffer.references === 0) {
  5943. this._gl.deleteBuffer(buffer);
  5944. return true;
  5945. }
  5946. return false;
  5947. };
  5948. Engine.prototype.createInstancesBuffer = function (capacity) {
  5949. var buffer = this._gl.createBuffer();
  5950. buffer.capacity = capacity;
  5951. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5952. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5953. return buffer;
  5954. };
  5955. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5956. this._gl.deleteBuffer(buffer);
  5957. };
  5958. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5959. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5960. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5961. for (var index = 0; index < 4; index++) {
  5962. var offsetLocation = offsetLocations[index];
  5963. this._gl.enableVertexAttribArray(offsetLocation);
  5964. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5965. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5966. }
  5967. };
  5968. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5969. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5970. for (var index = 0; index < 4; index++) {
  5971. var offsetLocation = offsetLocations[index];
  5972. this._gl.disableVertexAttribArray(offsetLocation);
  5973. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5974. }
  5975. };
  5976. Engine.prototype.applyStates = function () {
  5977. this._depthCullingState.apply(this._gl);
  5978. this._alphaState.apply(this._gl);
  5979. };
  5980. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5981. // Apply states
  5982. this.applyStates();
  5983. this._drawCalls++;
  5984. // Render
  5985. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5986. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5987. if (instancesCount) {
  5988. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5989. return;
  5990. }
  5991. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5992. };
  5993. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5994. // Apply states
  5995. this.applyStates();
  5996. this._drawCalls++;
  5997. if (instancesCount) {
  5998. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5999. return;
  6000. }
  6001. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6002. };
  6003. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6004. // Apply states
  6005. this.applyStates();
  6006. this._drawCalls++;
  6007. if (instancesCount) {
  6008. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6009. return;
  6010. }
  6011. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6012. };
  6013. // Shaders
  6014. Engine.prototype._releaseEffect = function (effect) {
  6015. if (this._compiledEffects[effect._key]) {
  6016. delete this._compiledEffects[effect._key];
  6017. if (effect.getProgram()) {
  6018. this._gl.deleteProgram(effect.getProgram());
  6019. }
  6020. }
  6021. };
  6022. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6023. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6024. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6025. var name = vertex + "+" + fragment + "@" + defines;
  6026. if (this._compiledEffects[name]) {
  6027. return this._compiledEffects[name];
  6028. }
  6029. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6030. effect._key = name;
  6031. this._compiledEffects[name] = effect;
  6032. return effect;
  6033. };
  6034. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6035. if (uniformsNames === void 0) { uniformsNames = []; }
  6036. if (samplers === void 0) { samplers = []; }
  6037. if (defines === void 0) { defines = ""; }
  6038. return this.createEffect({
  6039. vertex: "particles",
  6040. fragmentElement: fragmentName
  6041. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6042. };
  6043. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6044. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6045. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6046. var shaderProgram = this._gl.createProgram();
  6047. this._gl.attachShader(shaderProgram, vertexShader);
  6048. this._gl.attachShader(shaderProgram, fragmentShader);
  6049. this._gl.linkProgram(shaderProgram);
  6050. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6051. if (!linked) {
  6052. var error = this._gl.getProgramInfoLog(shaderProgram);
  6053. if (error) {
  6054. throw new Error(error);
  6055. }
  6056. }
  6057. this._gl.deleteShader(vertexShader);
  6058. this._gl.deleteShader(fragmentShader);
  6059. return shaderProgram;
  6060. };
  6061. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6062. var results = [];
  6063. for (var index = 0; index < uniformsNames.length; index++) {
  6064. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6065. }
  6066. return results;
  6067. };
  6068. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6069. var results = [];
  6070. for (var index = 0; index < attributesNames.length; index++) {
  6071. try {
  6072. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6073. }
  6074. catch (e) {
  6075. results.push(-1);
  6076. }
  6077. }
  6078. return results;
  6079. };
  6080. Engine.prototype.enableEffect = function (effect) {
  6081. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6082. if (effect && effect.onBind) {
  6083. effect.onBind(effect);
  6084. }
  6085. return;
  6086. }
  6087. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6088. // Use program
  6089. this._gl.useProgram(effect.getProgram());
  6090. for (var i in this._vertexAttribArrays) {
  6091. //make sure this is a number)
  6092. var iAsNumber = +i;
  6093. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6094. continue;
  6095. }
  6096. this._vertexAttribArrays[iAsNumber] = false;
  6097. this._gl.disableVertexAttribArray(iAsNumber);
  6098. }
  6099. var attributesCount = effect.getAttributesCount();
  6100. for (var index = 0; index < attributesCount; index++) {
  6101. // Attributes
  6102. var order = effect.getAttributeLocation(index);
  6103. if (order >= 0) {
  6104. this._vertexAttribArrays[order] = true;
  6105. this._gl.enableVertexAttribArray(order);
  6106. }
  6107. }
  6108. this._currentEffect = effect;
  6109. if (effect.onBind) {
  6110. effect.onBind(effect);
  6111. }
  6112. };
  6113. Engine.prototype.setArray = function (uniform, array) {
  6114. if (!uniform)
  6115. return;
  6116. this._gl.uniform1fv(uniform, array);
  6117. };
  6118. Engine.prototype.setArray2 = function (uniform, array) {
  6119. if (!uniform || array.length % 2 !== 0)
  6120. return;
  6121. this._gl.uniform2fv(uniform, array);
  6122. };
  6123. Engine.prototype.setArray3 = function (uniform, array) {
  6124. if (!uniform || array.length % 3 !== 0)
  6125. return;
  6126. this._gl.uniform3fv(uniform, array);
  6127. };
  6128. Engine.prototype.setArray4 = function (uniform, array) {
  6129. if (!uniform || array.length % 4 !== 0)
  6130. return;
  6131. this._gl.uniform4fv(uniform, array);
  6132. };
  6133. Engine.prototype.setMatrices = function (uniform, matrices) {
  6134. if (!uniform)
  6135. return;
  6136. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6137. };
  6138. Engine.prototype.setMatrix = function (uniform, matrix) {
  6139. if (!uniform)
  6140. return;
  6141. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6142. };
  6143. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6144. if (!uniform)
  6145. return;
  6146. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6147. };
  6148. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6149. if (!uniform)
  6150. return;
  6151. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6152. };
  6153. Engine.prototype.setFloat = function (uniform, value) {
  6154. if (!uniform)
  6155. return;
  6156. this._gl.uniform1f(uniform, value);
  6157. };
  6158. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6159. if (!uniform)
  6160. return;
  6161. this._gl.uniform2f(uniform, x, y);
  6162. };
  6163. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6164. if (!uniform)
  6165. return;
  6166. this._gl.uniform3f(uniform, x, y, z);
  6167. };
  6168. Engine.prototype.setBool = function (uniform, bool) {
  6169. if (!uniform)
  6170. return;
  6171. this._gl.uniform1i(uniform, bool);
  6172. };
  6173. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6174. if (!uniform)
  6175. return;
  6176. this._gl.uniform4f(uniform, x, y, z, w);
  6177. };
  6178. Engine.prototype.setColor3 = function (uniform, color3) {
  6179. if (!uniform)
  6180. return;
  6181. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6182. };
  6183. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6184. if (!uniform)
  6185. return;
  6186. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6187. };
  6188. // States
  6189. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6190. if (zOffset === void 0) { zOffset = 0; }
  6191. if (reverseSide === void 0) { reverseSide = false; }
  6192. // Culling
  6193. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6194. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6195. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6196. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6197. if (culling) {
  6198. this._depthCullingState.cullFace = cullFace;
  6199. this._depthCullingState.cull = true;
  6200. }
  6201. else {
  6202. this._depthCullingState.cull = false;
  6203. }
  6204. }
  6205. // Z offset
  6206. this._depthCullingState.zOffset = zOffset;
  6207. };
  6208. Engine.prototype.setDepthBuffer = function (enable) {
  6209. this._depthCullingState.depthTest = enable;
  6210. };
  6211. Engine.prototype.getDepthWrite = function () {
  6212. return this._depthCullingState.depthMask;
  6213. };
  6214. Engine.prototype.setDepthWrite = function (enable) {
  6215. this._depthCullingState.depthMask = enable;
  6216. };
  6217. Engine.prototype.setColorWrite = function (enable) {
  6218. this._gl.colorMask(enable, enable, enable, enable);
  6219. };
  6220. Engine.prototype.setAlphaMode = function (mode) {
  6221. if (this._alphaMode === mode) {
  6222. return;
  6223. }
  6224. switch (mode) {
  6225. case Engine.ALPHA_DISABLE:
  6226. this.setDepthWrite(true);
  6227. this._alphaState.alphaBlend = false;
  6228. break;
  6229. case Engine.ALPHA_COMBINE:
  6230. this.setDepthWrite(false);
  6231. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6232. this._alphaState.alphaBlend = true;
  6233. break;
  6234. case Engine.ALPHA_ONEONE:
  6235. this.setDepthWrite(false);
  6236. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6237. this._alphaState.alphaBlend = true;
  6238. break;
  6239. case Engine.ALPHA_ADD:
  6240. this.setDepthWrite(false);
  6241. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6242. this._alphaState.alphaBlend = true;
  6243. break;
  6244. case Engine.ALPHA_SUBTRACT:
  6245. this.setDepthWrite(false);
  6246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6247. this._alphaState.alphaBlend = true;
  6248. break;
  6249. case Engine.ALPHA_MULTIPLY:
  6250. this.setDepthWrite(false);
  6251. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6252. this._alphaState.alphaBlend = true;
  6253. break;
  6254. case Engine.ALPHA_MAXIMIZED:
  6255. this.setDepthWrite(false);
  6256. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6257. this._alphaState.alphaBlend = true;
  6258. break;
  6259. }
  6260. this._alphaMode = mode;
  6261. };
  6262. Engine.prototype.getAlphaMode = function () {
  6263. return this._alphaMode;
  6264. };
  6265. Engine.prototype.setAlphaTesting = function (enable) {
  6266. this._alphaTest = enable;
  6267. };
  6268. Engine.prototype.getAlphaTesting = function () {
  6269. return this._alphaTest;
  6270. };
  6271. // Textures
  6272. Engine.prototype.wipeCaches = function () {
  6273. this.resetTextureCache();
  6274. this._currentEffect = null;
  6275. this._depthCullingState.reset();
  6276. this._alphaState.reset();
  6277. this._cachedVertexBuffers = null;
  6278. this._cachedIndexBuffer = null;
  6279. this._cachedEffectForVertexBuffers = null;
  6280. };
  6281. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6282. var gl = this._gl;
  6283. gl.bindTexture(gl.TEXTURE_2D, texture);
  6284. var magFilter = gl.NEAREST;
  6285. var minFilter = gl.NEAREST;
  6286. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6287. magFilter = gl.LINEAR;
  6288. minFilter = gl.LINEAR;
  6289. }
  6290. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6291. magFilter = gl.LINEAR;
  6292. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6293. }
  6294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6296. gl.bindTexture(gl.TEXTURE_2D, null);
  6297. texture.samplingMode = samplingMode;
  6298. };
  6299. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6300. var _this = this;
  6301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6302. if (onLoad === void 0) { onLoad = null; }
  6303. if (onError === void 0) { onError = null; }
  6304. if (buffer === void 0) { buffer = null; }
  6305. var texture = this._gl.createTexture();
  6306. var extension;
  6307. var fromData = false;
  6308. if (url.substr(0, 5) === "data:") {
  6309. fromData = true;
  6310. }
  6311. if (!fromData)
  6312. extension = url.substr(url.length - 4, 4).toLowerCase();
  6313. else {
  6314. var oldUrl = url;
  6315. fromData = oldUrl.split(':');
  6316. url = oldUrl;
  6317. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6318. }
  6319. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6320. var isTGA = (extension === ".tga");
  6321. scene._addPendingData(texture);
  6322. texture.url = url;
  6323. texture.noMipmap = noMipmap;
  6324. texture.references = 1;
  6325. texture.samplingMode = samplingMode;
  6326. this._loadedTexturesCache.push(texture);
  6327. var onerror = function () {
  6328. scene._removePendingData(texture);
  6329. if (onError) {
  6330. onError();
  6331. }
  6332. };
  6333. var callback;
  6334. if (isTGA) {
  6335. callback = function (arrayBuffer) {
  6336. var data = new Uint8Array(arrayBuffer);
  6337. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6338. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6339. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6340. }, onLoad, samplingMode);
  6341. };
  6342. if (!(fromData instanceof Array))
  6343. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6344. callback(arrayBuffer);
  6345. }, onerror, scene.database, true);
  6346. else
  6347. callback(buffer);
  6348. }
  6349. else if (isDDS) {
  6350. callback = function (data) {
  6351. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6352. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6353. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6354. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6355. }, onLoad, samplingMode);
  6356. };
  6357. if (!(fromData instanceof Array))
  6358. BABYLON.Tools.LoadFile(url, function (data) {
  6359. callback(data);
  6360. }, onerror, scene.database, true);
  6361. else
  6362. callback(buffer);
  6363. }
  6364. else {
  6365. var onload = function (img) {
  6366. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6367. var isPot = (img.width === potWidth && img.height === potHeight);
  6368. if (!isPot) {
  6369. _this._prepareWorkingCanvas();
  6370. _this._workingCanvas.width = potWidth;
  6371. _this._workingCanvas.height = potHeight;
  6372. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6373. _this._workingContext.imageSmoothingEnabled = false;
  6374. _this._workingContext.mozImageSmoothingEnabled = false;
  6375. _this._workingContext.oImageSmoothingEnabled = false;
  6376. _this._workingContext.webkitImageSmoothingEnabled = false;
  6377. _this._workingContext.msImageSmoothingEnabled = false;
  6378. }
  6379. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6380. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6381. _this._workingContext.imageSmoothingEnabled = true;
  6382. _this._workingContext.mozImageSmoothingEnabled = true;
  6383. _this._workingContext.oImageSmoothingEnabled = true;
  6384. _this._workingContext.webkitImageSmoothingEnabled = true;
  6385. _this._workingContext.msImageSmoothingEnabled = true;
  6386. }
  6387. }
  6388. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6389. }, onLoad, samplingMode);
  6390. };
  6391. if (!(fromData instanceof Array))
  6392. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6393. else
  6394. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6395. }
  6396. return texture;
  6397. };
  6398. Engine.prototype._getInternalFormat = function (format) {
  6399. var internalFormat = this._gl.RGBA;
  6400. switch (format) {
  6401. case Engine.TEXTUREFORMAT_ALPHA:
  6402. internalFormat = this._gl.ALPHA;
  6403. break;
  6404. case Engine.TEXTUREFORMAT_LUMINANCE:
  6405. internalFormat = this._gl.LUMINANCE;
  6406. break;
  6407. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6408. internalFormat = this._gl.LUMINANCE_ALPHA;
  6409. break;
  6410. case Engine.TEXTUREFORMAT_RGB:
  6411. internalFormat = this._gl.RGB;
  6412. break;
  6413. case Engine.TEXTUREFORMAT_RGBA:
  6414. internalFormat = this._gl.RGBA;
  6415. break;
  6416. }
  6417. return internalFormat;
  6418. };
  6419. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6420. if (compression === void 0) { compression = null; }
  6421. var internalFormat = this._getInternalFormat(format);
  6422. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6423. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6424. if (compression) {
  6425. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6426. }
  6427. else {
  6428. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6429. }
  6430. if (texture.generateMipMaps) {
  6431. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6432. }
  6433. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6434. this.resetTextureCache();
  6435. texture.isReady = true;
  6436. };
  6437. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6438. if (compression === void 0) { compression = null; }
  6439. var texture = this._gl.createTexture();
  6440. texture._baseWidth = width;
  6441. texture._baseHeight = height;
  6442. texture._width = width;
  6443. texture._height = height;
  6444. texture.references = 1;
  6445. this.updateRawTexture(texture, data, format, invertY, compression);
  6446. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6447. // Filters
  6448. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6449. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6450. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6451. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6452. texture.samplingMode = samplingMode;
  6453. this._loadedTexturesCache.push(texture);
  6454. return texture;
  6455. };
  6456. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6457. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6458. var texture = this._gl.createTexture();
  6459. texture._baseWidth = width;
  6460. texture._baseHeight = height;
  6461. if (forceExponantOfTwo) {
  6462. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6463. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6464. }
  6465. this.resetTextureCache();
  6466. texture._width = width;
  6467. texture._height = height;
  6468. texture.isReady = false;
  6469. texture.generateMipMaps = generateMipMaps;
  6470. texture.references = 1;
  6471. texture.samplingMode = samplingMode;
  6472. this.updateTextureSamplingMode(samplingMode, texture);
  6473. this._loadedTexturesCache.push(texture);
  6474. return texture;
  6475. };
  6476. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6477. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6478. if (texture.isCube) {
  6479. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6480. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6481. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6482. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6483. }
  6484. else {
  6485. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6486. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6487. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6488. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6489. }
  6490. };
  6491. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6492. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6493. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6494. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6495. if (texture.generateMipMaps) {
  6496. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6497. }
  6498. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6499. this.resetTextureCache();
  6500. texture.isReady = true;
  6501. };
  6502. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6503. if (texture._isDisabled) {
  6504. return;
  6505. }
  6506. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6507. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6508. try {
  6509. // Testing video texture support
  6510. if (this._videoTextureSupported === undefined) {
  6511. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6512. if (this._gl.getError() !== 0) {
  6513. this._videoTextureSupported = false;
  6514. }
  6515. else {
  6516. this._videoTextureSupported = true;
  6517. }
  6518. }
  6519. // Copy video through the current working canvas if video texture is not supported
  6520. if (!this._videoTextureSupported) {
  6521. if (!texture._workingCanvas) {
  6522. texture._workingCanvas = document.createElement("canvas");
  6523. texture._workingContext = texture._workingCanvas.getContext("2d");
  6524. texture._workingCanvas.width = texture._width;
  6525. texture._workingCanvas.height = texture._height;
  6526. }
  6527. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6528. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6529. }
  6530. else {
  6531. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6532. }
  6533. if (texture.generateMipMaps) {
  6534. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6535. }
  6536. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6537. this.resetTextureCache();
  6538. texture.isReady = true;
  6539. }
  6540. catch (ex) {
  6541. // Something unexpected
  6542. // Let's disable the texture
  6543. texture._isDisabled = true;
  6544. }
  6545. };
  6546. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6547. // old version had a "generateMipMaps" arg instead of options.
  6548. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6549. // in the same way, generateDepthBuffer is defaulted to true
  6550. var generateMipMaps = false;
  6551. var generateDepthBuffer = true;
  6552. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6553. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6554. if (options !== undefined) {
  6555. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6556. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6557. type = options.type === undefined ? type : options.type;
  6558. if (options.samplingMode !== undefined) {
  6559. samplingMode = options.samplingMode;
  6560. }
  6561. if (type === Engine.TEXTURETYPE_FLOAT) {
  6562. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6563. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6564. }
  6565. }
  6566. var gl = this._gl;
  6567. var texture = gl.createTexture();
  6568. gl.bindTexture(gl.TEXTURE_2D, texture);
  6569. var width = size.width || size;
  6570. var height = size.height || size;
  6571. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6572. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6573. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6574. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6575. }
  6576. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6577. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6578. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6579. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6580. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6581. var depthBuffer;
  6582. // Create the depth buffer
  6583. if (generateDepthBuffer) {
  6584. depthBuffer = gl.createRenderbuffer();
  6585. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6586. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6587. }
  6588. // Create the framebuffer
  6589. var framebuffer = gl.createFramebuffer();
  6590. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6591. if (generateDepthBuffer) {
  6592. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6593. }
  6594. if (generateMipMaps) {
  6595. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6596. }
  6597. // Unbind
  6598. gl.bindTexture(gl.TEXTURE_2D, null);
  6599. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6600. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6601. texture._framebuffer = framebuffer;
  6602. if (generateDepthBuffer) {
  6603. texture._depthBuffer = depthBuffer;
  6604. }
  6605. texture._width = width;
  6606. texture._height = height;
  6607. texture.isReady = true;
  6608. texture.generateMipMaps = generateMipMaps;
  6609. texture.references = 1;
  6610. texture.samplingMode = samplingMode;
  6611. this.resetTextureCache();
  6612. this._loadedTexturesCache.push(texture);
  6613. return texture;
  6614. };
  6615. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6616. var gl = this._gl;
  6617. var texture = gl.createTexture();
  6618. var generateMipMaps = true;
  6619. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6620. if (options !== undefined) {
  6621. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6622. if (options.samplingMode !== undefined) {
  6623. samplingMode = options.samplingMode;
  6624. }
  6625. }
  6626. texture.isCube = true;
  6627. texture.references = 1;
  6628. texture.generateMipMaps = generateMipMaps;
  6629. texture.references = 1;
  6630. texture.samplingMode = samplingMode;
  6631. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6632. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6633. for (var face = 0; face < 6; face++) {
  6634. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6635. }
  6636. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6637. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6640. // Create the depth buffer
  6641. var depthBuffer = gl.createRenderbuffer();
  6642. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6643. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6644. // Create the framebuffer
  6645. var framebuffer = gl.createFramebuffer();
  6646. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6647. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6648. // Mipmaps
  6649. if (texture.generateMipMaps) {
  6650. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6651. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6652. }
  6653. // Unbind
  6654. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6655. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6656. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6657. texture._framebuffer = framebuffer;
  6658. texture._depthBuffer = depthBuffer;
  6659. this.resetTextureCache();
  6660. texture._width = size;
  6661. texture._height = size;
  6662. texture.isReady = true;
  6663. return texture;
  6664. };
  6665. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6666. var _this = this;
  6667. var gl = this._gl;
  6668. var texture = gl.createTexture();
  6669. texture.isCube = true;
  6670. texture.url = rootUrl;
  6671. texture.references = 1;
  6672. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6673. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6674. if (isDDS) {
  6675. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6676. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6677. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6678. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6679. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6680. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6681. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6682. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6683. }
  6684. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6688. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6689. _this.resetTextureCache();
  6690. texture._width = info.width;
  6691. texture._height = info.height;
  6692. texture.isReady = true;
  6693. }, null, null, true);
  6694. }
  6695. else {
  6696. cascadeLoad(rootUrl, scene, function (imgs) {
  6697. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6698. var height = width;
  6699. _this._prepareWorkingCanvas();
  6700. _this._workingCanvas.width = width;
  6701. _this._workingCanvas.height = height;
  6702. var faces = [
  6703. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6704. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6705. ];
  6706. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6707. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6708. for (var index = 0; index < faces.length; index++) {
  6709. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6710. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6711. }
  6712. if (!noMipmap) {
  6713. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6714. }
  6715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6716. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6717. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6719. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6720. _this.resetTextureCache();
  6721. texture._width = width;
  6722. texture._height = height;
  6723. texture.isReady = true;
  6724. }, files);
  6725. }
  6726. return texture;
  6727. };
  6728. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6729. var _this = this;
  6730. var gl = this._gl;
  6731. var texture = gl.createTexture();
  6732. scene._addPendingData(texture);
  6733. texture.isCube = true;
  6734. texture.references = 1;
  6735. texture.url = url;
  6736. var internalFormat = this._getInternalFormat(format);
  6737. var textureType = gl.UNSIGNED_BYTE;
  6738. if (type === Engine.TEXTURETYPE_FLOAT) {
  6739. textureType = gl.FLOAT;
  6740. }
  6741. var width = size;
  6742. var height = width;
  6743. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6744. texture._width = width;
  6745. texture._height = height;
  6746. var onerror = function () {
  6747. scene._removePendingData(texture);
  6748. };
  6749. var internalCallback = function (data) {
  6750. var rgbeDataArrays = callback(data);
  6751. var facesIndex = [
  6752. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6753. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6754. ];
  6755. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6756. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6757. if (!noMipmap && isPot) {
  6758. if (mipmmapGenerator) {
  6759. var arrayTemp = [];
  6760. // Data are known to be in +X +Y +Z -X -Y -Z
  6761. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6762. arrayTemp.push(rgbeDataArrays[0]); // +X
  6763. arrayTemp.push(rgbeDataArrays[3]); // -X
  6764. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6765. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6766. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6767. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6768. var mipData = mipmmapGenerator(arrayTemp);
  6769. for (var level = 0; level < mipData.length; level++) {
  6770. var mipSize = width >> level;
  6771. // mipData is order in +X -X +Y -Y +Z -Z
  6772. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6773. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6774. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6775. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6776. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6777. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6778. }
  6779. }
  6780. else {
  6781. // Data are known to be in +X +Y +Z -X -Y -Z
  6782. for (var index = 0; index < facesIndex.length; index++) {
  6783. var faceData = rgbeDataArrays[index];
  6784. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6785. }
  6786. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6787. }
  6788. }
  6789. else {
  6790. noMipmap = true;
  6791. }
  6792. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6793. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6795. }
  6796. else {
  6797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6799. }
  6800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6802. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6803. texture.isReady = true;
  6804. _this.resetTextureCache();
  6805. scene._removePendingData(texture);
  6806. };
  6807. BABYLON.Tools.LoadFile(url, function (data) {
  6808. internalCallback(data);
  6809. }, onerror, scene.database, true);
  6810. return texture;
  6811. };
  6812. ;
  6813. Engine.prototype._releaseTexture = function (texture) {
  6814. var gl = this._gl;
  6815. if (texture._framebuffer) {
  6816. gl.deleteFramebuffer(texture._framebuffer);
  6817. }
  6818. if (texture._depthBuffer) {
  6819. gl.deleteRenderbuffer(texture._depthBuffer);
  6820. }
  6821. gl.deleteTexture(texture);
  6822. // Unbind channels
  6823. this.unbindAllTextures();
  6824. var index = this._loadedTexturesCache.indexOf(texture);
  6825. if (index !== -1) {
  6826. this._loadedTexturesCache.splice(index, 1);
  6827. }
  6828. };
  6829. Engine.prototype.bindSamplers = function (effect) {
  6830. this._gl.useProgram(effect.getProgram());
  6831. var samplers = effect.getSamplers();
  6832. for (var index = 0; index < samplers.length; index++) {
  6833. var uniform = effect.getUniform(samplers[index]);
  6834. this._gl.uniform1i(uniform, index);
  6835. }
  6836. this._currentEffect = null;
  6837. };
  6838. Engine.prototype._bindTexture = function (channel, texture) {
  6839. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6840. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6841. this._activeTexturesCache[channel] = null;
  6842. };
  6843. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6844. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6845. };
  6846. Engine.prototype.unbindAllTextures = function () {
  6847. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6848. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6849. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6850. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6851. this._activeTexturesCache[channel] = null;
  6852. }
  6853. };
  6854. Engine.prototype.setTexture = function (channel, texture) {
  6855. if (channel < 0) {
  6856. return;
  6857. }
  6858. // Not ready?
  6859. if (!texture || !texture.isReady()) {
  6860. if (this._activeTexturesCache[channel] != null) {
  6861. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6862. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6863. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6864. this._activeTexturesCache[channel] = null;
  6865. }
  6866. return;
  6867. }
  6868. // Video
  6869. var alreadyActivated = false;
  6870. if (texture instanceof BABYLON.VideoTexture) {
  6871. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6872. alreadyActivated = true;
  6873. texture.update();
  6874. }
  6875. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6876. texture.delayLoad();
  6877. return;
  6878. }
  6879. if (this._activeTexturesCache[channel] === texture) {
  6880. return;
  6881. }
  6882. this._activeTexturesCache[channel] = texture;
  6883. var internalTexture = texture.getInternalTexture();
  6884. if (!alreadyActivated) {
  6885. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6886. }
  6887. if (internalTexture.isCube) {
  6888. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6889. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6890. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6891. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6892. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6893. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6894. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6895. }
  6896. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6897. }
  6898. else {
  6899. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6900. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6901. internalTexture._cachedWrapU = texture.wrapU;
  6902. switch (texture.wrapU) {
  6903. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6904. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6905. break;
  6906. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6907. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6908. break;
  6909. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6910. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6911. break;
  6912. }
  6913. }
  6914. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6915. internalTexture._cachedWrapV = texture.wrapV;
  6916. switch (texture.wrapV) {
  6917. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6918. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6919. break;
  6920. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6921. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6922. break;
  6923. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6924. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6925. break;
  6926. }
  6927. }
  6928. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6929. }
  6930. };
  6931. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6932. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6933. var value = texture.anisotropicFilteringLevel;
  6934. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6935. value = 1;
  6936. }
  6937. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6938. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6939. texture._cachedAnisotropicFilteringLevel = value;
  6940. }
  6941. };
  6942. Engine.prototype.readPixels = function (x, y, width, height) {
  6943. var data = new Uint8Array(height * width * 4);
  6944. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6945. return data;
  6946. };
  6947. Engine.prototype.releaseInternalTexture = function (texture) {
  6948. if (!texture) {
  6949. return;
  6950. }
  6951. texture.references--;
  6952. // Final reference ?
  6953. if (texture.references === 0) {
  6954. var texturesCache = this.getLoadedTexturesCache();
  6955. var index = texturesCache.indexOf(texture);
  6956. if (index > -1) {
  6957. texturesCache.splice(index, 1);
  6958. }
  6959. this._releaseTexture(texture);
  6960. }
  6961. };
  6962. // Dispose
  6963. Engine.prototype.dispose = function () {
  6964. this.hideLoadingUI();
  6965. this.stopRenderLoop();
  6966. // Release scenes
  6967. while (this.scenes.length) {
  6968. this.scenes[0].dispose();
  6969. }
  6970. // Release audio engine
  6971. Engine.audioEngine.dispose();
  6972. // Release effects
  6973. for (var name in this._compiledEffects) {
  6974. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6975. }
  6976. // Unbind
  6977. for (var i in this._vertexAttribArrays) {
  6978. //making sure this is a string
  6979. var iAsNumber = +i;
  6980. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6981. continue;
  6982. }
  6983. this._gl.disableVertexAttribArray(iAsNumber);
  6984. }
  6985. this._gl = null;
  6986. // Events
  6987. window.removeEventListener("blur", this._onBlur);
  6988. window.removeEventListener("focus", this._onFocus);
  6989. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6990. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6991. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6992. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6993. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6994. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6995. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6996. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6997. };
  6998. // Loading screen
  6999. Engine.prototype.displayLoadingUI = function () {
  7000. this._loadingScreen.displayLoadingUI();
  7001. };
  7002. Engine.prototype.hideLoadingUI = function () {
  7003. this._loadingScreen.hideLoadingUI();
  7004. };
  7005. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7006. get: function () {
  7007. return this._loadingScreen;
  7008. },
  7009. set: function (loadingScreen) {
  7010. this._loadingScreen = loadingScreen;
  7011. },
  7012. enumerable: true,
  7013. configurable: true
  7014. });
  7015. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7016. set: function (text) {
  7017. this._loadingScreen.loadingUIText = text;
  7018. },
  7019. enumerable: true,
  7020. configurable: true
  7021. });
  7022. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7023. set: function (color) {
  7024. this._loadingScreen.loadingUIBackgroundColor = color;
  7025. },
  7026. enumerable: true,
  7027. configurable: true
  7028. });
  7029. // FPS
  7030. Engine.prototype.getFps = function () {
  7031. return this.fps;
  7032. };
  7033. Engine.prototype.getDeltaTime = function () {
  7034. return this.deltaTime;
  7035. };
  7036. Engine.prototype._measureFps = function () {
  7037. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7038. var length = this.previousFramesDuration.length;
  7039. if (length >= 2) {
  7040. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7041. }
  7042. if (length >= this.fpsRange) {
  7043. if (length > this.fpsRange) {
  7044. this.previousFramesDuration.splice(0, 1);
  7045. length = this.previousFramesDuration.length;
  7046. }
  7047. var sum = 0;
  7048. for (var id = 0; id < length - 1; id++) {
  7049. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7050. }
  7051. this.fps = 1000.0 / (sum / (length - 1));
  7052. }
  7053. };
  7054. // Statics
  7055. Engine.isSupported = function () {
  7056. try {
  7057. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7058. if (navigator.isCocoonJS) {
  7059. return true;
  7060. }
  7061. var tempcanvas = document.createElement("canvas");
  7062. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7063. return gl != null && !!window.WebGLRenderingContext;
  7064. }
  7065. catch (e) {
  7066. return false;
  7067. }
  7068. };
  7069. // Const statics
  7070. Engine._ALPHA_DISABLE = 0;
  7071. Engine._ALPHA_ADD = 1;
  7072. Engine._ALPHA_COMBINE = 2;
  7073. Engine._ALPHA_SUBTRACT = 3;
  7074. Engine._ALPHA_MULTIPLY = 4;
  7075. Engine._ALPHA_MAXIMIZED = 5;
  7076. Engine._ALPHA_ONEONE = 6;
  7077. Engine._DELAYLOADSTATE_NONE = 0;
  7078. Engine._DELAYLOADSTATE_LOADED = 1;
  7079. Engine._DELAYLOADSTATE_LOADING = 2;
  7080. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7081. Engine._TEXTUREFORMAT_ALPHA = 0;
  7082. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7083. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7084. Engine._TEXTUREFORMAT_RGB = 4;
  7085. Engine._TEXTUREFORMAT_RGBA = 5;
  7086. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7087. Engine._TEXTURETYPE_FLOAT = 1;
  7088. // Updatable statics so stick with vars here
  7089. Engine.CollisionsEpsilon = 0.001;
  7090. Engine.CodeRepository = "src/";
  7091. Engine.ShadersRepository = "src/Shaders/";
  7092. return Engine;
  7093. })();
  7094. BABYLON.Engine = Engine;
  7095. })(BABYLON || (BABYLON = {}));
  7096. var BABYLON;
  7097. (function (BABYLON) {
  7098. /**
  7099. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7100. */
  7101. var Node = (function () {
  7102. /**
  7103. * @constructor
  7104. * @param {string} name - the name and id to be given to this node
  7105. * @param {BABYLON.Scene} the scene this node will be added to
  7106. */
  7107. function Node(name, scene) {
  7108. this.state = "";
  7109. this.animations = new Array();
  7110. this._ranges = {};
  7111. this._childrenFlag = -1;
  7112. this._isEnabled = true;
  7113. this._isReady = true;
  7114. this._currentRenderId = -1;
  7115. this._parentRenderId = -1;
  7116. this.name = name;
  7117. this.id = name;
  7118. this._scene = scene;
  7119. this._initCache();
  7120. }
  7121. Node.prototype.getScene = function () {
  7122. return this._scene;
  7123. };
  7124. Node.prototype.getEngine = function () {
  7125. return this._scene.getEngine();
  7126. };
  7127. // override it in derived class
  7128. Node.prototype.getWorldMatrix = function () {
  7129. return BABYLON.Matrix.Identity();
  7130. };
  7131. // override it in derived class if you add new variables to the cache
  7132. // and call the parent class method
  7133. Node.prototype._initCache = function () {
  7134. this._cache = {};
  7135. this._cache.parent = undefined;
  7136. };
  7137. Node.prototype.updateCache = function (force) {
  7138. if (!force && this.isSynchronized())
  7139. return;
  7140. this._cache.parent = this.parent;
  7141. this._updateCache();
  7142. };
  7143. // override it in derived class if you add new variables to the cache
  7144. // and call the parent class method if !ignoreParentClass
  7145. Node.prototype._updateCache = function (ignoreParentClass) {
  7146. };
  7147. // override it in derived class if you add new variables to the cache
  7148. Node.prototype._isSynchronized = function () {
  7149. return true;
  7150. };
  7151. Node.prototype._markSyncedWithParent = function () {
  7152. this._parentRenderId = this.parent._currentRenderId;
  7153. };
  7154. Node.prototype.isSynchronizedWithParent = function () {
  7155. if (!this.parent) {
  7156. return true;
  7157. }
  7158. if (this._parentRenderId !== this.parent._currentRenderId) {
  7159. return false;
  7160. }
  7161. return this.parent.isSynchronized();
  7162. };
  7163. Node.prototype.isSynchronized = function (updateCache) {
  7164. var check = this.hasNewParent();
  7165. check = check || !this.isSynchronizedWithParent();
  7166. check = check || !this._isSynchronized();
  7167. if (updateCache)
  7168. this.updateCache(true);
  7169. return !check;
  7170. };
  7171. Node.prototype.hasNewParent = function (update) {
  7172. if (this._cache.parent === this.parent)
  7173. return false;
  7174. if (update)
  7175. this._cache.parent = this.parent;
  7176. return true;
  7177. };
  7178. /**
  7179. * Is this node ready to be used/rendered
  7180. * @return {boolean} is it ready
  7181. */
  7182. Node.prototype.isReady = function () {
  7183. return this._isReady;
  7184. };
  7185. /**
  7186. * Is this node enabled.
  7187. * If the node has a parent and is enabled, the parent will be inspected as well.
  7188. * @return {boolean} whether this node (and its parent) is enabled.
  7189. * @see setEnabled
  7190. */
  7191. Node.prototype.isEnabled = function () {
  7192. if (!this._isEnabled) {
  7193. return false;
  7194. }
  7195. if (this.parent) {
  7196. return this.parent.isEnabled();
  7197. }
  7198. return true;
  7199. };
  7200. /**
  7201. * Set the enabled state of this node.
  7202. * @param {boolean} value - the new enabled state
  7203. * @see isEnabled
  7204. */
  7205. Node.prototype.setEnabled = function (value) {
  7206. this._isEnabled = value;
  7207. };
  7208. /**
  7209. * Is this node a descendant of the given node.
  7210. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7211. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7212. * @see parent
  7213. */
  7214. Node.prototype.isDescendantOf = function (ancestor) {
  7215. if (this.parent) {
  7216. if (this.parent === ancestor) {
  7217. return true;
  7218. }
  7219. return this.parent.isDescendantOf(ancestor);
  7220. }
  7221. return false;
  7222. };
  7223. /**
  7224. * Evaluate a list of nodes and determine if they should be considered as descendants considering the given criterias
  7225. * @param {BABYLON.Node[]} list the input array of nodes to evaluate
  7226. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7227. * @param {boolean} directDecendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7228. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7229. */
  7230. Node.prototype._getDescendants = function (list, results, directDecendantsOnly, predicate) {
  7231. if (directDecendantsOnly === void 0) { directDecendantsOnly = false; }
  7232. for (var index = 0; index < list.length; index++) {
  7233. var item = list[index];
  7234. if (((directDecendantsOnly && item.parent === this) || (!directDecendantsOnly && item.isDescendantOf(this))) && (!predicate || predicate(item))) {
  7235. results.push(item);
  7236. }
  7237. }
  7238. };
  7239. /**
  7240. * Will return all nodes that have this node as parent.
  7241. * @param {boolean} directDecendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7242. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7243. * @return {BABYLON.Node[]} all children nodes of all types.
  7244. */
  7245. Node.prototype.getDescendants = function (directDecendantsOnly, predicate) {
  7246. var results = [];
  7247. this._getDescendants(this._scene.meshes, results, directDecendantsOnly, predicate);
  7248. this._getDescendants(this._scene.lights, results, directDecendantsOnly, predicate);
  7249. this._getDescendants(this._scene.cameras, results, directDecendantsOnly, predicate);
  7250. return results;
  7251. };
  7252. /**
  7253. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7254. * @Deprecated, legacy support.
  7255. * use getDecendants instead.
  7256. */
  7257. Node.prototype.getChildren = function (predicate) {
  7258. return this.getDescendants(true, predicate);
  7259. };
  7260. /**
  7261. * Get all child-meshes of this node.
  7262. */
  7263. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7264. var results = [];
  7265. this._getDescendants(this._scene.meshes, results, directDecendantsOnly, predicate);
  7266. return results;
  7267. };
  7268. Node.prototype._setReady = function (state) {
  7269. if (state === this._isReady) {
  7270. return;
  7271. }
  7272. if (!state) {
  7273. this._isReady = false;
  7274. return;
  7275. }
  7276. this._isReady = true;
  7277. if (this.onReady) {
  7278. this.onReady(this);
  7279. }
  7280. };
  7281. Node.prototype.getAnimationByName = function (name) {
  7282. for (var i = 0; i < this.animations.length; i++) {
  7283. var animation = this.animations[i];
  7284. if (animation.name === name) {
  7285. return animation;
  7286. }
  7287. }
  7288. return null;
  7289. };
  7290. Node.prototype.createAnimationRange = function (name, from, to) {
  7291. // check name not already in use
  7292. if (!this._ranges[name]) {
  7293. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7294. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7295. if (this.animations[i]) {
  7296. this.animations[i].createRange(name, from, to);
  7297. }
  7298. }
  7299. }
  7300. };
  7301. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7302. if (deleteFrames === void 0) { deleteFrames = true; }
  7303. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7304. if (this.animations[i]) {
  7305. this.animations[i].deleteRange(name, deleteFrames);
  7306. }
  7307. }
  7308. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7309. };
  7310. Node.prototype.getAnimationRange = function (name) {
  7311. return this._ranges[name];
  7312. };
  7313. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7314. var range = this.getAnimationRange(name);
  7315. if (!range) {
  7316. return null;
  7317. }
  7318. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7319. };
  7320. Node.prototype.serializeAnimationRanges = function () {
  7321. var serializationRanges = [];
  7322. for (var name in this._ranges) {
  7323. var range = {};
  7324. range.name = name;
  7325. range.from = this._ranges[name].from;
  7326. range.to = this._ranges[name].to;
  7327. serializationRanges.push(range);
  7328. }
  7329. return serializationRanges;
  7330. };
  7331. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7332. if (parsedNode.ranges) {
  7333. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7334. var data = parsedNode.ranges[index];
  7335. node.createAnimationRange(data.name, data.from, data.to);
  7336. }
  7337. }
  7338. };
  7339. __decorate([
  7340. BABYLON.serialize()
  7341. ], Node.prototype, "name", void 0);
  7342. __decorate([
  7343. BABYLON.serialize()
  7344. ], Node.prototype, "id", void 0);
  7345. __decorate([
  7346. BABYLON.serialize()
  7347. ], Node.prototype, "uniqueId", void 0);
  7348. __decorate([
  7349. BABYLON.serialize()
  7350. ], Node.prototype, "state", void 0);
  7351. return Node;
  7352. })();
  7353. BABYLON.Node = Node;
  7354. })(BABYLON || (BABYLON = {}));
  7355. var BABYLON;
  7356. (function (BABYLON) {
  7357. var FilesInput = (function () {
  7358. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7359. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7360. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7361. this._engine = p_engine;
  7362. this._canvas = p_canvas;
  7363. this._currentScene = p_scene;
  7364. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7365. this._progressCallback = p_progressCallback;
  7366. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7367. this._textureLoadingCallback = p_textureLoadingCallback;
  7368. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7369. }
  7370. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7371. var _this = this;
  7372. if (p_elementToMonitor) {
  7373. this._elementToMonitor = p_elementToMonitor;
  7374. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7375. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7376. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7377. }
  7378. };
  7379. FilesInput.prototype.renderFunction = function () {
  7380. if (this._additionnalRenderLoopLogicCallback) {
  7381. this._additionnalRenderLoopLogicCallback();
  7382. }
  7383. if (this._currentScene) {
  7384. if (this._textureLoadingCallback) {
  7385. var remaining = this._currentScene.getWaitingItemsCount();
  7386. if (remaining > 0) {
  7387. this._textureLoadingCallback(remaining);
  7388. }
  7389. }
  7390. this._currentScene.render();
  7391. }
  7392. };
  7393. FilesInput.prototype.drag = function (e) {
  7394. e.stopPropagation();
  7395. e.preventDefault();
  7396. };
  7397. FilesInput.prototype.drop = function (eventDrop) {
  7398. eventDrop.stopPropagation();
  7399. eventDrop.preventDefault();
  7400. this.loadFiles(eventDrop);
  7401. };
  7402. FilesInput.prototype.loadFiles = function (event) {
  7403. if (this._startingProcessingFilesCallback)
  7404. this._startingProcessingFilesCallback();
  7405. // Handling data transfer via drag'n'drop
  7406. if (event && event.dataTransfer && event.dataTransfer.files) {
  7407. this._filesToLoad = event.dataTransfer.files;
  7408. }
  7409. // Handling files from input files
  7410. if (event && event.target && event.target.files) {
  7411. this._filesToLoad = event.target.files;
  7412. }
  7413. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7414. for (var i = 0; i < this._filesToLoad.length; i++) {
  7415. switch (this._filesToLoad[i].type) {
  7416. case "image/jpeg":
  7417. case "image/png":
  7418. case "image/bmp":
  7419. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7420. break;
  7421. case "image/targa":
  7422. case "image/vnd.ms-dds":
  7423. case "audio/wav":
  7424. case "audio/x-wav":
  7425. case "audio/mp3":
  7426. case "audio/mpeg":
  7427. case "audio/mpeg3":
  7428. case "audio/x-mpeg-3":
  7429. case "audio/ogg":
  7430. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7431. break;
  7432. default:
  7433. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7434. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7435. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7436. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7437. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7438. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7439. this._sceneFileToLoad = this._filesToLoad[i];
  7440. }
  7441. break;
  7442. }
  7443. }
  7444. this.reload();
  7445. }
  7446. };
  7447. FilesInput.prototype.reload = function () {
  7448. var _this = this;
  7449. var that = this;
  7450. // If a ".babylon" file has been provided
  7451. if (this._sceneFileToLoad) {
  7452. if (this._currentScene) {
  7453. if (BABYLON.Tools.errorsCount > 0) {
  7454. BABYLON.Tools.ClearLogCache();
  7455. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7456. }
  7457. this._engine.stopRenderLoop();
  7458. this._currentScene.dispose();
  7459. }
  7460. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7461. that._currentScene = newScene;
  7462. // Wait for textures and shaders to be ready
  7463. that._currentScene.executeWhenReady(function () {
  7464. // Attach camera to canvas inputs
  7465. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7466. that._currentScene.createDefaultCameraOrLight();
  7467. }
  7468. that._currentScene.activeCamera.attachControl(that._canvas);
  7469. if (that._sceneLoadedCallback) {
  7470. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7471. }
  7472. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7473. });
  7474. }, function (progress) {
  7475. if (_this._progressCallback) {
  7476. _this._progressCallback(progress);
  7477. }
  7478. });
  7479. }
  7480. else {
  7481. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7482. }
  7483. };
  7484. FilesInput.FilesTextures = new Array();
  7485. FilesInput.FilesToLoad = new Array();
  7486. return FilesInput;
  7487. })();
  7488. BABYLON.FilesInput = FilesInput;
  7489. })(BABYLON || (BABYLON = {}));
  7490. var BABYLON;
  7491. (function (BABYLON) {
  7492. var IntersectionInfo = (function () {
  7493. function IntersectionInfo(bu, bv, distance) {
  7494. this.bu = bu;
  7495. this.bv = bv;
  7496. this.distance = distance;
  7497. this.faceId = 0;
  7498. this.subMeshId = 0;
  7499. }
  7500. return IntersectionInfo;
  7501. })();
  7502. BABYLON.IntersectionInfo = IntersectionInfo;
  7503. var PickingInfo = (function () {
  7504. function PickingInfo() {
  7505. this.hit = false;
  7506. this.distance = 0;
  7507. this.pickedPoint = null;
  7508. this.pickedMesh = null;
  7509. this.bu = 0;
  7510. this.bv = 0;
  7511. this.faceId = -1;
  7512. this.subMeshId = 0;
  7513. this.pickedSprite = null;
  7514. }
  7515. // Methods
  7516. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7517. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7518. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7519. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7520. return null;
  7521. }
  7522. var indices = this.pickedMesh.getIndices();
  7523. var result;
  7524. if (useVerticesNormals) {
  7525. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7526. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7527. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7528. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7529. normal0 = normal0.scale(this.bu);
  7530. normal1 = normal1.scale(this.bv);
  7531. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7532. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7533. }
  7534. else {
  7535. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7536. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7537. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7538. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7539. var p1p2 = vertex1.subtract(vertex2);
  7540. var p3p2 = vertex3.subtract(vertex2);
  7541. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7542. }
  7543. if (useWorldCoordinates) {
  7544. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7545. }
  7546. return BABYLON.Vector3.Normalize(result);
  7547. };
  7548. PickingInfo.prototype.getTextureCoordinates = function () {
  7549. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7550. return null;
  7551. }
  7552. var indices = this.pickedMesh.getIndices();
  7553. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7554. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7555. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7556. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7557. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7558. uv1 = uv1.scale(this.bu);
  7559. uv2 = uv2.scale(this.bv);
  7560. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7561. };
  7562. return PickingInfo;
  7563. })();
  7564. BABYLON.PickingInfo = PickingInfo;
  7565. })(BABYLON || (BABYLON = {}));
  7566. var BABYLON;
  7567. (function (BABYLON) {
  7568. var BoundingSphere = (function () {
  7569. function BoundingSphere(minimum, maximum) {
  7570. this.minimum = minimum;
  7571. this.maximum = maximum;
  7572. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7573. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7574. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7575. this.radius = distance * 0.5;
  7576. this.centerWorld = BABYLON.Vector3.Zero();
  7577. this._update(BABYLON.Matrix.Identity());
  7578. }
  7579. // Methods
  7580. BoundingSphere.prototype._update = function (world) {
  7581. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7582. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7583. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7584. };
  7585. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7586. for (var i = 0; i < 6; i++) {
  7587. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7588. return false;
  7589. }
  7590. return true;
  7591. };
  7592. BoundingSphere.prototype.intersectsPoint = function (point) {
  7593. var x = this.centerWorld.x - point.x;
  7594. var y = this.centerWorld.y - point.y;
  7595. var z = this.centerWorld.z - point.z;
  7596. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7597. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7598. return false;
  7599. return true;
  7600. };
  7601. // Statics
  7602. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7603. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7604. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7605. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7606. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7607. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7608. return false;
  7609. return true;
  7610. };
  7611. return BoundingSphere;
  7612. })();
  7613. BABYLON.BoundingSphere = BoundingSphere;
  7614. })(BABYLON || (BABYLON = {}));
  7615. var BABYLON;
  7616. (function (BABYLON) {
  7617. var BoundingBox = (function () {
  7618. function BoundingBox(minimum, maximum) {
  7619. this.minimum = minimum;
  7620. this.maximum = maximum;
  7621. this.vectors = new Array();
  7622. this.vectorsWorld = new Array();
  7623. // Bounding vectors
  7624. this.vectors.push(this.minimum.clone());
  7625. this.vectors.push(this.maximum.clone());
  7626. this.vectors.push(this.minimum.clone());
  7627. this.vectors[2].x = this.maximum.x;
  7628. this.vectors.push(this.minimum.clone());
  7629. this.vectors[3].y = this.maximum.y;
  7630. this.vectors.push(this.minimum.clone());
  7631. this.vectors[4].z = this.maximum.z;
  7632. this.vectors.push(this.maximum.clone());
  7633. this.vectors[5].z = this.minimum.z;
  7634. this.vectors.push(this.maximum.clone());
  7635. this.vectors[6].x = this.minimum.x;
  7636. this.vectors.push(this.maximum.clone());
  7637. this.vectors[7].y = this.minimum.y;
  7638. // OBB
  7639. this.center = this.maximum.add(this.minimum).scale(0.5);
  7640. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7641. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7642. // World
  7643. for (var index = 0; index < this.vectors.length; index++) {
  7644. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7645. }
  7646. this.minimumWorld = BABYLON.Vector3.Zero();
  7647. this.maximumWorld = BABYLON.Vector3.Zero();
  7648. this._update(BABYLON.Matrix.Identity());
  7649. }
  7650. // Methods
  7651. BoundingBox.prototype.getWorldMatrix = function () {
  7652. return this._worldMatrix;
  7653. };
  7654. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7655. this._worldMatrix.copyFrom(matrix);
  7656. return this;
  7657. };
  7658. BoundingBox.prototype._update = function (world) {
  7659. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7660. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7661. for (var index = 0; index < this.vectors.length; index++) {
  7662. var v = this.vectorsWorld[index];
  7663. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7664. if (v.x < this.minimumWorld.x)
  7665. this.minimumWorld.x = v.x;
  7666. if (v.y < this.minimumWorld.y)
  7667. this.minimumWorld.y = v.y;
  7668. if (v.z < this.minimumWorld.z)
  7669. this.minimumWorld.z = v.z;
  7670. if (v.x > this.maximumWorld.x)
  7671. this.maximumWorld.x = v.x;
  7672. if (v.y > this.maximumWorld.y)
  7673. this.maximumWorld.y = v.y;
  7674. if (v.z > this.maximumWorld.z)
  7675. this.maximumWorld.z = v.z;
  7676. }
  7677. // OBB
  7678. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7679. this.center.scaleInPlace(0.5);
  7680. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7681. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7682. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7683. this._worldMatrix = world;
  7684. };
  7685. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7686. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7687. };
  7688. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7689. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7690. };
  7691. BoundingBox.prototype.intersectsPoint = function (point) {
  7692. var delta = -BABYLON.Epsilon;
  7693. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7694. return false;
  7695. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7696. return false;
  7697. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7698. return false;
  7699. return true;
  7700. };
  7701. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7702. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7703. };
  7704. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7705. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7706. return false;
  7707. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7708. return false;
  7709. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7710. return false;
  7711. return true;
  7712. };
  7713. // Statics
  7714. BoundingBox.Intersects = function (box0, box1) {
  7715. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7716. return false;
  7717. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7718. return false;
  7719. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7720. return false;
  7721. return true;
  7722. };
  7723. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7724. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7725. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7726. return (num <= (sphereRadius * sphereRadius));
  7727. };
  7728. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7729. for (var p = 0; p < 6; p++) {
  7730. for (var i = 0; i < 8; i++) {
  7731. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7732. return false;
  7733. }
  7734. }
  7735. }
  7736. return true;
  7737. };
  7738. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7739. for (var p = 0; p < 6; p++) {
  7740. var inCount = 8;
  7741. for (var i = 0; i < 8; i++) {
  7742. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7743. --inCount;
  7744. }
  7745. else {
  7746. break;
  7747. }
  7748. }
  7749. if (inCount === 0)
  7750. return false;
  7751. }
  7752. return true;
  7753. };
  7754. return BoundingBox;
  7755. })();
  7756. BABYLON.BoundingBox = BoundingBox;
  7757. })(BABYLON || (BABYLON = {}));
  7758. var BABYLON;
  7759. (function (BABYLON) {
  7760. var computeBoxExtents = function (axis, box) {
  7761. var p = BABYLON.Vector3.Dot(box.center, axis);
  7762. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7763. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7764. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7765. var r = r0 + r1 + r2;
  7766. return {
  7767. min: p - r,
  7768. max: p + r
  7769. };
  7770. };
  7771. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7772. var axisOverlap = function (axis, box0, box1) {
  7773. var result0 = computeBoxExtents(axis, box0);
  7774. var result1 = computeBoxExtents(axis, box1);
  7775. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7776. };
  7777. var BoundingInfo = (function () {
  7778. function BoundingInfo(minimum, maximum) {
  7779. this.minimum = minimum;
  7780. this.maximum = maximum;
  7781. this._isLocked = false;
  7782. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7783. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7784. }
  7785. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7786. get: function () {
  7787. return this._isLocked;
  7788. },
  7789. set: function (value) {
  7790. this._isLocked = value;
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. // Methods
  7796. BoundingInfo.prototype.update = function (world) {
  7797. if (this._isLocked) {
  7798. return;
  7799. }
  7800. this.boundingBox._update(world);
  7801. this.boundingSphere._update(world);
  7802. };
  7803. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7804. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7805. return false;
  7806. return this.boundingBox.isInFrustum(frustumPlanes);
  7807. };
  7808. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7809. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7810. };
  7811. BoundingInfo.prototype._checkCollision = function (collider) {
  7812. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7813. };
  7814. BoundingInfo.prototype.intersectsPoint = function (point) {
  7815. if (!this.boundingSphere.centerWorld) {
  7816. return false;
  7817. }
  7818. if (!this.boundingSphere.intersectsPoint(point)) {
  7819. return false;
  7820. }
  7821. if (!this.boundingBox.intersectsPoint(point)) {
  7822. return false;
  7823. }
  7824. return true;
  7825. };
  7826. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7827. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7828. return false;
  7829. }
  7830. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7831. return false;
  7832. }
  7833. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7834. return false;
  7835. }
  7836. if (!precise) {
  7837. return true;
  7838. }
  7839. var box0 = this.boundingBox;
  7840. var box1 = boundingInfo.boundingBox;
  7841. if (!axisOverlap(box0.directions[0], box0, box1))
  7842. return false;
  7843. if (!axisOverlap(box0.directions[1], box0, box1))
  7844. return false;
  7845. if (!axisOverlap(box0.directions[2], box0, box1))
  7846. return false;
  7847. if (!axisOverlap(box1.directions[0], box0, box1))
  7848. return false;
  7849. if (!axisOverlap(box1.directions[1], box0, box1))
  7850. return false;
  7851. if (!axisOverlap(box1.directions[2], box0, box1))
  7852. return false;
  7853. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7854. return false;
  7855. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7856. return false;
  7857. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7858. return false;
  7859. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7860. return false;
  7861. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7862. return false;
  7863. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7864. return false;
  7865. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7866. return false;
  7867. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7868. return false;
  7869. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7870. return false;
  7871. return true;
  7872. };
  7873. return BoundingInfo;
  7874. })();
  7875. BABYLON.BoundingInfo = BoundingInfo;
  7876. })(BABYLON || (BABYLON = {}));
  7877. var BABYLON;
  7878. (function (BABYLON) {
  7879. var Ray = (function () {
  7880. function Ray(origin, direction, length) {
  7881. if (length === void 0) { length = Number.MAX_VALUE; }
  7882. this.origin = origin;
  7883. this.direction = direction;
  7884. this.length = length;
  7885. }
  7886. // Methods
  7887. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  7888. var d = 0.0;
  7889. var maxValue = Number.MAX_VALUE;
  7890. var inv;
  7891. var min;
  7892. var max;
  7893. var temp;
  7894. if (Math.abs(this.direction.x) < 0.0000001) {
  7895. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  7896. return false;
  7897. }
  7898. }
  7899. else {
  7900. inv = 1.0 / this.direction.x;
  7901. min = (minimum.x - this.origin.x) * inv;
  7902. max = (maximum.x - this.origin.x) * inv;
  7903. if (max === -Infinity) {
  7904. max = Infinity;
  7905. }
  7906. if (min > max) {
  7907. temp = min;
  7908. min = max;
  7909. max = temp;
  7910. }
  7911. d = Math.max(min, d);
  7912. maxValue = Math.min(max, maxValue);
  7913. if (d > maxValue) {
  7914. return false;
  7915. }
  7916. }
  7917. if (Math.abs(this.direction.y) < 0.0000001) {
  7918. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  7919. return false;
  7920. }
  7921. }
  7922. else {
  7923. inv = 1.0 / this.direction.y;
  7924. min = (minimum.y - this.origin.y) * inv;
  7925. max = (maximum.y - this.origin.y) * inv;
  7926. if (max === -Infinity) {
  7927. max = Infinity;
  7928. }
  7929. if (min > max) {
  7930. temp = min;
  7931. min = max;
  7932. max = temp;
  7933. }
  7934. d = Math.max(min, d);
  7935. maxValue = Math.min(max, maxValue);
  7936. if (d > maxValue) {
  7937. return false;
  7938. }
  7939. }
  7940. if (Math.abs(this.direction.z) < 0.0000001) {
  7941. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  7942. return false;
  7943. }
  7944. }
  7945. else {
  7946. inv = 1.0 / this.direction.z;
  7947. min = (minimum.z - this.origin.z) * inv;
  7948. max = (maximum.z - this.origin.z) * inv;
  7949. if (max === -Infinity) {
  7950. max = Infinity;
  7951. }
  7952. if (min > max) {
  7953. temp = min;
  7954. min = max;
  7955. max = temp;
  7956. }
  7957. d = Math.max(min, d);
  7958. maxValue = Math.min(max, maxValue);
  7959. if (d > maxValue) {
  7960. return false;
  7961. }
  7962. }
  7963. return true;
  7964. };
  7965. Ray.prototype.intersectsBox = function (box) {
  7966. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  7967. };
  7968. Ray.prototype.intersectsSphere = function (sphere) {
  7969. var x = sphere.center.x - this.origin.x;
  7970. var y = sphere.center.y - this.origin.y;
  7971. var z = sphere.center.z - this.origin.z;
  7972. var pyth = (x * x) + (y * y) + (z * z);
  7973. var rr = sphere.radius * sphere.radius;
  7974. if (pyth <= rr) {
  7975. return true;
  7976. }
  7977. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  7978. if (dot < 0.0) {
  7979. return false;
  7980. }
  7981. var temp = pyth - (dot * dot);
  7982. return temp <= rr;
  7983. };
  7984. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  7985. if (!this._edge1) {
  7986. this._edge1 = BABYLON.Vector3.Zero();
  7987. this._edge2 = BABYLON.Vector3.Zero();
  7988. this._pvec = BABYLON.Vector3.Zero();
  7989. this._tvec = BABYLON.Vector3.Zero();
  7990. this._qvec = BABYLON.Vector3.Zero();
  7991. }
  7992. vertex1.subtractToRef(vertex0, this._edge1);
  7993. vertex2.subtractToRef(vertex0, this._edge2);
  7994. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  7995. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  7996. if (det === 0) {
  7997. return null;
  7998. }
  7999. var invdet = 1 / det;
  8000. this.origin.subtractToRef(vertex0, this._tvec);
  8001. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8002. if (bu < 0 || bu > 1.0) {
  8003. return null;
  8004. }
  8005. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8006. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8007. if (bv < 0 || bu + bv > 1.0) {
  8008. return null;
  8009. }
  8010. //check if the distance is longer than the predefined length.
  8011. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8012. if (distance > this.length) {
  8013. return null;
  8014. }
  8015. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8016. };
  8017. // Statics
  8018. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8019. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8020. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8021. var direction = end.subtract(start);
  8022. direction.normalize();
  8023. return new Ray(start, direction);
  8024. };
  8025. /**
  8026. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  8027. * transformed to the given world matrix.
  8028. * @param origin The origin point
  8029. * @param end The end point
  8030. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8031. */
  8032. Ray.CreateNewFromTo = function (origin, end, world) {
  8033. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8034. var direction = end.subtract(origin);
  8035. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8036. direction.normalize();
  8037. return Ray.Transform(new Ray(origin, direction, length), world);
  8038. };
  8039. Ray.Transform = function (ray, matrix) {
  8040. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8041. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8042. return new Ray(newOrigin, newDirection, ray.length);
  8043. };
  8044. return Ray;
  8045. })();
  8046. BABYLON.Ray = Ray;
  8047. })(BABYLON || (BABYLON = {}));
  8048. var BABYLON;
  8049. (function (BABYLON) {
  8050. var AbstractMesh = (function (_super) {
  8051. __extends(AbstractMesh, _super);
  8052. // Constructor
  8053. function AbstractMesh(name, scene) {
  8054. var _this = this;
  8055. _super.call(this, name, scene);
  8056. // Properties
  8057. this.definedFacingForward = true; // orientation for POV movement & rotation
  8058. this.position = new BABYLON.Vector3(0, 0, 0);
  8059. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8060. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8061. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8062. this.visibility = 1.0;
  8063. this.alphaIndex = Number.MAX_VALUE;
  8064. this.infiniteDistance = false;
  8065. this.isVisible = true;
  8066. this.isPickable = true;
  8067. this.showBoundingBox = false;
  8068. this.showSubMeshesBoundingBox = false;
  8069. this.onDispose = null;
  8070. this.isBlocker = false;
  8071. this.renderingGroupId = 0;
  8072. this.receiveShadows = false;
  8073. this.renderOutline = false;
  8074. this.outlineColor = BABYLON.Color3.Red();
  8075. this.outlineWidth = 0.02;
  8076. this.renderOverlay = false;
  8077. this.overlayColor = BABYLON.Color3.Red();
  8078. this.overlayAlpha = 0.5;
  8079. this.hasVertexAlpha = false;
  8080. this.useVertexColors = true;
  8081. this.applyFog = true;
  8082. this.computeBonesUsingShaders = true;
  8083. this.scalingDeterminant = 1;
  8084. this.numBoneInfluencers = 4;
  8085. this.useOctreeForRenderingSelection = true;
  8086. this.useOctreeForPicking = true;
  8087. this.useOctreeForCollisions = true;
  8088. this.layerMask = 0x0FFFFFFF;
  8089. this.alwaysSelectAsActiveMesh = false;
  8090. // Collisions
  8091. this._checkCollisions = false;
  8092. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8093. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8094. this._collider = new BABYLON.Collider();
  8095. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8096. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8097. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8098. // Edges
  8099. this.edgesWidth = 1;
  8100. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8101. // Cache
  8102. this._localWorld = BABYLON.Matrix.Zero();
  8103. this._worldMatrix = BABYLON.Matrix.Zero();
  8104. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8105. this._absolutePosition = BABYLON.Vector3.Zero();
  8106. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8107. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8108. this._isDirty = false;
  8109. this._pivotMatrix = BABYLON.Matrix.Identity();
  8110. this._isDisposed = false;
  8111. this._renderId = 0;
  8112. this._intersectionsInProgress = new Array();
  8113. this._onAfterWorldMatrixUpdate = new Array();
  8114. this._isWorldMatrixFrozen = false;
  8115. this._unIndexed = false;
  8116. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8117. if (collidedMesh === void 0) { collidedMesh = null; }
  8118. //TODO move this to the collision coordinator!
  8119. if (_this.getScene().workerCollisions)
  8120. newPosition.multiplyInPlace(_this._collider.radius);
  8121. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8122. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8123. _this.position.addInPlace(_this._diffPositionForCollisions);
  8124. }
  8125. if (_this.onCollide && collidedMesh) {
  8126. _this.onCollide(collidedMesh);
  8127. }
  8128. if (_this.onCollisionPositionChange) {
  8129. _this.onCollisionPositionChange(_this.position);
  8130. }
  8131. };
  8132. scene.addMesh(this);
  8133. }
  8134. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8135. get: function () {
  8136. return AbstractMesh._BILLBOARDMODE_NONE;
  8137. },
  8138. enumerable: true,
  8139. configurable: true
  8140. });
  8141. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8142. get: function () {
  8143. return AbstractMesh._BILLBOARDMODE_X;
  8144. },
  8145. enumerable: true,
  8146. configurable: true
  8147. });
  8148. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8149. get: function () {
  8150. return AbstractMesh._BILLBOARDMODE_Y;
  8151. },
  8152. enumerable: true,
  8153. configurable: true
  8154. });
  8155. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8156. get: function () {
  8157. return AbstractMesh._BILLBOARDMODE_Z;
  8158. },
  8159. enumerable: true,
  8160. configurable: true
  8161. });
  8162. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8163. get: function () {
  8164. return AbstractMesh._BILLBOARDMODE_ALL;
  8165. },
  8166. enumerable: true,
  8167. configurable: true
  8168. });
  8169. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8170. get: function () {
  8171. return this._skeleton;
  8172. },
  8173. set: function (value) {
  8174. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8175. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8176. }
  8177. if (value && value.needInitialSkinMatrix) {
  8178. value._registerMeshWithPoseMatrix(this);
  8179. }
  8180. this._skeleton = value;
  8181. if (!this._skeleton) {
  8182. this._bonesTransformMatrices = null;
  8183. }
  8184. },
  8185. enumerable: true,
  8186. configurable: true
  8187. });
  8188. /**
  8189. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8190. */
  8191. AbstractMesh.prototype.toString = function (fullDetails) {
  8192. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8193. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8194. if (this._skeleton) {
  8195. ret += ", skeleton: " + this._skeleton.name;
  8196. }
  8197. if (fullDetails) {
  8198. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8199. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8200. }
  8201. return ret;
  8202. };
  8203. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8204. /**
  8205. * Getting the rotation object.
  8206. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8207. */
  8208. get: function () {
  8209. return this._rotation;
  8210. },
  8211. set: function (newRotation) {
  8212. this._rotation = newRotation;
  8213. },
  8214. enumerable: true,
  8215. configurable: true
  8216. });
  8217. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8218. get: function () {
  8219. return this._scaling;
  8220. },
  8221. set: function (newScaling) {
  8222. this._scaling = newScaling;
  8223. if (this.physicsImpostor) {
  8224. this.physicsImpostor.forceUpdate();
  8225. }
  8226. },
  8227. enumerable: true,
  8228. configurable: true
  8229. });
  8230. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8231. get: function () {
  8232. return this._rotationQuaternion;
  8233. },
  8234. set: function (quaternion) {
  8235. this._rotationQuaternion = quaternion;
  8236. //reset the rotation vector.
  8237. if (quaternion && this.rotation.length()) {
  8238. this.rotation.copyFromFloats(0, 0, 0);
  8239. }
  8240. },
  8241. enumerable: true,
  8242. configurable: true
  8243. });
  8244. // Methods
  8245. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8246. this._poseMatrix.copyFrom(matrix);
  8247. };
  8248. AbstractMesh.prototype.getPoseMatrix = function () {
  8249. return this._poseMatrix;
  8250. };
  8251. AbstractMesh.prototype.disableEdgesRendering = function () {
  8252. if (this._edgesRenderer !== undefined) {
  8253. this._edgesRenderer.dispose();
  8254. this._edgesRenderer = undefined;
  8255. }
  8256. };
  8257. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8258. if (epsilon === void 0) { epsilon = 0.95; }
  8259. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8260. this.disableEdgesRendering();
  8261. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8262. };
  8263. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8264. get: function () {
  8265. return false;
  8266. },
  8267. enumerable: true,
  8268. configurable: true
  8269. });
  8270. AbstractMesh.prototype.getLOD = function (camera) {
  8271. return this;
  8272. };
  8273. AbstractMesh.prototype.getTotalVertices = function () {
  8274. return 0;
  8275. };
  8276. AbstractMesh.prototype.getIndices = function () {
  8277. return null;
  8278. };
  8279. AbstractMesh.prototype.getVerticesData = function (kind) {
  8280. return null;
  8281. };
  8282. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8283. return false;
  8284. };
  8285. AbstractMesh.prototype.getBoundingInfo = function () {
  8286. if (this._masterMesh) {
  8287. return this._masterMesh.getBoundingInfo();
  8288. }
  8289. if (!this._boundingInfo) {
  8290. this._updateBoundingInfo();
  8291. }
  8292. return this._boundingInfo;
  8293. };
  8294. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8295. get: function () {
  8296. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8297. },
  8298. enumerable: true,
  8299. configurable: true
  8300. });
  8301. AbstractMesh.prototype._preActivate = function () {
  8302. };
  8303. AbstractMesh.prototype._activate = function (renderId) {
  8304. this._renderId = renderId;
  8305. };
  8306. AbstractMesh.prototype.getWorldMatrix = function () {
  8307. if (this._masterMesh) {
  8308. return this._masterMesh.getWorldMatrix();
  8309. }
  8310. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8311. this.computeWorldMatrix();
  8312. }
  8313. return this._worldMatrix;
  8314. };
  8315. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8316. get: function () {
  8317. return this._worldMatrix;
  8318. },
  8319. enumerable: true,
  8320. configurable: true
  8321. });
  8322. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8323. get: function () {
  8324. return this._absolutePosition;
  8325. },
  8326. enumerable: true,
  8327. configurable: true
  8328. });
  8329. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8330. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8331. this.computeWorldMatrix(true);
  8332. this._isWorldMatrixFrozen = true;
  8333. };
  8334. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8335. this._isWorldMatrixFrozen = false;
  8336. this.computeWorldMatrix(true);
  8337. };
  8338. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8339. get: function () {
  8340. return this._isWorldMatrixFrozen;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8346. axis.normalize();
  8347. if (!this.rotationQuaternion) {
  8348. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8349. this.rotation = BABYLON.Vector3.Zero();
  8350. }
  8351. var rotationQuaternion;
  8352. if (!space || space === BABYLON.Space.LOCAL) {
  8353. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8354. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8355. }
  8356. else {
  8357. if (this.parent) {
  8358. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8359. invertParentWorldMatrix.invert();
  8360. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8361. }
  8362. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8363. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8364. }
  8365. };
  8366. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8367. var displacementVector = axis.scale(distance);
  8368. if (!space || space === BABYLON.Space.LOCAL) {
  8369. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8370. this.setPositionWithLocalVector(tempV3);
  8371. }
  8372. else {
  8373. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8374. }
  8375. };
  8376. AbstractMesh.prototype.getAbsolutePosition = function () {
  8377. this.computeWorldMatrix();
  8378. return this._absolutePosition;
  8379. };
  8380. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8381. if (!absolutePosition) {
  8382. return;
  8383. }
  8384. var absolutePositionX;
  8385. var absolutePositionY;
  8386. var absolutePositionZ;
  8387. if (absolutePosition.x === undefined) {
  8388. if (arguments.length < 3) {
  8389. return;
  8390. }
  8391. absolutePositionX = arguments[0];
  8392. absolutePositionY = arguments[1];
  8393. absolutePositionZ = arguments[2];
  8394. }
  8395. else {
  8396. absolutePositionX = absolutePosition.x;
  8397. absolutePositionY = absolutePosition.y;
  8398. absolutePositionZ = absolutePosition.z;
  8399. }
  8400. if (this.parent) {
  8401. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8402. invertParentWorldMatrix.invert();
  8403. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8404. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8405. }
  8406. else {
  8407. this.position.x = absolutePositionX;
  8408. this.position.y = absolutePositionY;
  8409. this.position.z = absolutePositionZ;
  8410. }
  8411. };
  8412. // ================================== Point of View Movement =================================
  8413. /**
  8414. * Perform relative position change from the point of view of behind the front of the mesh.
  8415. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8416. * Supports definition of mesh facing forward or backward.
  8417. * @param {number} amountRight
  8418. * @param {number} amountUp
  8419. * @param {number} amountForward
  8420. */
  8421. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8422. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8423. };
  8424. /**
  8425. * Calculate relative position change from the point of view of behind the front of the mesh.
  8426. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8427. * Supports definition of mesh facing forward or backward.
  8428. * @param {number} amountRight
  8429. * @param {number} amountUp
  8430. * @param {number} amountForward
  8431. */
  8432. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8433. var rotMatrix = new BABYLON.Matrix();
  8434. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8435. rotQuaternion.toRotationMatrix(rotMatrix);
  8436. var translationDelta = BABYLON.Vector3.Zero();
  8437. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8438. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8439. return translationDelta;
  8440. };
  8441. // ================================== Point of View Rotation =================================
  8442. /**
  8443. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8444. * Supports definition of mesh facing forward or backward.
  8445. * @param {number} flipBack
  8446. * @param {number} twirlClockwise
  8447. * @param {number} tiltRight
  8448. */
  8449. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8450. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8451. };
  8452. /**
  8453. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8454. * Supports definition of mesh facing forward or backward.
  8455. * @param {number} flipBack
  8456. * @param {number} twirlClockwise
  8457. * @param {number} tiltRight
  8458. */
  8459. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8460. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8461. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8462. };
  8463. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8464. this._pivotMatrix = matrix;
  8465. this._cache.pivotMatrixUpdated = true;
  8466. };
  8467. AbstractMesh.prototype.getPivotMatrix = function () {
  8468. return this._pivotMatrix;
  8469. };
  8470. AbstractMesh.prototype._isSynchronized = function () {
  8471. if (this._isDirty) {
  8472. return false;
  8473. }
  8474. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8475. return false;
  8476. if (this._cache.pivotMatrixUpdated) {
  8477. return false;
  8478. }
  8479. if (this.infiniteDistance) {
  8480. return false;
  8481. }
  8482. if (!this._cache.position.equals(this.position))
  8483. return false;
  8484. if (this.rotationQuaternion) {
  8485. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8486. return false;
  8487. }
  8488. else {
  8489. if (!this._cache.rotation.equals(this.rotation))
  8490. return false;
  8491. }
  8492. if (!this._cache.scaling.equals(this.scaling))
  8493. return false;
  8494. return true;
  8495. };
  8496. AbstractMesh.prototype._initCache = function () {
  8497. _super.prototype._initCache.call(this);
  8498. this._cache.localMatrixUpdated = false;
  8499. this._cache.position = BABYLON.Vector3.Zero();
  8500. this._cache.scaling = BABYLON.Vector3.Zero();
  8501. this._cache.rotation = BABYLON.Vector3.Zero();
  8502. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8503. this._cache.billboardMode = -1;
  8504. };
  8505. AbstractMesh.prototype.markAsDirty = function (property) {
  8506. if (property === "rotation") {
  8507. this.rotationQuaternion = null;
  8508. }
  8509. this._currentRenderId = Number.MAX_VALUE;
  8510. this._isDirty = true;
  8511. };
  8512. AbstractMesh.prototype._updateBoundingInfo = function () {
  8513. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8514. this._boundingInfo.update(this.worldMatrixFromCache);
  8515. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8516. };
  8517. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8518. if (!this.subMeshes) {
  8519. return;
  8520. }
  8521. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8522. var subMesh = this.subMeshes[subIndex];
  8523. if (!subMesh.IsGlobal) {
  8524. subMesh.updateBoundingInfo(matrix);
  8525. }
  8526. }
  8527. };
  8528. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8529. if (this._isWorldMatrixFrozen) {
  8530. return this._worldMatrix;
  8531. }
  8532. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8533. this._currentRenderId = this.getScene().getRenderId();
  8534. return this._worldMatrix;
  8535. }
  8536. this._cache.position.copyFrom(this.position);
  8537. this._cache.scaling.copyFrom(this.scaling);
  8538. this._cache.pivotMatrixUpdated = false;
  8539. this._cache.billboardMode = this.billboardMode;
  8540. this._currentRenderId = this.getScene().getRenderId();
  8541. this._isDirty = false;
  8542. // Scaling
  8543. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8544. // Rotation
  8545. //rotate, if quaternion is set and rotation was used
  8546. if (this.rotationQuaternion) {
  8547. var len = this.rotation.length();
  8548. if (len) {
  8549. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8550. this.rotation.copyFromFloats(0, 0, 0);
  8551. }
  8552. }
  8553. if (this.rotationQuaternion) {
  8554. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8555. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8556. }
  8557. else {
  8558. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8559. this._cache.rotation.copyFrom(this.rotation);
  8560. }
  8561. // Translation
  8562. if (this.infiniteDistance && !this.parent) {
  8563. var camera = this.getScene().activeCamera;
  8564. if (camera) {
  8565. var cameraWorldMatrix = camera.getWorldMatrix();
  8566. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8567. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8568. }
  8569. }
  8570. else {
  8571. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8572. }
  8573. // Composing transformations
  8574. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8575. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8576. // Billboarding
  8577. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8578. var localPosition = this.position.clone();
  8579. var zero = this.getScene().activeCamera.globalPosition.clone();
  8580. if (this.parent && this.parent.position) {
  8581. localPosition.addInPlace(this.parent.position);
  8582. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8583. }
  8584. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8585. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8586. zero.x = localPosition.x + BABYLON.Epsilon;
  8587. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8588. zero.y = localPosition.y + BABYLON.Epsilon;
  8589. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8590. zero.z = localPosition.z + BABYLON.Epsilon;
  8591. }
  8592. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8593. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8594. BABYLON.Tmp.Matrix[3].invert();
  8595. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8596. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8597. }
  8598. // Local world
  8599. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8600. // Parent
  8601. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8602. this._markSyncedWithParent();
  8603. if (this._meshToBoneReferal) {
  8604. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8605. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8606. }
  8607. else {
  8608. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8609. }
  8610. }
  8611. else {
  8612. this._worldMatrix.copyFrom(this._localWorld);
  8613. }
  8614. // Bounding info
  8615. this._updateBoundingInfo();
  8616. // Absolute position
  8617. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8618. // Callbacks
  8619. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8620. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8621. }
  8622. if (!this._poseMatrix) {
  8623. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8624. }
  8625. return this._worldMatrix;
  8626. };
  8627. /**
  8628. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8629. * @param func: callback function to add
  8630. */
  8631. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8632. this._onAfterWorldMatrixUpdate.push(func);
  8633. };
  8634. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8635. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8636. if (index > -1) {
  8637. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8638. }
  8639. };
  8640. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8641. this.computeWorldMatrix();
  8642. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8643. };
  8644. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8645. this.computeWorldMatrix();
  8646. var invLocalWorldMatrix = this._localWorld.clone();
  8647. invLocalWorldMatrix.invert();
  8648. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8649. };
  8650. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8651. this.computeWorldMatrix(true);
  8652. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8653. };
  8654. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8655. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8656. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8657. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8658. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8659. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8660. /// <returns>Mesh oriented towards targetMesh</returns>
  8661. yawCor = yawCor || 0; // default to zero if undefined
  8662. pitchCor = pitchCor || 0;
  8663. rollCor = rollCor || 0;
  8664. var dv = targetPoint.subtract(this.position);
  8665. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8666. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8667. var pitch = Math.atan2(dv.y, len);
  8668. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8669. };
  8670. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8671. this._meshToBoneReferal = affectedMesh;
  8672. this.parent = bone;
  8673. if (bone.getWorldMatrix().determinant() < 0) {
  8674. this.scalingDeterminant *= -1;
  8675. }
  8676. };
  8677. AbstractMesh.prototype.detachFromBone = function () {
  8678. if (this.parent.getWorldMatrix().determinant() < 0) {
  8679. this.scalingDeterminant *= -1;
  8680. }
  8681. this._meshToBoneReferal = null;
  8682. this.parent = null;
  8683. };
  8684. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8685. return this._boundingInfo.isInFrustum(frustumPlanes);
  8686. };
  8687. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8688. if (!camera) {
  8689. camera = this.getScene().activeCamera;
  8690. }
  8691. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8692. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8693. return false;
  8694. }
  8695. return true;
  8696. };
  8697. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8698. if (!this._boundingInfo || !mesh._boundingInfo) {
  8699. return false;
  8700. }
  8701. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8702. };
  8703. AbstractMesh.prototype.intersectsPoint = function (point) {
  8704. if (!this._boundingInfo) {
  8705. return false;
  8706. }
  8707. return this._boundingInfo.intersectsPoint(point);
  8708. };
  8709. // Physics
  8710. /**
  8711. * @Deprecated. Use new PhysicsImpostor instead.
  8712. * */
  8713. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8714. //legacy support
  8715. if (impostor.impostor) {
  8716. options = impostor;
  8717. impostor = impostor.impostor;
  8718. }
  8719. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options);
  8720. return this.physicsImpostor.physicsBody;
  8721. };
  8722. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8723. return this.physicsImpostor;
  8724. };
  8725. /**
  8726. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  8727. */
  8728. AbstractMesh.prototype.getPhysicsMass = function () {
  8729. return this.physicsImpostor.getParam("mass");
  8730. };
  8731. /**
  8732. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  8733. */
  8734. AbstractMesh.prototype.getPhysicsFriction = function () {
  8735. return this.physicsImpostor.getParam("friction");
  8736. };
  8737. /**
  8738. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  8739. */
  8740. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8741. return this.physicsImpostor.getParam("resitution");
  8742. };
  8743. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8744. if (!camera) {
  8745. camera = this.getScene().activeCamera;
  8746. }
  8747. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8748. };
  8749. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8750. if (!camera) {
  8751. camera = this.getScene().activeCamera;
  8752. }
  8753. return this.absolutePosition.subtract(camera.position).length();
  8754. };
  8755. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8756. if (!this.physicsImpostor) {
  8757. return;
  8758. }
  8759. this.physicsImpostor.applyImpulse(force, contactPoint);
  8760. };
  8761. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8762. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  8763. return;
  8764. }
  8765. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  8766. mainPivot: pivot1,
  8767. connectedPivot: pivot2,
  8768. nativeParams: options
  8769. });
  8770. };
  8771. /**
  8772. * @Deprecated
  8773. */
  8774. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8775. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8776. this.updatePhysicsBody();
  8777. };
  8778. /**
  8779. * @Deprecated
  8780. * Calling this function is not needed anymore.
  8781. * The physics engine takes care of transofmration automatically.
  8782. */
  8783. AbstractMesh.prototype.updatePhysicsBody = function () {
  8784. //Unneeded
  8785. };
  8786. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8787. // Collisions
  8788. get: function () {
  8789. return this._checkCollisions;
  8790. },
  8791. set: function (collisionEnabled) {
  8792. this._checkCollisions = collisionEnabled;
  8793. if (this.getScene().workerCollisions) {
  8794. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8795. }
  8796. },
  8797. enumerable: true,
  8798. configurable: true
  8799. });
  8800. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8801. var globalPosition = this.getAbsolutePosition();
  8802. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8803. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8804. this._collider.radius = this.ellipsoid;
  8805. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8806. };
  8807. // Submeshes octree
  8808. /**
  8809. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8810. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8811. */
  8812. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8813. if (maxCapacity === void 0) { maxCapacity = 64; }
  8814. if (maxDepth === void 0) { maxDepth = 2; }
  8815. if (!this._submeshesOctree) {
  8816. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8817. }
  8818. this.computeWorldMatrix(true);
  8819. // Update octree
  8820. var bbox = this.getBoundingInfo().boundingBox;
  8821. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8822. return this._submeshesOctree;
  8823. };
  8824. // Collisions
  8825. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8826. this._generatePointsArray();
  8827. // Transformation
  8828. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8829. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8830. subMesh._lastColliderWorldVertices = [];
  8831. subMesh._trianglePlanes = [];
  8832. var start = subMesh.verticesStart;
  8833. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8834. for (var i = start; i < end; i++) {
  8835. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8836. }
  8837. }
  8838. // Collide
  8839. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8840. if (collider.collisionFound) {
  8841. collider.collidedMesh = this;
  8842. }
  8843. };
  8844. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8845. var subMeshes;
  8846. var len;
  8847. // Octrees
  8848. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8849. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8850. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8851. len = intersections.length;
  8852. subMeshes = intersections.data;
  8853. }
  8854. else {
  8855. subMeshes = this.subMeshes;
  8856. len = subMeshes.length;
  8857. }
  8858. for (var index = 0; index < len; index++) {
  8859. var subMesh = subMeshes[index];
  8860. // Bounding test
  8861. if (len > 1 && !subMesh._checkCollision(collider))
  8862. continue;
  8863. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8864. }
  8865. };
  8866. AbstractMesh.prototype._checkCollision = function (collider) {
  8867. // Bounding box test
  8868. if (!this._boundingInfo._checkCollision(collider))
  8869. return;
  8870. // Transformation matrix
  8871. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8872. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8873. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8874. };
  8875. // Picking
  8876. AbstractMesh.prototype._generatePointsArray = function () {
  8877. return false;
  8878. };
  8879. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8880. var pickingInfo = new BABYLON.PickingInfo();
  8881. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8882. return pickingInfo;
  8883. }
  8884. if (!this._generatePointsArray()) {
  8885. return pickingInfo;
  8886. }
  8887. var intersectInfo = null;
  8888. // Octrees
  8889. var subMeshes;
  8890. var len;
  8891. if (this._submeshesOctree && this.useOctreeForPicking) {
  8892. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8893. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8894. len = intersections.length;
  8895. subMeshes = intersections.data;
  8896. }
  8897. else {
  8898. subMeshes = this.subMeshes;
  8899. len = subMeshes.length;
  8900. }
  8901. for (var index = 0; index < len; index++) {
  8902. var subMesh = subMeshes[index];
  8903. // Bounding test
  8904. if (len > 1 && !subMesh.canIntersects(ray))
  8905. continue;
  8906. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8907. if (currentIntersectInfo) {
  8908. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8909. intersectInfo = currentIntersectInfo;
  8910. intersectInfo.subMeshId = index;
  8911. if (fastCheck) {
  8912. break;
  8913. }
  8914. }
  8915. }
  8916. }
  8917. if (intersectInfo) {
  8918. // Get picked point
  8919. var world = this.getWorldMatrix();
  8920. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8921. var direction = ray.direction.clone();
  8922. direction = direction.scale(intersectInfo.distance);
  8923. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8924. var pickedPoint = worldOrigin.add(worldDirection);
  8925. // Return result
  8926. pickingInfo.hit = true;
  8927. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8928. pickingInfo.pickedPoint = pickedPoint;
  8929. pickingInfo.pickedMesh = this;
  8930. pickingInfo.bu = intersectInfo.bu;
  8931. pickingInfo.bv = intersectInfo.bv;
  8932. pickingInfo.faceId = intersectInfo.faceId;
  8933. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8934. return pickingInfo;
  8935. }
  8936. return pickingInfo;
  8937. };
  8938. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8939. return null;
  8940. };
  8941. AbstractMesh.prototype.releaseSubMeshes = function () {
  8942. if (this.subMeshes) {
  8943. while (this.subMeshes.length) {
  8944. this.subMeshes[0].dispose();
  8945. }
  8946. }
  8947. else {
  8948. this.subMeshes = new Array();
  8949. }
  8950. };
  8951. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8952. var index;
  8953. // Action manager
  8954. if (this.actionManager) {
  8955. this.actionManager.dispose();
  8956. this.actionManager = null;
  8957. }
  8958. // Skeleton
  8959. this.skeleton = null;
  8960. // Animations
  8961. this.getScene().stopAnimation(this);
  8962. // Physics
  8963. if (this.physicsImpostor) {
  8964. this.physicsImpostor.dispose(!doNotRecurse);
  8965. }
  8966. // Intersections in progress
  8967. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8968. var other = this._intersectionsInProgress[index];
  8969. var pos = other._intersectionsInProgress.indexOf(this);
  8970. other._intersectionsInProgress.splice(pos, 1);
  8971. }
  8972. this._intersectionsInProgress = [];
  8973. // Edges
  8974. if (this._edgesRenderer) {
  8975. this._edgesRenderer.dispose();
  8976. this._edgesRenderer = null;
  8977. }
  8978. // SubMeshes
  8979. this.releaseSubMeshes();
  8980. // Remove from scene
  8981. this.getScene().removeMesh(this);
  8982. if (!doNotRecurse) {
  8983. // Particles
  8984. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8985. if (this.getScene().particleSystems[index].emitter === this) {
  8986. this.getScene().particleSystems[index].dispose();
  8987. index--;
  8988. }
  8989. }
  8990. // Children
  8991. var objects = this.getScene().meshes.slice(0);
  8992. for (index = 0; index < objects.length; index++) {
  8993. if (objects[index].parent === this) {
  8994. objects[index].dispose();
  8995. }
  8996. }
  8997. }
  8998. else {
  8999. for (index = 0; index < this.getScene().meshes.length; index++) {
  9000. var obj = this.getScene().meshes[index];
  9001. if (obj.parent === this) {
  9002. obj.parent = null;
  9003. obj.computeWorldMatrix(true);
  9004. }
  9005. }
  9006. }
  9007. this._onAfterWorldMatrixUpdate = [];
  9008. this._isDisposed = true;
  9009. // Callback
  9010. if (this.onDispose) {
  9011. this.onDispose();
  9012. }
  9013. };
  9014. // Statics
  9015. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9016. AbstractMesh._BILLBOARDMODE_X = 1;
  9017. AbstractMesh._BILLBOARDMODE_Y = 2;
  9018. AbstractMesh._BILLBOARDMODE_Z = 4;
  9019. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9020. return AbstractMesh;
  9021. })(BABYLON.Node);
  9022. BABYLON.AbstractMesh = AbstractMesh;
  9023. })(BABYLON || (BABYLON = {}));
  9024. var BABYLON;
  9025. (function (BABYLON) {
  9026. var Light = (function (_super) {
  9027. __extends(Light, _super);
  9028. function Light(name, scene) {
  9029. _super.call(this, name, scene);
  9030. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9031. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9032. this.intensity = 1.0;
  9033. this.range = Number.MAX_VALUE;
  9034. this.includeOnlyWithLayerMask = 0;
  9035. this.includedOnlyMeshes = new Array();
  9036. this.excludedMeshes = new Array();
  9037. this.excludeWithLayerMask = 0;
  9038. // PBR Properties.
  9039. this.radius = 0.00001;
  9040. this._excludedMeshesIds = new Array();
  9041. this._includedOnlyMeshesIds = new Array();
  9042. scene.addLight(this);
  9043. }
  9044. /**
  9045. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9046. */
  9047. Light.prototype.toString = function (fullDetails) {
  9048. var ret = "Name: " + this.name;
  9049. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9050. if (this.animations) {
  9051. for (var i = 0; i < this.animations.length; i++) {
  9052. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9053. }
  9054. }
  9055. if (fullDetails) {
  9056. }
  9057. return ret;
  9058. };
  9059. Light.prototype.getShadowGenerator = function () {
  9060. return this._shadowGenerator;
  9061. };
  9062. Light.prototype.getAbsolutePosition = function () {
  9063. return BABYLON.Vector3.Zero();
  9064. };
  9065. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9066. };
  9067. Light.prototype._getWorldMatrix = function () {
  9068. return BABYLON.Matrix.Identity();
  9069. };
  9070. Light.prototype.canAffectMesh = function (mesh) {
  9071. if (!mesh) {
  9072. return true;
  9073. }
  9074. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9075. return false;
  9076. }
  9077. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9078. return false;
  9079. }
  9080. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9081. return false;
  9082. }
  9083. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9084. return false;
  9085. }
  9086. return true;
  9087. };
  9088. Light.prototype.getWorldMatrix = function () {
  9089. this._currentRenderId = this.getScene().getRenderId();
  9090. var worldMatrix = this._getWorldMatrix();
  9091. if (this.parent && this.parent.getWorldMatrix) {
  9092. if (!this._parentedWorldMatrix) {
  9093. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9094. }
  9095. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9096. this._markSyncedWithParent();
  9097. return this._parentedWorldMatrix;
  9098. }
  9099. return worldMatrix;
  9100. };
  9101. Light.prototype.dispose = function () {
  9102. if (this._shadowGenerator) {
  9103. this._shadowGenerator.dispose();
  9104. this._shadowGenerator = null;
  9105. }
  9106. // Animations
  9107. this.getScene().stopAnimation(this);
  9108. // Remove from scene
  9109. this.getScene().removeLight(this);
  9110. };
  9111. Light.prototype.getTypeID = function () {
  9112. return 0;
  9113. };
  9114. Light.prototype.clone = function (name) {
  9115. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9116. };
  9117. Light.prototype.serialize = function () {
  9118. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9119. // Type
  9120. serializationObject.type = this.getTypeID();
  9121. // Parent
  9122. if (this.parent) {
  9123. serializationObject.parentId = this.parent.id;
  9124. }
  9125. // Animations
  9126. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9127. serializationObject.ranges = this.serializeAnimationRanges();
  9128. return serializationObject;
  9129. };
  9130. Light.GetConstructorFromName = function (type, name, scene) {
  9131. switch (type) {
  9132. case 0:
  9133. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9134. case 1:
  9135. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9136. case 2:
  9137. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9138. case 3:
  9139. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9140. }
  9141. };
  9142. Light.Parse = function (parsedLight, scene) {
  9143. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9144. // Inclusion / exclusions
  9145. if (parsedLight.excludedMeshesIds) {
  9146. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9147. }
  9148. if (parsedLight.includedOnlyMeshesIds) {
  9149. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9150. }
  9151. // Parent
  9152. if (parsedLight.parentId) {
  9153. light._waitingParentId = parsedLight.parentId;
  9154. }
  9155. // Animations
  9156. if (parsedLight.animations) {
  9157. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9158. var parsedAnimation = parsedLight.animations[animationIndex];
  9159. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9160. }
  9161. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9162. }
  9163. if (parsedLight.autoAnimate) {
  9164. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9165. }
  9166. return light;
  9167. };
  9168. __decorate([
  9169. BABYLON.serializeAsColor3()
  9170. ], Light.prototype, "diffuse", void 0);
  9171. __decorate([
  9172. BABYLON.serializeAsColor3()
  9173. ], Light.prototype, "specular", void 0);
  9174. __decorate([
  9175. BABYLON.serialize()
  9176. ], Light.prototype, "intensity", void 0);
  9177. __decorate([
  9178. BABYLON.serialize()
  9179. ], Light.prototype, "range", void 0);
  9180. __decorate([
  9181. BABYLON.serialize()
  9182. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9183. __decorate([
  9184. BABYLON.serialize()
  9185. ], Light.prototype, "radius", void 0);
  9186. return Light;
  9187. })(BABYLON.Node);
  9188. BABYLON.Light = Light;
  9189. })(BABYLON || (BABYLON = {}));
  9190. var BABYLON;
  9191. (function (BABYLON) {
  9192. var PointLight = (function (_super) {
  9193. __extends(PointLight, _super);
  9194. function PointLight(name, position, scene) {
  9195. _super.call(this, name, scene);
  9196. this.position = position;
  9197. }
  9198. PointLight.prototype.getAbsolutePosition = function () {
  9199. return this.transformedPosition ? this.transformedPosition : this.position;
  9200. };
  9201. PointLight.prototype.computeTransformedPosition = function () {
  9202. if (this.parent && this.parent.getWorldMatrix) {
  9203. if (!this.transformedPosition) {
  9204. this.transformedPosition = BABYLON.Vector3.Zero();
  9205. }
  9206. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9207. return true;
  9208. }
  9209. return false;
  9210. };
  9211. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9212. if (this.parent && this.parent.getWorldMatrix) {
  9213. this.computeTransformedPosition();
  9214. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9215. return;
  9216. }
  9217. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9218. };
  9219. PointLight.prototype.needCube = function () {
  9220. return true;
  9221. };
  9222. PointLight.prototype.supportsVSM = function () {
  9223. return false;
  9224. };
  9225. PointLight.prototype.needRefreshPerFrame = function () {
  9226. return false;
  9227. };
  9228. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9229. switch (faceIndex) {
  9230. case 0:
  9231. return new BABYLON.Vector3(1, 0, 0);
  9232. case 1:
  9233. return new BABYLON.Vector3(-1, 0, 0);
  9234. case 2:
  9235. return new BABYLON.Vector3(0, -1, 0);
  9236. case 3:
  9237. return new BABYLON.Vector3(0, 1, 0);
  9238. case 4:
  9239. return new BABYLON.Vector3(0, 0, 1);
  9240. case 5:
  9241. return new BABYLON.Vector3(0, 0, -1);
  9242. }
  9243. return BABYLON.Vector3.Zero();
  9244. };
  9245. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9246. var activeCamera = this.getScene().activeCamera;
  9247. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9248. };
  9249. PointLight.prototype._getWorldMatrix = function () {
  9250. if (!this._worldMatrix) {
  9251. this._worldMatrix = BABYLON.Matrix.Identity();
  9252. }
  9253. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9254. return this._worldMatrix;
  9255. };
  9256. PointLight.prototype.getTypeID = function () {
  9257. return 0;
  9258. };
  9259. __decorate([
  9260. BABYLON.serializeAsVector3()
  9261. ], PointLight.prototype, "position", void 0);
  9262. return PointLight;
  9263. })(BABYLON.Light);
  9264. BABYLON.PointLight = PointLight;
  9265. })(BABYLON || (BABYLON = {}));
  9266. var BABYLON;
  9267. (function (BABYLON) {
  9268. var SpotLight = (function (_super) {
  9269. __extends(SpotLight, _super);
  9270. function SpotLight(name, position, direction, angle, exponent, scene) {
  9271. _super.call(this, name, scene);
  9272. this.position = position;
  9273. this.direction = direction;
  9274. this.angle = angle;
  9275. this.exponent = exponent;
  9276. }
  9277. SpotLight.prototype.getAbsolutePosition = function () {
  9278. return this.transformedPosition ? this.transformedPosition : this.position;
  9279. };
  9280. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9281. var activeCamera = this.getScene().activeCamera;
  9282. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9283. };
  9284. SpotLight.prototype.needCube = function () {
  9285. return false;
  9286. };
  9287. SpotLight.prototype.supportsVSM = function () {
  9288. return true;
  9289. };
  9290. SpotLight.prototype.needRefreshPerFrame = function () {
  9291. return false;
  9292. };
  9293. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9294. return this.direction;
  9295. };
  9296. SpotLight.prototype.setDirectionToTarget = function (target) {
  9297. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9298. return this.direction;
  9299. };
  9300. SpotLight.prototype.computeTransformedPosition = function () {
  9301. if (this.parent && this.parent.getWorldMatrix) {
  9302. if (!this.transformedPosition) {
  9303. this.transformedPosition = BABYLON.Vector3.Zero();
  9304. }
  9305. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9306. return true;
  9307. }
  9308. return false;
  9309. };
  9310. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9311. var normalizeDirection;
  9312. if (this.parent && this.parent.getWorldMatrix) {
  9313. if (!this._transformedDirection) {
  9314. this._transformedDirection = BABYLON.Vector3.Zero();
  9315. }
  9316. this.computeTransformedPosition();
  9317. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9318. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9319. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9320. }
  9321. else {
  9322. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9323. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9324. }
  9325. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9326. };
  9327. SpotLight.prototype._getWorldMatrix = function () {
  9328. if (!this._worldMatrix) {
  9329. this._worldMatrix = BABYLON.Matrix.Identity();
  9330. }
  9331. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9332. return this._worldMatrix;
  9333. };
  9334. SpotLight.prototype.getTypeID = function () {
  9335. return 2;
  9336. };
  9337. __decorate([
  9338. BABYLON.serializeAsVector3()
  9339. ], SpotLight.prototype, "position", void 0);
  9340. __decorate([
  9341. BABYLON.serializeAsVector3()
  9342. ], SpotLight.prototype, "direction", void 0);
  9343. __decorate([
  9344. BABYLON.serialize()
  9345. ], SpotLight.prototype, "angle", void 0);
  9346. __decorate([
  9347. BABYLON.serialize()
  9348. ], SpotLight.prototype, "exponent", void 0);
  9349. return SpotLight;
  9350. })(BABYLON.Light);
  9351. BABYLON.SpotLight = SpotLight;
  9352. })(BABYLON || (BABYLON = {}));
  9353. var BABYLON;
  9354. (function (BABYLON) {
  9355. var HemisphericLight = (function (_super) {
  9356. __extends(HemisphericLight, _super);
  9357. function HemisphericLight(name, direction, scene) {
  9358. _super.call(this, name, scene);
  9359. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9360. this.direction = direction;
  9361. }
  9362. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9363. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9364. return this.direction;
  9365. };
  9366. HemisphericLight.prototype.getShadowGenerator = function () {
  9367. return null;
  9368. };
  9369. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9370. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9371. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9372. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9373. };
  9374. HemisphericLight.prototype._getWorldMatrix = function () {
  9375. if (!this._worldMatrix) {
  9376. this._worldMatrix = BABYLON.Matrix.Identity();
  9377. }
  9378. return this._worldMatrix;
  9379. };
  9380. HemisphericLight.prototype.getTypeID = function () {
  9381. return 3;
  9382. };
  9383. __decorate([
  9384. BABYLON.serializeAsColor3()
  9385. ], HemisphericLight.prototype, "groundColor", void 0);
  9386. __decorate([
  9387. BABYLON.serializeAsVector3()
  9388. ], HemisphericLight.prototype, "direction", void 0);
  9389. return HemisphericLight;
  9390. })(BABYLON.Light);
  9391. BABYLON.HemisphericLight = HemisphericLight;
  9392. })(BABYLON || (BABYLON = {}));
  9393. var BABYLON;
  9394. (function (BABYLON) {
  9395. var DirectionalLight = (function (_super) {
  9396. __extends(DirectionalLight, _super);
  9397. function DirectionalLight(name, direction, scene) {
  9398. _super.call(this, name, scene);
  9399. this.shadowOrthoScale = 0.5;
  9400. this.autoUpdateExtends = true;
  9401. // Cache
  9402. this._orthoLeft = Number.MAX_VALUE;
  9403. this._orthoRight = Number.MIN_VALUE;
  9404. this._orthoTop = Number.MIN_VALUE;
  9405. this._orthoBottom = Number.MAX_VALUE;
  9406. this.position = direction.scale(-1);
  9407. this.direction = direction;
  9408. }
  9409. DirectionalLight.prototype.getAbsolutePosition = function () {
  9410. return this.transformedPosition ? this.transformedPosition : this.position;
  9411. };
  9412. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9413. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9414. return this.direction;
  9415. };
  9416. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9417. var activeCamera = this.getScene().activeCamera;
  9418. // Check extends
  9419. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9420. var tempVector3 = BABYLON.Vector3.Zero();
  9421. this._orthoLeft = Number.MAX_VALUE;
  9422. this._orthoRight = Number.MIN_VALUE;
  9423. this._orthoTop = Number.MIN_VALUE;
  9424. this._orthoBottom = Number.MAX_VALUE;
  9425. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9426. var mesh = renderList[meshIndex];
  9427. if (!mesh) {
  9428. continue;
  9429. }
  9430. var boundingInfo = mesh.getBoundingInfo();
  9431. if (!boundingInfo) {
  9432. continue;
  9433. }
  9434. var boundingBox = boundingInfo.boundingBox;
  9435. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9436. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9437. if (tempVector3.x < this._orthoLeft)
  9438. this._orthoLeft = tempVector3.x;
  9439. if (tempVector3.y < this._orthoBottom)
  9440. this._orthoBottom = tempVector3.y;
  9441. if (tempVector3.x > this._orthoRight)
  9442. this._orthoRight = tempVector3.x;
  9443. if (tempVector3.y > this._orthoTop)
  9444. this._orthoTop = tempVector3.y;
  9445. }
  9446. }
  9447. }
  9448. var xOffset = this._orthoRight - this._orthoLeft;
  9449. var yOffset = this._orthoTop - this._orthoBottom;
  9450. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  9451. };
  9452. DirectionalLight.prototype.supportsVSM = function () {
  9453. return true;
  9454. };
  9455. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9456. return true;
  9457. };
  9458. DirectionalLight.prototype.needCube = function () {
  9459. return false;
  9460. };
  9461. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9462. return this.direction;
  9463. };
  9464. DirectionalLight.prototype.computeTransformedPosition = function () {
  9465. if (this.parent && this.parent.getWorldMatrix) {
  9466. if (!this.transformedPosition) {
  9467. this.transformedPosition = BABYLON.Vector3.Zero();
  9468. }
  9469. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9470. return true;
  9471. }
  9472. return false;
  9473. };
  9474. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9475. if (this.parent && this.parent.getWorldMatrix) {
  9476. if (!this._transformedDirection) {
  9477. this._transformedDirection = BABYLON.Vector3.Zero();
  9478. }
  9479. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9480. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9481. return;
  9482. }
  9483. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9484. };
  9485. DirectionalLight.prototype._getWorldMatrix = function () {
  9486. if (!this._worldMatrix) {
  9487. this._worldMatrix = BABYLON.Matrix.Identity();
  9488. }
  9489. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9490. return this._worldMatrix;
  9491. };
  9492. DirectionalLight.prototype.getTypeID = function () {
  9493. return 1;
  9494. };
  9495. __decorate([
  9496. BABYLON.serializeAsVector3()
  9497. ], DirectionalLight.prototype, "position", void 0);
  9498. __decorate([
  9499. BABYLON.serializeAsVector3()
  9500. ], DirectionalLight.prototype, "direction", void 0);
  9501. __decorate([
  9502. BABYLON.serialize()
  9503. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9504. __decorate([
  9505. BABYLON.serialize()
  9506. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9507. return DirectionalLight;
  9508. })(BABYLON.Light);
  9509. BABYLON.DirectionalLight = DirectionalLight;
  9510. })(BABYLON || (BABYLON = {}));
  9511. var BABYLON;
  9512. (function (BABYLON) {
  9513. var ShadowGenerator = (function () {
  9514. function ShadowGenerator(mapSize, light) {
  9515. var _this = this;
  9516. // Members
  9517. this._filter = ShadowGenerator.FILTER_NONE;
  9518. this.blurScale = 2;
  9519. this._blurBoxOffset = 0;
  9520. this._bias = 0.00005;
  9521. this._lightDirection = BABYLON.Vector3.Zero();
  9522. this.forceBackFacesOnly = false;
  9523. this._darkness = 0;
  9524. this._transparencyShadow = false;
  9525. this._viewMatrix = BABYLON.Matrix.Zero();
  9526. this._projectionMatrix = BABYLON.Matrix.Zero();
  9527. this._transformMatrix = BABYLON.Matrix.Zero();
  9528. this._worldViewProjection = BABYLON.Matrix.Zero();
  9529. this._currentFaceIndex = 0;
  9530. this._currentFaceIndexCache = 0;
  9531. this._light = light;
  9532. this._scene = light.getScene();
  9533. this._mapSize = mapSize;
  9534. light._shadowGenerator = this;
  9535. // Render target
  9536. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9537. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9538. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9539. this._shadowMap.anisotropicFilteringLevel = 1;
  9540. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9541. this._shadowMap.renderParticles = false;
  9542. this._shadowMap.onBeforeRender = function (faceIndex) {
  9543. _this._currentFaceIndex = faceIndex;
  9544. };
  9545. this._shadowMap.onAfterUnbind = function () {
  9546. if (!_this.useBlurVarianceShadowMap) {
  9547. return;
  9548. }
  9549. if (!_this._shadowMap2) {
  9550. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9551. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9552. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9553. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9554. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9555. _this._downSamplePostprocess.onApply = function (effect) {
  9556. effect.setTexture("textureSampler", _this._shadowMap);
  9557. };
  9558. _this.blurBoxOffset = 1;
  9559. }
  9560. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9561. };
  9562. // Custom render function
  9563. var renderSubMesh = function (subMesh) {
  9564. var mesh = subMesh.getRenderingMesh();
  9565. var scene = _this._scene;
  9566. var engine = scene.getEngine();
  9567. // Culling
  9568. engine.setState(subMesh.getMaterial().backFaceCulling);
  9569. // Managing instances
  9570. var batch = mesh._getInstancesRenderList(subMesh._id);
  9571. if (batch.mustReturn) {
  9572. return;
  9573. }
  9574. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9575. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9576. engine.enableEffect(_this._effect);
  9577. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9578. var material = subMesh.getMaterial();
  9579. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9580. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9581. if (_this.getLight().needCube()) {
  9582. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9583. }
  9584. // Alpha test
  9585. if (material && material.needAlphaTesting()) {
  9586. var alphaTexture = material.getAlphaTestTexture();
  9587. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9588. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9589. }
  9590. // Bones
  9591. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9592. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9593. }
  9594. if (_this.forceBackFacesOnly) {
  9595. engine.setState(true, 0, false, true);
  9596. }
  9597. // Draw
  9598. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9599. if (_this.forceBackFacesOnly) {
  9600. engine.setState(true, 0, false, false);
  9601. }
  9602. }
  9603. else {
  9604. // Need to reset refresh rate of the shadowMap
  9605. _this._shadowMap.resetRefreshCounter();
  9606. }
  9607. };
  9608. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9609. var index;
  9610. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9611. renderSubMesh(opaqueSubMeshes.data[index]);
  9612. }
  9613. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9614. renderSubMesh(alphaTestSubMeshes.data[index]);
  9615. }
  9616. if (_this._transparencyShadow) {
  9617. for (index = 0; index < transparentSubMeshes.length; index++) {
  9618. renderSubMesh(transparentSubMeshes.data[index]);
  9619. }
  9620. }
  9621. };
  9622. this._shadowMap.onClear = function (engine) {
  9623. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9624. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9625. }
  9626. else {
  9627. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9628. }
  9629. };
  9630. }
  9631. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9632. // Static
  9633. get: function () {
  9634. return ShadowGenerator._FILTER_NONE;
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9640. get: function () {
  9641. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9642. },
  9643. enumerable: true,
  9644. configurable: true
  9645. });
  9646. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9647. get: function () {
  9648. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9649. },
  9650. enumerable: true,
  9651. configurable: true
  9652. });
  9653. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9654. get: function () {
  9655. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9656. },
  9657. enumerable: true,
  9658. configurable: true
  9659. });
  9660. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9661. get: function () {
  9662. return this._bias;
  9663. },
  9664. set: function (bias) {
  9665. this._bias = bias;
  9666. },
  9667. enumerable: true,
  9668. configurable: true
  9669. });
  9670. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9671. get: function () {
  9672. return this._blurBoxOffset;
  9673. },
  9674. set: function (value) {
  9675. var _this = this;
  9676. if (this._blurBoxOffset === value) {
  9677. return;
  9678. }
  9679. this._blurBoxOffset = value;
  9680. if (this._boxBlurPostprocess) {
  9681. this._boxBlurPostprocess.dispose();
  9682. }
  9683. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  9684. this._boxBlurPostprocess.onApply = function (effect) {
  9685. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9686. };
  9687. },
  9688. enumerable: true,
  9689. configurable: true
  9690. });
  9691. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9692. get: function () {
  9693. return this._filter;
  9694. },
  9695. set: function (value) {
  9696. if (this._filter === value) {
  9697. return;
  9698. }
  9699. this._filter = value;
  9700. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9701. this._shadowMap.anisotropicFilteringLevel = 16;
  9702. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9703. }
  9704. else {
  9705. this._shadowMap.anisotropicFilteringLevel = 1;
  9706. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9707. }
  9708. },
  9709. enumerable: true,
  9710. configurable: true
  9711. });
  9712. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9713. get: function () {
  9714. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9715. },
  9716. set: function (value) {
  9717. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9718. },
  9719. enumerable: true,
  9720. configurable: true
  9721. });
  9722. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9723. get: function () {
  9724. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9725. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9726. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9727. },
  9728. set: function (value) {
  9729. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9730. },
  9731. enumerable: true,
  9732. configurable: true
  9733. });
  9734. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9735. get: function () {
  9736. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9737. },
  9738. set: function (value) {
  9739. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9740. },
  9741. enumerable: true,
  9742. configurable: true
  9743. });
  9744. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9745. var defines = [];
  9746. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9747. defines.push("#define VSM");
  9748. }
  9749. if (this.getLight().needCube()) {
  9750. defines.push("#define CUBEMAP");
  9751. }
  9752. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9753. var mesh = subMesh.getMesh();
  9754. var material = subMesh.getMaterial();
  9755. // Alpha test
  9756. if (material && material.needAlphaTesting()) {
  9757. defines.push("#define ALPHATEST");
  9758. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9759. attribs.push(BABYLON.VertexBuffer.UVKind);
  9760. defines.push("#define UV1");
  9761. }
  9762. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9763. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9764. defines.push("#define UV2");
  9765. }
  9766. }
  9767. // Bones
  9768. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9769. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9770. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9771. if (mesh.numBoneInfluencers > 4) {
  9772. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9773. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9774. }
  9775. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9776. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9777. }
  9778. else {
  9779. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9780. }
  9781. // Instances
  9782. if (useInstances) {
  9783. defines.push("#define INSTANCES");
  9784. attribs.push("world0");
  9785. attribs.push("world1");
  9786. attribs.push("world2");
  9787. attribs.push("world3");
  9788. }
  9789. // Get correct effect
  9790. var join = defines.join("\n");
  9791. if (this._cachedDefines !== join) {
  9792. this._cachedDefines = join;
  9793. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9794. }
  9795. return this._effect.isReady();
  9796. };
  9797. ShadowGenerator.prototype.getShadowMap = function () {
  9798. return this._shadowMap;
  9799. };
  9800. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9801. if (this._shadowMap2) {
  9802. return this._shadowMap2;
  9803. }
  9804. return this._shadowMap;
  9805. };
  9806. ShadowGenerator.prototype.getLight = function () {
  9807. return this._light;
  9808. };
  9809. // Methods
  9810. ShadowGenerator.prototype.getTransformMatrix = function () {
  9811. var scene = this._scene;
  9812. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9813. return this._transformMatrix;
  9814. }
  9815. this._currentRenderID = scene.getRenderId();
  9816. this._currentFaceIndexCache = this._currentFaceIndex;
  9817. var lightPosition = this._light.position;
  9818. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9819. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9820. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9821. }
  9822. if (this._light.computeTransformedPosition()) {
  9823. lightPosition = this._light.transformedPosition;
  9824. }
  9825. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9826. this._cachedPosition = lightPosition.clone();
  9827. this._cachedDirection = this._lightDirection.clone();
  9828. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9829. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9830. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9831. }
  9832. return this._transformMatrix;
  9833. };
  9834. ShadowGenerator.prototype.getDarkness = function () {
  9835. return this._darkness;
  9836. };
  9837. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9838. if (darkness >= 1.0)
  9839. this._darkness = 1.0;
  9840. else if (darkness <= 0.0)
  9841. this._darkness = 0.0;
  9842. else
  9843. this._darkness = darkness;
  9844. };
  9845. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9846. this._transparencyShadow = hasShadow;
  9847. };
  9848. ShadowGenerator.prototype._packHalf = function (depth) {
  9849. var scale = depth * 255.0;
  9850. var fract = scale - Math.floor(scale);
  9851. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9852. };
  9853. ShadowGenerator.prototype.dispose = function () {
  9854. this._shadowMap.dispose();
  9855. if (this._shadowMap2) {
  9856. this._shadowMap2.dispose();
  9857. }
  9858. if (this._downSamplePostprocess) {
  9859. this._downSamplePostprocess.dispose();
  9860. }
  9861. if (this._boxBlurPostprocess) {
  9862. this._boxBlurPostprocess.dispose();
  9863. }
  9864. };
  9865. ShadowGenerator.prototype.serialize = function () {
  9866. var serializationObject = {};
  9867. serializationObject.lightId = this._light.id;
  9868. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9869. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9870. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9871. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9872. serializationObject.renderList = [];
  9873. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9874. var mesh = this.getShadowMap().renderList[meshIndex];
  9875. serializationObject.renderList.push(mesh.id);
  9876. }
  9877. return serializationObject;
  9878. };
  9879. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9880. //casting to point light, as light is missing the position attr and typescript complains.
  9881. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9882. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9883. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9884. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9885. shadowGenerator.getShadowMap().renderList.push(mesh);
  9886. }
  9887. if (parsedShadowGenerator.usePoissonSampling) {
  9888. shadowGenerator.usePoissonSampling = true;
  9889. }
  9890. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9891. shadowGenerator.useVarianceShadowMap = true;
  9892. }
  9893. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9894. shadowGenerator.useBlurVarianceShadowMap = true;
  9895. if (parsedShadowGenerator.blurScale) {
  9896. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9897. }
  9898. if (parsedShadowGenerator.blurBoxOffset) {
  9899. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9900. }
  9901. }
  9902. if (parsedShadowGenerator.bias !== undefined) {
  9903. shadowGenerator.bias = parsedShadowGenerator.bias;
  9904. }
  9905. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9906. return shadowGenerator;
  9907. };
  9908. ShadowGenerator._FILTER_NONE = 0;
  9909. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9910. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9911. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9912. return ShadowGenerator;
  9913. })();
  9914. BABYLON.ShadowGenerator = ShadowGenerator;
  9915. })(BABYLON || (BABYLON = {}));
  9916. var BABYLON;
  9917. (function (BABYLON) {
  9918. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9919. if (boxMin.x > sphereCenter.x + sphereRadius)
  9920. return false;
  9921. if (sphereCenter.x - sphereRadius > boxMax.x)
  9922. return false;
  9923. if (boxMin.y > sphereCenter.y + sphereRadius)
  9924. return false;
  9925. if (sphereCenter.y - sphereRadius > boxMax.y)
  9926. return false;
  9927. if (boxMin.z > sphereCenter.z + sphereRadius)
  9928. return false;
  9929. if (sphereCenter.z - sphereRadius > boxMax.z)
  9930. return false;
  9931. return true;
  9932. };
  9933. var getLowestRoot = function (a, b, c, maxR) {
  9934. var determinant = b * b - 4.0 * a * c;
  9935. var result = { root: 0, found: false };
  9936. if (determinant < 0)
  9937. return result;
  9938. var sqrtD = Math.sqrt(determinant);
  9939. var r1 = (-b - sqrtD) / (2.0 * a);
  9940. var r2 = (-b + sqrtD) / (2.0 * a);
  9941. if (r1 > r2) {
  9942. var temp = r2;
  9943. r2 = r1;
  9944. r1 = temp;
  9945. }
  9946. if (r1 > 0 && r1 < maxR) {
  9947. result.root = r1;
  9948. result.found = true;
  9949. return result;
  9950. }
  9951. if (r2 > 0 && r2 < maxR) {
  9952. result.root = r2;
  9953. result.found = true;
  9954. return result;
  9955. }
  9956. return result;
  9957. };
  9958. var Collider = (function () {
  9959. function Collider() {
  9960. this.radius = new BABYLON.Vector3(1, 1, 1);
  9961. this.retry = 0;
  9962. this.basePointWorld = BABYLON.Vector3.Zero();
  9963. this.velocityWorld = BABYLON.Vector3.Zero();
  9964. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9965. this._collisionPoint = BABYLON.Vector3.Zero();
  9966. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9967. this._tempVector = BABYLON.Vector3.Zero();
  9968. this._tempVector2 = BABYLON.Vector3.Zero();
  9969. this._tempVector3 = BABYLON.Vector3.Zero();
  9970. this._tempVector4 = BABYLON.Vector3.Zero();
  9971. this._edge = BABYLON.Vector3.Zero();
  9972. this._baseToVertex = BABYLON.Vector3.Zero();
  9973. this._destinationPoint = BABYLON.Vector3.Zero();
  9974. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9975. this._displacementVector = BABYLON.Vector3.Zero();
  9976. }
  9977. // Methods
  9978. Collider.prototype._initialize = function (source, dir, e) {
  9979. this.velocity = dir;
  9980. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9981. this.basePoint = source;
  9982. source.multiplyToRef(this.radius, this.basePointWorld);
  9983. dir.multiplyToRef(this.radius, this.velocityWorld);
  9984. this.velocityWorldLength = this.velocityWorld.length();
  9985. this.epsilon = e;
  9986. this.collisionFound = false;
  9987. };
  9988. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9989. pa.subtractToRef(point, this._tempVector);
  9990. pb.subtractToRef(point, this._tempVector2);
  9991. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9992. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9993. if (d < 0)
  9994. return false;
  9995. pc.subtractToRef(point, this._tempVector3);
  9996. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9997. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9998. if (d < 0)
  9999. return false;
  10000. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10001. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10002. return d >= 0;
  10003. };
  10004. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10005. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10006. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10007. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10008. return false;
  10009. }
  10010. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10011. return false;
  10012. return true;
  10013. };
  10014. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10015. var t0;
  10016. var embeddedInPlane = false;
  10017. //defensive programming, actually not needed.
  10018. if (!trianglePlaneArray) {
  10019. trianglePlaneArray = [];
  10020. }
  10021. if (!trianglePlaneArray[faceIndex]) {
  10022. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10023. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10024. }
  10025. var trianglePlane = trianglePlaneArray[faceIndex];
  10026. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10027. return;
  10028. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10029. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10030. if (normalDotVelocity == 0) {
  10031. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10032. return;
  10033. embeddedInPlane = true;
  10034. t0 = 0;
  10035. }
  10036. else {
  10037. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10038. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10039. if (t0 > t1) {
  10040. var temp = t1;
  10041. t1 = t0;
  10042. t0 = temp;
  10043. }
  10044. if (t0 > 1.0 || t1 < 0.0)
  10045. return;
  10046. if (t0 < 0)
  10047. t0 = 0;
  10048. if (t0 > 1.0)
  10049. t0 = 1.0;
  10050. }
  10051. this._collisionPoint.copyFromFloats(0, 0, 0);
  10052. var found = false;
  10053. var t = 1.0;
  10054. if (!embeddedInPlane) {
  10055. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10056. this.velocity.scaleToRef(t0, this._tempVector);
  10057. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10058. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10059. found = true;
  10060. t = t0;
  10061. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10062. }
  10063. }
  10064. if (!found) {
  10065. var velocitySquaredLength = this.velocity.lengthSquared();
  10066. var a = velocitySquaredLength;
  10067. this.basePoint.subtractToRef(p1, this._tempVector);
  10068. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10069. var c = this._tempVector.lengthSquared() - 1.0;
  10070. var lowestRoot = getLowestRoot(a, b, c, t);
  10071. if (lowestRoot.found) {
  10072. t = lowestRoot.root;
  10073. found = true;
  10074. this._collisionPoint.copyFrom(p1);
  10075. }
  10076. this.basePoint.subtractToRef(p2, this._tempVector);
  10077. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10078. c = this._tempVector.lengthSquared() - 1.0;
  10079. lowestRoot = getLowestRoot(a, b, c, t);
  10080. if (lowestRoot.found) {
  10081. t = lowestRoot.root;
  10082. found = true;
  10083. this._collisionPoint.copyFrom(p2);
  10084. }
  10085. this.basePoint.subtractToRef(p3, this._tempVector);
  10086. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10087. c = this._tempVector.lengthSquared() - 1.0;
  10088. lowestRoot = getLowestRoot(a, b, c, t);
  10089. if (lowestRoot.found) {
  10090. t = lowestRoot.root;
  10091. found = true;
  10092. this._collisionPoint.copyFrom(p3);
  10093. }
  10094. p2.subtractToRef(p1, this._edge);
  10095. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10096. var edgeSquaredLength = this._edge.lengthSquared();
  10097. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10098. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10099. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10100. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10101. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10102. lowestRoot = getLowestRoot(a, b, c, t);
  10103. if (lowestRoot.found) {
  10104. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10105. if (f >= 0.0 && f <= 1.0) {
  10106. t = lowestRoot.root;
  10107. found = true;
  10108. this._edge.scaleInPlace(f);
  10109. p1.addToRef(this._edge, this._collisionPoint);
  10110. }
  10111. }
  10112. p3.subtractToRef(p2, this._edge);
  10113. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10114. edgeSquaredLength = this._edge.lengthSquared();
  10115. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10116. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10117. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10118. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10119. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10120. lowestRoot = getLowestRoot(a, b, c, t);
  10121. if (lowestRoot.found) {
  10122. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10123. if (f >= 0.0 && f <= 1.0) {
  10124. t = lowestRoot.root;
  10125. found = true;
  10126. this._edge.scaleInPlace(f);
  10127. p2.addToRef(this._edge, this._collisionPoint);
  10128. }
  10129. }
  10130. p1.subtractToRef(p3, this._edge);
  10131. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10132. edgeSquaredLength = this._edge.lengthSquared();
  10133. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10134. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10135. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10136. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10137. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10138. lowestRoot = getLowestRoot(a, b, c, t);
  10139. if (lowestRoot.found) {
  10140. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10141. if (f >= 0.0 && f <= 1.0) {
  10142. t = lowestRoot.root;
  10143. found = true;
  10144. this._edge.scaleInPlace(f);
  10145. p3.addToRef(this._edge, this._collisionPoint);
  10146. }
  10147. }
  10148. }
  10149. if (found) {
  10150. var distToCollision = t * this.velocity.length();
  10151. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10152. if (!this.intersectionPoint) {
  10153. this.intersectionPoint = this._collisionPoint.clone();
  10154. }
  10155. else {
  10156. this.intersectionPoint.copyFrom(this._collisionPoint);
  10157. }
  10158. this.nearestDistance = distToCollision;
  10159. this.collisionFound = true;
  10160. }
  10161. }
  10162. };
  10163. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10164. for (var i = indexStart; i < indexEnd; i += 3) {
  10165. var p1 = pts[indices[i] - decal];
  10166. var p2 = pts[indices[i + 1] - decal];
  10167. var p3 = pts[indices[i + 2] - decal];
  10168. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10169. }
  10170. };
  10171. Collider.prototype._getResponse = function (pos, vel) {
  10172. pos.addToRef(vel, this._destinationPoint);
  10173. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10174. this.basePoint.addToRef(vel, pos);
  10175. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10176. this._slidePlaneNormal.normalize();
  10177. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10178. pos.addInPlace(this._displacementVector);
  10179. this.intersectionPoint.addInPlace(this._displacementVector);
  10180. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10181. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10182. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10183. };
  10184. return Collider;
  10185. })();
  10186. BABYLON.Collider = Collider;
  10187. })(BABYLON || (BABYLON = {}));
  10188. var BABYLON;
  10189. (function (BABYLON) {
  10190. //WebWorker code will be inserted to this variable.
  10191. BABYLON.CollisionWorker = "";
  10192. (function (WorkerTaskType) {
  10193. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10194. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10195. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10196. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10197. var WorkerTaskType = BABYLON.WorkerTaskType;
  10198. (function (WorkerReplyType) {
  10199. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10200. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10201. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10202. var WorkerReplyType = BABYLON.WorkerReplyType;
  10203. var CollisionCoordinatorWorker = (function () {
  10204. function CollisionCoordinatorWorker() {
  10205. var _this = this;
  10206. this._scaledPosition = BABYLON.Vector3.Zero();
  10207. this._scaledVelocity = BABYLON.Vector3.Zero();
  10208. this.onMeshUpdated = function (mesh) {
  10209. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10210. };
  10211. this.onGeometryUpdated = function (geometry) {
  10212. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10213. };
  10214. this._afterRender = function () {
  10215. if (!_this._init)
  10216. return;
  10217. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10218. return;
  10219. }
  10220. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10221. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10222. if (_this._runningUpdated > 4) {
  10223. return;
  10224. }
  10225. ++_this._runningUpdated;
  10226. var payload = {
  10227. updatedMeshes: _this._addUpdateMeshesList,
  10228. updatedGeometries: _this._addUpdateGeometriesList,
  10229. removedGeometries: _this._toRemoveGeometryArray,
  10230. removedMeshes: _this._toRemoveMeshesArray
  10231. };
  10232. var message = {
  10233. payload: payload,
  10234. taskType: WorkerTaskType.UPDATE
  10235. };
  10236. var serializable = [];
  10237. for (var id in payload.updatedGeometries) {
  10238. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10239. //prepare transferables
  10240. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10241. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10242. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10243. }
  10244. }
  10245. _this._worker.postMessage(message, serializable);
  10246. _this._addUpdateMeshesList = {};
  10247. _this._addUpdateGeometriesList = {};
  10248. _this._toRemoveGeometryArray = [];
  10249. _this._toRemoveMeshesArray = [];
  10250. };
  10251. this._onMessageFromWorker = function (e) {
  10252. var returnData = e.data;
  10253. if (returnData.error != WorkerReplyType.SUCCESS) {
  10254. //TODO what errors can be returned from the worker?
  10255. BABYLON.Tools.Warn("error returned from worker!");
  10256. return;
  10257. }
  10258. switch (returnData.taskType) {
  10259. case WorkerTaskType.INIT:
  10260. _this._init = true;
  10261. //Update the worked with ALL of the scene's current state
  10262. _this._scene.meshes.forEach(function (mesh) {
  10263. _this.onMeshAdded(mesh);
  10264. });
  10265. _this._scene.getGeometries().forEach(function (geometry) {
  10266. _this.onGeometryAdded(geometry);
  10267. });
  10268. break;
  10269. case WorkerTaskType.UPDATE:
  10270. _this._runningUpdated--;
  10271. break;
  10272. case WorkerTaskType.COLLIDE:
  10273. _this._runningCollisionTask = false;
  10274. var returnPayload = returnData.payload;
  10275. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10276. return;
  10277. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10278. //cleanup
  10279. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10280. break;
  10281. }
  10282. };
  10283. this._collisionsCallbackArray = [];
  10284. this._init = false;
  10285. this._runningUpdated = 0;
  10286. this._runningCollisionTask = false;
  10287. this._addUpdateMeshesList = {};
  10288. this._addUpdateGeometriesList = {};
  10289. this._toRemoveGeometryArray = [];
  10290. this._toRemoveMeshesArray = [];
  10291. }
  10292. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10293. if (!this._init)
  10294. return;
  10295. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10296. return;
  10297. position.divideToRef(collider.radius, this._scaledPosition);
  10298. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10299. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10300. var payload = {
  10301. collider: {
  10302. position: this._scaledPosition.asArray(),
  10303. velocity: this._scaledVelocity.asArray(),
  10304. radius: collider.radius.asArray()
  10305. },
  10306. collisionId: collisionIndex,
  10307. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10308. maximumRetry: maximumRetry
  10309. };
  10310. var message = {
  10311. payload: payload,
  10312. taskType: WorkerTaskType.COLLIDE
  10313. };
  10314. this._worker.postMessage(message);
  10315. };
  10316. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10317. this._scene = scene;
  10318. this._scene.registerAfterRender(this._afterRender);
  10319. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10320. this._worker = new Worker(workerUrl);
  10321. this._worker.onmessage = this._onMessageFromWorker;
  10322. var message = {
  10323. payload: {},
  10324. taskType: WorkerTaskType.INIT
  10325. };
  10326. this._worker.postMessage(message);
  10327. };
  10328. CollisionCoordinatorWorker.prototype.destroy = function () {
  10329. this._scene.unregisterAfterRender(this._afterRender);
  10330. this._worker.terminate();
  10331. };
  10332. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10333. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10334. this.onMeshUpdated(mesh);
  10335. };
  10336. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10337. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10338. };
  10339. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10340. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10341. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10342. this.onGeometryUpdated(geometry);
  10343. };
  10344. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10345. this._toRemoveGeometryArray.push(geometry.id);
  10346. };
  10347. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10348. var submeshes = [];
  10349. if (mesh.subMeshes) {
  10350. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10351. return {
  10352. position: idx,
  10353. verticesStart: sm.verticesStart,
  10354. verticesCount: sm.verticesCount,
  10355. indexStart: sm.indexStart,
  10356. indexCount: sm.indexCount,
  10357. hasMaterial: !!sm.getMaterial(),
  10358. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10359. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10360. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10361. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10362. };
  10363. });
  10364. }
  10365. var geometryId = null;
  10366. if (mesh instanceof BABYLON.Mesh) {
  10367. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10368. }
  10369. else if (mesh instanceof BABYLON.InstancedMesh) {
  10370. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10371. }
  10372. return {
  10373. uniqueId: mesh.uniqueId,
  10374. id: mesh.id,
  10375. name: mesh.name,
  10376. geometryId: geometryId,
  10377. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10378. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10379. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10380. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10381. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10382. subMeshes: submeshes,
  10383. checkCollisions: mesh.checkCollisions
  10384. };
  10385. };
  10386. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10387. return {
  10388. id: geometry.id,
  10389. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10390. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10391. indices: new Int32Array(geometry.getIndices() || []),
  10392. };
  10393. };
  10394. return CollisionCoordinatorWorker;
  10395. })();
  10396. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10397. var CollisionCoordinatorLegacy = (function () {
  10398. function CollisionCoordinatorLegacy() {
  10399. this._scaledPosition = BABYLON.Vector3.Zero();
  10400. this._scaledVelocity = BABYLON.Vector3.Zero();
  10401. this._finalPosition = BABYLON.Vector3.Zero();
  10402. }
  10403. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10404. position.divideToRef(collider.radius, this._scaledPosition);
  10405. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10406. collider.collidedMesh = null;
  10407. collider.retry = 0;
  10408. collider.initialVelocity = this._scaledVelocity;
  10409. collider.initialPosition = this._scaledPosition;
  10410. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10411. this._finalPosition.multiplyInPlace(collider.radius);
  10412. //run the callback
  10413. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10414. };
  10415. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10416. this._scene = scene;
  10417. };
  10418. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10419. //Legacy need no destruction method.
  10420. };
  10421. //No update in legacy mode
  10422. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10423. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10424. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10425. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10426. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10427. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10428. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10429. if (excludedMesh === void 0) { excludedMesh = null; }
  10430. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10431. if (collider.retry >= maximumRetry) {
  10432. finalPosition.copyFrom(position);
  10433. return;
  10434. }
  10435. collider._initialize(position, velocity, closeDistance);
  10436. // Check all meshes
  10437. for (var index = 0; index < this._scene.meshes.length; index++) {
  10438. var mesh = this._scene.meshes[index];
  10439. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10440. mesh._checkCollision(collider);
  10441. }
  10442. }
  10443. if (!collider.collisionFound) {
  10444. position.addToRef(velocity, finalPosition);
  10445. return;
  10446. }
  10447. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10448. collider._getResponse(position, velocity);
  10449. }
  10450. if (velocity.length() <= closeDistance) {
  10451. finalPosition.copyFrom(position);
  10452. return;
  10453. }
  10454. collider.retry++;
  10455. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10456. };
  10457. return CollisionCoordinatorLegacy;
  10458. })();
  10459. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10460. })(BABYLON || (BABYLON = {}));
  10461. var BABYLON;
  10462. (function (BABYLON) {
  10463. var Camera = (function (_super) {
  10464. __extends(Camera, _super);
  10465. function Camera(name, position, scene) {
  10466. _super.call(this, name, scene);
  10467. this.upVector = BABYLON.Vector3.Up();
  10468. this.orthoLeft = null;
  10469. this.orthoRight = null;
  10470. this.orthoBottom = null;
  10471. this.orthoTop = null;
  10472. this.fov = 0.8;
  10473. this.minZ = 1.0;
  10474. this.maxZ = 10000.0;
  10475. this.inertia = 0.9;
  10476. this.mode = Camera.PERSPECTIVE_CAMERA;
  10477. this.isIntermediate = false;
  10478. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10479. this.layerMask = 0x0FFFFFFF;
  10480. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10481. // Camera rig members
  10482. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10483. this._rigCameras = new Array();
  10484. // Cache
  10485. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10486. this._projectionMatrix = new BABYLON.Matrix();
  10487. this._postProcesses = new Array();
  10488. this._postProcessesTakenIndices = [];
  10489. this._activeMeshes = new BABYLON.SmartArray(256);
  10490. this._globalPosition = BABYLON.Vector3.Zero();
  10491. scene.addCamera(this);
  10492. if (!scene.activeCamera) {
  10493. scene.activeCamera = this;
  10494. }
  10495. this.position = position;
  10496. }
  10497. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10498. get: function () {
  10499. return Camera._PERSPECTIVE_CAMERA;
  10500. },
  10501. enumerable: true,
  10502. configurable: true
  10503. });
  10504. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10505. get: function () {
  10506. return Camera._ORTHOGRAPHIC_CAMERA;
  10507. },
  10508. enumerable: true,
  10509. configurable: true
  10510. });
  10511. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10512. get: function () {
  10513. return Camera._FOVMODE_VERTICAL_FIXED;
  10514. },
  10515. enumerable: true,
  10516. configurable: true
  10517. });
  10518. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10519. get: function () {
  10520. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10521. },
  10522. enumerable: true,
  10523. configurable: true
  10524. });
  10525. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10526. get: function () {
  10527. return Camera._RIG_MODE_NONE;
  10528. },
  10529. enumerable: true,
  10530. configurable: true
  10531. });
  10532. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10533. get: function () {
  10534. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10535. },
  10536. enumerable: true,
  10537. configurable: true
  10538. });
  10539. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10540. get: function () {
  10541. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10542. },
  10543. enumerable: true,
  10544. configurable: true
  10545. });
  10546. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10547. get: function () {
  10548. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10549. },
  10550. enumerable: true,
  10551. configurable: true
  10552. });
  10553. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10554. get: function () {
  10555. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10556. },
  10557. enumerable: true,
  10558. configurable: true
  10559. });
  10560. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10561. get: function () {
  10562. return Camera._RIG_MODE_VR;
  10563. },
  10564. enumerable: true,
  10565. configurable: true
  10566. });
  10567. /**
  10568. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10569. */
  10570. Camera.prototype.toString = function (fullDetails) {
  10571. var ret = "Name: " + this.name;
  10572. ret += ", type: " + this.getTypeName();
  10573. if (this.animations) {
  10574. for (var i = 0; i < this.animations.length; i++) {
  10575. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10576. }
  10577. }
  10578. if (fullDetails) {
  10579. }
  10580. return ret;
  10581. };
  10582. Object.defineProperty(Camera.prototype, "globalPosition", {
  10583. get: function () {
  10584. return this._globalPosition;
  10585. },
  10586. enumerable: true,
  10587. configurable: true
  10588. });
  10589. Camera.prototype.getActiveMeshes = function () {
  10590. return this._activeMeshes;
  10591. };
  10592. Camera.prototype.isActiveMesh = function (mesh) {
  10593. return (this._activeMeshes.indexOf(mesh) !== -1);
  10594. };
  10595. //Cache
  10596. Camera.prototype._initCache = function () {
  10597. _super.prototype._initCache.call(this);
  10598. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10599. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10600. this._cache.mode = undefined;
  10601. this._cache.minZ = undefined;
  10602. this._cache.maxZ = undefined;
  10603. this._cache.fov = undefined;
  10604. this._cache.aspectRatio = undefined;
  10605. this._cache.orthoLeft = undefined;
  10606. this._cache.orthoRight = undefined;
  10607. this._cache.orthoBottom = undefined;
  10608. this._cache.orthoTop = undefined;
  10609. this._cache.renderWidth = undefined;
  10610. this._cache.renderHeight = undefined;
  10611. };
  10612. Camera.prototype._updateCache = function (ignoreParentClass) {
  10613. if (!ignoreParentClass) {
  10614. _super.prototype._updateCache.call(this);
  10615. }
  10616. var engine = this.getEngine();
  10617. this._cache.position.copyFrom(this.position);
  10618. this._cache.upVector.copyFrom(this.upVector);
  10619. this._cache.mode = this.mode;
  10620. this._cache.minZ = this.minZ;
  10621. this._cache.maxZ = this.maxZ;
  10622. this._cache.fov = this.fov;
  10623. this._cache.aspectRatio = engine.getAspectRatio(this);
  10624. this._cache.orthoLeft = this.orthoLeft;
  10625. this._cache.orthoRight = this.orthoRight;
  10626. this._cache.orthoBottom = this.orthoBottom;
  10627. this._cache.orthoTop = this.orthoTop;
  10628. this._cache.renderWidth = engine.getRenderWidth();
  10629. this._cache.renderHeight = engine.getRenderHeight();
  10630. };
  10631. Camera.prototype._updateFromScene = function () {
  10632. this.updateCache();
  10633. this._update();
  10634. };
  10635. // Synchronized
  10636. Camera.prototype._isSynchronized = function () {
  10637. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10638. };
  10639. Camera.prototype._isSynchronizedViewMatrix = function () {
  10640. if (!_super.prototype._isSynchronized.call(this))
  10641. return false;
  10642. return this._cache.position.equals(this.position)
  10643. && this._cache.upVector.equals(this.upVector)
  10644. && this.isSynchronizedWithParent();
  10645. };
  10646. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10647. var check = this._cache.mode === this.mode
  10648. && this._cache.minZ === this.minZ
  10649. && this._cache.maxZ === this.maxZ;
  10650. if (!check) {
  10651. return false;
  10652. }
  10653. var engine = this.getEngine();
  10654. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10655. check = this._cache.fov === this.fov
  10656. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10657. }
  10658. else {
  10659. check = this._cache.orthoLeft === this.orthoLeft
  10660. && this._cache.orthoRight === this.orthoRight
  10661. && this._cache.orthoBottom === this.orthoBottom
  10662. && this._cache.orthoTop === this.orthoTop
  10663. && this._cache.renderWidth === engine.getRenderWidth()
  10664. && this._cache.renderHeight === engine.getRenderHeight();
  10665. }
  10666. return check;
  10667. };
  10668. // Controls
  10669. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10670. };
  10671. Camera.prototype.detachControl = function (element) {
  10672. };
  10673. Camera.prototype._update = function () {
  10674. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10675. this._updateRigCameras();
  10676. }
  10677. this._checkInputs();
  10678. };
  10679. Camera.prototype._checkInputs = function () {
  10680. };
  10681. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10682. if (insertAt === void 0) { insertAt = null; }
  10683. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10684. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10685. return 0;
  10686. }
  10687. if (insertAt == null || insertAt < 0) {
  10688. this._postProcesses.push(postProcess);
  10689. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10690. return this._postProcesses.length - 1;
  10691. }
  10692. var add = 0;
  10693. var i;
  10694. var start;
  10695. if (this._postProcesses[insertAt]) {
  10696. start = this._postProcesses.length - 1;
  10697. for (i = start; i >= insertAt + 1; --i) {
  10698. this._postProcesses[i + 1] = this._postProcesses[i];
  10699. }
  10700. add = 1;
  10701. }
  10702. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10703. if (this._postProcessesTakenIndices[i] < insertAt) {
  10704. continue;
  10705. }
  10706. start = this._postProcessesTakenIndices.length - 1;
  10707. for (var j = start; j >= i; --j) {
  10708. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10709. }
  10710. this._postProcessesTakenIndices[i] = insertAt;
  10711. break;
  10712. }
  10713. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10714. this._postProcessesTakenIndices.push(insertAt);
  10715. }
  10716. var result = insertAt + add;
  10717. this._postProcesses[result] = postProcess;
  10718. return result;
  10719. };
  10720. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10721. if (atIndices === void 0) { atIndices = null; }
  10722. var result = [];
  10723. var i;
  10724. var index;
  10725. if (!atIndices) {
  10726. var length = this._postProcesses.length;
  10727. for (i = 0; i < length; i++) {
  10728. if (this._postProcesses[i] !== postProcess) {
  10729. continue;
  10730. }
  10731. delete this._postProcesses[i];
  10732. index = this._postProcessesTakenIndices.indexOf(i);
  10733. this._postProcessesTakenIndices.splice(index, 1);
  10734. }
  10735. }
  10736. else {
  10737. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10738. for (i = 0; i < atIndices.length; i++) {
  10739. var foundPostProcess = this._postProcesses[atIndices[i]];
  10740. if (foundPostProcess !== postProcess) {
  10741. result.push(i);
  10742. continue;
  10743. }
  10744. delete this._postProcesses[atIndices[i]];
  10745. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10746. this._postProcessesTakenIndices.splice(index, 1);
  10747. }
  10748. }
  10749. return result;
  10750. };
  10751. Camera.prototype.getWorldMatrix = function () {
  10752. if (!this._worldMatrix) {
  10753. this._worldMatrix = BABYLON.Matrix.Identity();
  10754. }
  10755. var viewMatrix = this.getViewMatrix();
  10756. viewMatrix.invertToRef(this._worldMatrix);
  10757. return this._worldMatrix;
  10758. };
  10759. Camera.prototype._getViewMatrix = function () {
  10760. return BABYLON.Matrix.Identity();
  10761. };
  10762. Camera.prototype.getViewMatrix = function (force) {
  10763. this._computedViewMatrix = this._computeViewMatrix(force);
  10764. if (!force && this._isSynchronizedViewMatrix()) {
  10765. return this._computedViewMatrix;
  10766. }
  10767. if (!this.parent || !this.parent.getWorldMatrix) {
  10768. this._globalPosition.copyFrom(this.position);
  10769. }
  10770. else {
  10771. if (!this._worldMatrix) {
  10772. this._worldMatrix = BABYLON.Matrix.Identity();
  10773. }
  10774. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10775. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10776. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10777. this._computedViewMatrix.invert();
  10778. this._markSyncedWithParent();
  10779. }
  10780. this._currentRenderId = this.getScene().getRenderId();
  10781. return this._computedViewMatrix;
  10782. };
  10783. Camera.prototype._computeViewMatrix = function (force) {
  10784. if (!force && this._isSynchronizedViewMatrix()) {
  10785. return this._computedViewMatrix;
  10786. }
  10787. this._computedViewMatrix = this._getViewMatrix();
  10788. this._currentRenderId = this.getScene().getRenderId();
  10789. return this._computedViewMatrix;
  10790. };
  10791. Camera.prototype.getProjectionMatrix = function (force) {
  10792. if (!force && this._isSynchronizedProjectionMatrix()) {
  10793. return this._projectionMatrix;
  10794. }
  10795. var engine = this.getEngine();
  10796. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10797. if (this.minZ <= 0) {
  10798. this.minZ = 0.1;
  10799. }
  10800. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  10801. return this._projectionMatrix;
  10802. }
  10803. var halfWidth = engine.getRenderWidth() / 2.0;
  10804. var halfHeight = engine.getRenderHeight() / 2.0;
  10805. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10806. return this._projectionMatrix;
  10807. };
  10808. Camera.prototype.dispose = function () {
  10809. // Animations
  10810. this.getScene().stopAnimation(this);
  10811. // Remove from scene
  10812. this.getScene().removeCamera(this);
  10813. while (this._rigCameras.length > 0) {
  10814. this._rigCameras.pop().dispose();
  10815. }
  10816. // Postprocesses
  10817. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10818. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10819. }
  10820. };
  10821. // ---- Camera rigs section ----
  10822. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10823. while (this._rigCameras.length > 0) {
  10824. this._rigCameras.pop().dispose();
  10825. }
  10826. this.cameraRigMode = mode;
  10827. this._cameraRigParams = {};
  10828. switch (this.cameraRigMode) {
  10829. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10830. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10831. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10832. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10833. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10834. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10835. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10836. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10837. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10838. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10839. break;
  10840. }
  10841. var postProcesses = new Array();
  10842. switch (this.cameraRigMode) {
  10843. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10844. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10845. this._rigCameras[0].isIntermediate = true;
  10846. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10847. postProcesses[1].onApply = function (effect) {
  10848. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10849. };
  10850. break;
  10851. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10852. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10853. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10854. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10855. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10856. var secondCamIndex = 1 - firstCamIndex;
  10857. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10858. this._rigCameras[firstCamIndex].isIntermediate = true;
  10859. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10860. break;
  10861. case Camera.RIG_MODE_VR:
  10862. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10863. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10864. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  10865. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10866. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10867. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10868. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10869. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10870. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10871. if (metrics.compensateDistortion) {
  10872. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10873. }
  10874. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10875. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10876. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10877. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10878. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10879. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10880. if (metrics.compensateDistortion) {
  10881. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10882. }
  10883. break;
  10884. }
  10885. this._update();
  10886. };
  10887. Camera.prototype._getVRProjectionMatrix = function () {
  10888. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10889. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10890. return this._projectionMatrix;
  10891. };
  10892. Camera.prototype.setCameraRigParameter = function (name, value) {
  10893. this._cameraRigParams[name] = value;
  10894. //provisionnally:
  10895. if (name === "interaxialDistance") {
  10896. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10897. }
  10898. };
  10899. /**
  10900. * May needs to be overridden by children so sub has required properties to be copied
  10901. */
  10902. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10903. return null;
  10904. };
  10905. /**
  10906. * May needs to be overridden by children
  10907. */
  10908. Camera.prototype._updateRigCameras = function () {
  10909. for (var i = 0; i < this._rigCameras.length; i++) {
  10910. this._rigCameras[i].minZ = this.minZ;
  10911. this._rigCameras[i].maxZ = this.maxZ;
  10912. this._rigCameras[i].fov = this.fov;
  10913. }
  10914. // only update viewport when ANAGLYPH
  10915. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10916. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10917. }
  10918. };
  10919. Camera.prototype.serialize = function () {
  10920. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10921. // Type
  10922. serializationObject.type = this.getTypeName();
  10923. // Parent
  10924. if (this.parent) {
  10925. serializationObject.parentId = this.parent.id;
  10926. }
  10927. if (this.inputs) {
  10928. this.inputs.serialize(serializationObject);
  10929. }
  10930. // Animations
  10931. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10932. serializationObject.ranges = this.serializeAnimationRanges();
  10933. return serializationObject;
  10934. };
  10935. Camera.prototype.getTypeName = function () {
  10936. return "Camera";
  10937. };
  10938. Camera.prototype.clone = function (name) {
  10939. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  10940. };
  10941. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  10942. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  10943. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  10944. switch (type) {
  10945. case "ArcRotateCamera":
  10946. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  10947. case "DeviceOrientationCamera":
  10948. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  10949. case "FollowCamera":
  10950. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  10951. case "ArcFollowCamera":
  10952. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  10953. case "GamepadCamera":
  10954. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  10955. case "TouchCamera":
  10956. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  10957. case "VirtualJoysticksCamera":
  10958. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  10959. case "WebVRFreeCamera":
  10960. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10961. case "VRDeviceOrientationFreeCamera":
  10962. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10963. case "AnaglyphArcRotateCamera":
  10964. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10965. case "AnaglyphFreeCamera":
  10966. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10967. case "AnaglyphGamepadCamera":
  10968. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10969. case "AnaglyphUniversalCamera":
  10970. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10971. case "StereoscopicArcRotateCamera":
  10972. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10973. case "StereoscopicFreeCamera":
  10974. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10975. case "StereoscopicGamepadCamera":
  10976. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10977. case "StereoscopicUniversalCamera":
  10978. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10979. case "FreeCamera":
  10980. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10981. default:
  10982. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10983. }
  10984. };
  10985. Camera.Parse = function (parsedCamera, scene) {
  10986. var type = parsedCamera.type;
  10987. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  10988. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  10989. // Parent
  10990. if (parsedCamera.parentId) {
  10991. camera._waitingParentId = parsedCamera.parentId;
  10992. }
  10993. //If camera has an input manager, let it parse inputs settings
  10994. if (camera.inputs) {
  10995. camera.inputs.parse(parsedCamera);
  10996. }
  10997. // Target
  10998. if (parsedCamera.target) {
  10999. if (camera.setTarget) {
  11000. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11001. }
  11002. }
  11003. // Apply 3d rig, when found
  11004. if (parsedCamera.cameraRigMode) {
  11005. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11006. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11007. }
  11008. // Animations
  11009. if (parsedCamera.animations) {
  11010. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11011. var parsedAnimation = parsedCamera.animations[animationIndex];
  11012. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11013. }
  11014. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11015. }
  11016. if (parsedCamera.autoAnimate) {
  11017. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11018. }
  11019. return camera;
  11020. };
  11021. // Statics
  11022. Camera._PERSPECTIVE_CAMERA = 0;
  11023. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11024. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11025. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11026. Camera._RIG_MODE_NONE = 0;
  11027. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11028. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11029. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11030. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11031. Camera._RIG_MODE_VR = 20;
  11032. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11033. __decorate([
  11034. BABYLON.serializeAsVector3()
  11035. ], Camera.prototype, "position", void 0);
  11036. __decorate([
  11037. BABYLON.serialize()
  11038. ], Camera.prototype, "upVector", void 0);
  11039. __decorate([
  11040. BABYLON.serialize()
  11041. ], Camera.prototype, "orthoLeft", void 0);
  11042. __decorate([
  11043. BABYLON.serialize()
  11044. ], Camera.prototype, "orthoRight", void 0);
  11045. __decorate([
  11046. BABYLON.serialize()
  11047. ], Camera.prototype, "orthoBottom", void 0);
  11048. __decorate([
  11049. BABYLON.serialize()
  11050. ], Camera.prototype, "orthoTop", void 0);
  11051. __decorate([
  11052. BABYLON.serialize()
  11053. ], Camera.prototype, "fov", void 0);
  11054. __decorate([
  11055. BABYLON.serialize()
  11056. ], Camera.prototype, "minZ", void 0);
  11057. __decorate([
  11058. BABYLON.serialize()
  11059. ], Camera.prototype, "maxZ", void 0);
  11060. __decorate([
  11061. BABYLON.serialize()
  11062. ], Camera.prototype, "inertia", void 0);
  11063. __decorate([
  11064. BABYLON.serialize()
  11065. ], Camera.prototype, "mode", void 0);
  11066. __decorate([
  11067. BABYLON.serialize()
  11068. ], Camera.prototype, "layerMask", void 0);
  11069. __decorate([
  11070. BABYLON.serialize()
  11071. ], Camera.prototype, "fovMode", void 0);
  11072. __decorate([
  11073. BABYLON.serialize()
  11074. ], Camera.prototype, "cameraRigMode", void 0);
  11075. __decorate([
  11076. BABYLON.serialize()
  11077. ], Camera.prototype, "interaxialDistance", void 0);
  11078. __decorate([
  11079. BABYLON.serialize()
  11080. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11081. return Camera;
  11082. })(BABYLON.Node);
  11083. BABYLON.Camera = Camera;
  11084. })(BABYLON || (BABYLON = {}));
  11085. var BABYLON;
  11086. (function (BABYLON) {
  11087. BABYLON.CameraInputTypes = {};
  11088. var CameraInputsManager = (function () {
  11089. function CameraInputsManager(camera) {
  11090. this.attached = {};
  11091. this.camera = camera;
  11092. this.checkInputs = function () { };
  11093. }
  11094. CameraInputsManager.prototype.add = function (input) {
  11095. var type = input.getSimpleName();
  11096. if (this.attached[type]) {
  11097. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11098. return;
  11099. }
  11100. this.attached[type] = input;
  11101. input.camera = this.camera;
  11102. //for checkInputs, we are dynamically creating a function
  11103. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11104. if (input.checkInputs) {
  11105. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11106. }
  11107. if (this.attachedElement) {
  11108. input.attachControl(this.attachedElement);
  11109. }
  11110. };
  11111. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11112. for (var cam in this.attached) {
  11113. var input = this.attached[cam];
  11114. if (input == inputToRemove) {
  11115. input.detachControl(this.attachedElement);
  11116. delete this.attached[cam];
  11117. }
  11118. }
  11119. };
  11120. CameraInputsManager.prototype.removeByType = function (inputType) {
  11121. for (var cam in this.attached) {
  11122. var input = this.attached[cam];
  11123. if (input.getTypeName() == inputType) {
  11124. input.detachControl(this.attachedElement);
  11125. delete this.attached[cam];
  11126. }
  11127. }
  11128. };
  11129. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11130. var current = this.checkInputs;
  11131. return function () {
  11132. current();
  11133. fn();
  11134. };
  11135. };
  11136. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11137. this.attachedElement = element;
  11138. for (var cam in this.attached) {
  11139. var input = this.attached[cam];
  11140. this.attached[cam].attachControl(element, noPreventDefault);
  11141. }
  11142. };
  11143. CameraInputsManager.prototype.detachElement = function (element) {
  11144. for (var cam in this.attached) {
  11145. var input = this.attached[cam];
  11146. this.attached[cam].detachControl(element);
  11147. }
  11148. };
  11149. CameraInputsManager.prototype.rebuildInputCheck = function (element) {
  11150. this.checkInputs = function () { };
  11151. for (var cam in this.attached) {
  11152. var input = this.attached[cam];
  11153. if (input.checkInputs) {
  11154. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11155. }
  11156. }
  11157. };
  11158. CameraInputsManager.prototype.clear = function () {
  11159. if (this.attachedElement) {
  11160. this.detachElement(this.attachedElement);
  11161. }
  11162. this.attached = {};
  11163. this.attachedElement = null;
  11164. this.checkInputs = function () { };
  11165. };
  11166. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11167. var inputs = {};
  11168. for (var cam in this.attached) {
  11169. var input = this.attached[cam];
  11170. var res = BABYLON.SerializationHelper.Serialize(input, serializedCamera);
  11171. inputs[input.getTypeName()] = res;
  11172. }
  11173. serializedCamera.inputsmgr = inputs;
  11174. };
  11175. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11176. var parsedInputs = parsedCamera.inputsmgr;
  11177. if (parsedInputs) {
  11178. this.clear();
  11179. for (var n in parsedInputs) {
  11180. var construct = BABYLON.CameraInputTypes[n];
  11181. if (construct) {
  11182. var parsedinput = parsedInputs[n];
  11183. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11184. this.add(input);
  11185. }
  11186. }
  11187. }
  11188. else {
  11189. //2016-03-08 this part is for managing backward compatibility
  11190. for (var n in this.attached) {
  11191. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11192. if (construct) {
  11193. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11194. this.add(input);
  11195. }
  11196. }
  11197. }
  11198. };
  11199. return CameraInputsManager;
  11200. })();
  11201. BABYLON.CameraInputsManager = CameraInputsManager;
  11202. })(BABYLON || (BABYLON = {}));
  11203. var BABYLON;
  11204. (function (BABYLON) {
  11205. var FreeCameraMouseInput = (function () {
  11206. function FreeCameraMouseInput() {
  11207. this.angularSensibility = 2000.0;
  11208. }
  11209. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11210. var _this = this;
  11211. if (this._onMouseDown === undefined) {
  11212. var camera = this.camera;
  11213. var engine = this.camera.getEngine();
  11214. this._onMouseDown = function (evt) {
  11215. _this.previousPosition = {
  11216. x: evt.clientX,
  11217. y: evt.clientY
  11218. };
  11219. if (!noPreventDefault) {
  11220. evt.preventDefault();
  11221. }
  11222. };
  11223. this._onMouseUp = function (evt) {
  11224. _this.previousPosition = null;
  11225. if (!noPreventDefault) {
  11226. evt.preventDefault();
  11227. }
  11228. };
  11229. this._onMouseOut = function (evt) {
  11230. _this.previousPosition = null;
  11231. if (!noPreventDefault) {
  11232. evt.preventDefault();
  11233. }
  11234. };
  11235. this._onMouseMove = function (evt) {
  11236. if (!_this.previousPosition && !engine.isPointerLock) {
  11237. return;
  11238. }
  11239. var offsetX;
  11240. var offsetY;
  11241. if (!engine.isPointerLock) {
  11242. offsetX = evt.clientX - _this.previousPosition.x;
  11243. offsetY = evt.clientY - _this.previousPosition.y;
  11244. }
  11245. else {
  11246. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11247. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11248. }
  11249. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11250. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11251. _this.previousPosition = {
  11252. x: evt.clientX,
  11253. y: evt.clientY
  11254. };
  11255. if (!noPreventDefault) {
  11256. evt.preventDefault();
  11257. }
  11258. };
  11259. }
  11260. element.addEventListener("mousedown", this._onMouseDown, false);
  11261. element.addEventListener("mouseup", this._onMouseUp, false);
  11262. element.addEventListener("mouseout", this._onMouseOut, false);
  11263. element.addEventListener("mousemove", this._onMouseMove, false);
  11264. };
  11265. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11266. if (this._onMouseDown && element) {
  11267. this.previousPosition = null;
  11268. element.removeEventListener("mousedown", this._onMouseDown);
  11269. element.removeEventListener("mouseup", this._onMouseUp);
  11270. element.removeEventListener("mouseout", this._onMouseOut);
  11271. element.removeEventListener("mousemove", this._onMouseMove);
  11272. }
  11273. };
  11274. FreeCameraMouseInput.prototype.getTypeName = function () {
  11275. return "FreeCameraMouseInput";
  11276. };
  11277. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11278. return "mouse";
  11279. };
  11280. __decorate([
  11281. BABYLON.serialize()
  11282. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11283. return FreeCameraMouseInput;
  11284. })();
  11285. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11286. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11287. })(BABYLON || (BABYLON = {}));
  11288. var BABYLON;
  11289. (function (BABYLON) {
  11290. var FreeCameraKeyboardMoveInput = (function () {
  11291. function FreeCameraKeyboardMoveInput() {
  11292. this._keys = [];
  11293. this.keysUp = [38];
  11294. this.keysDown = [40];
  11295. this.keysLeft = [37];
  11296. this.keysRight = [39];
  11297. }
  11298. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11299. var _this = this;
  11300. if (this._onKeyDown === undefined) {
  11301. this._onKeyDown = function (evt) {
  11302. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11303. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11304. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11305. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11306. var index = _this._keys.indexOf(evt.keyCode);
  11307. if (index === -1) {
  11308. _this._keys.push(evt.keyCode);
  11309. }
  11310. if (!noPreventDefault) {
  11311. evt.preventDefault();
  11312. }
  11313. }
  11314. };
  11315. this._onKeyUp = function (evt) {
  11316. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11317. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11318. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11319. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11320. var index = _this._keys.indexOf(evt.keyCode);
  11321. if (index >= 0) {
  11322. _this._keys.splice(index, 1);
  11323. }
  11324. if (!noPreventDefault) {
  11325. evt.preventDefault();
  11326. }
  11327. }
  11328. };
  11329. BABYLON.Tools.RegisterTopRootEvents([
  11330. { name: "keydown", handler: this._onKeyDown },
  11331. { name: "keyup", handler: this._onKeyUp },
  11332. { name: "blur", handler: this._onLostFocus }
  11333. ]);
  11334. }
  11335. };
  11336. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11337. BABYLON.Tools.UnregisterTopRootEvents([
  11338. { name: "keydown", handler: this._onKeyDown },
  11339. { name: "keyup", handler: this._onKeyUp },
  11340. { name: "blur", handler: this._onLostFocus }
  11341. ]);
  11342. };
  11343. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11344. var camera = this.camera;
  11345. // Keyboard
  11346. for (var index = 0; index < this._keys.length; index++) {
  11347. var keyCode = this._keys[index];
  11348. var speed = camera._computeLocalCameraSpeed();
  11349. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11350. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11351. }
  11352. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11353. camera._localDirection.copyFromFloats(0, 0, speed);
  11354. }
  11355. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11356. camera._localDirection.copyFromFloats(speed, 0, 0);
  11357. }
  11358. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11359. camera._localDirection.copyFromFloats(0, 0, -speed);
  11360. }
  11361. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11362. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11363. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11364. }
  11365. };
  11366. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11367. return "FreeCameraKeyboardMoveInput";
  11368. };
  11369. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11370. this._keys = [];
  11371. };
  11372. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11373. return "keyboard";
  11374. };
  11375. __decorate([
  11376. BABYLON.serialize()
  11377. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11378. __decorate([
  11379. BABYLON.serialize()
  11380. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11381. __decorate([
  11382. BABYLON.serialize()
  11383. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11384. __decorate([
  11385. BABYLON.serialize()
  11386. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11387. return FreeCameraKeyboardMoveInput;
  11388. })();
  11389. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11390. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11391. })(BABYLON || (BABYLON = {}));
  11392. var BABYLON;
  11393. (function (BABYLON) {
  11394. var FreeCameraTouchInput = (function () {
  11395. function FreeCameraTouchInput() {
  11396. this._offsetX = null;
  11397. this._offsetY = null;
  11398. this._pointerCount = 0;
  11399. this._pointerPressed = [];
  11400. this.touchAngularSensibility = 200000.0;
  11401. this.touchMoveSensibility = 250.0;
  11402. }
  11403. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11404. var _this = this;
  11405. var previousPosition;
  11406. if (this._onPointerDown === undefined) {
  11407. this._onLostFocus = function (evt) {
  11408. _this._offsetX = null;
  11409. _this._offsetY = null;
  11410. };
  11411. this._onPointerDown = function (evt) {
  11412. if (evt.pointerType === "mouse") {
  11413. return;
  11414. }
  11415. if (!noPreventDefault) {
  11416. evt.preventDefault();
  11417. }
  11418. _this._pointerPressed.push(evt.pointerId);
  11419. if (_this._pointerPressed.length !== 1) {
  11420. return;
  11421. }
  11422. previousPosition = {
  11423. x: evt.clientX,
  11424. y: evt.clientY
  11425. };
  11426. };
  11427. this._onPointerUp = function (evt) {
  11428. if (evt.pointerType === "mouse") {
  11429. return;
  11430. }
  11431. if (!noPreventDefault) {
  11432. evt.preventDefault();
  11433. }
  11434. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11435. if (index === -1) {
  11436. return;
  11437. }
  11438. _this._pointerPressed.splice(index, 1);
  11439. if (index != 0) {
  11440. return;
  11441. }
  11442. previousPosition = null;
  11443. _this._offsetX = null;
  11444. _this._offsetY = null;
  11445. };
  11446. this._onPointerMove = function (evt) {
  11447. if (evt.pointerType === "mouse") {
  11448. return;
  11449. }
  11450. if (!noPreventDefault) {
  11451. evt.preventDefault();
  11452. }
  11453. if (!previousPosition) {
  11454. return;
  11455. }
  11456. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11457. if (index != 0) {
  11458. return;
  11459. }
  11460. _this._offsetX = evt.clientX - previousPosition.x;
  11461. _this._offsetY = -(evt.clientY - previousPosition.y);
  11462. };
  11463. }
  11464. element.addEventListener("blur", this._onLostFocus);
  11465. element.addEventListener("pointerdown", this._onPointerDown);
  11466. element.addEventListener("pointerup", this._onPointerUp);
  11467. element.addEventListener("pointerout", this._onPointerUp);
  11468. element.addEventListener("pointermove", this._onPointerMove);
  11469. };
  11470. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11471. element.removeEventListener("blur", this._onLostFocus);
  11472. element.removeEventListener("pointerdown", this._onPointerDown);
  11473. element.removeEventListener("pointerup", this._onPointerUp);
  11474. element.removeEventListener("pointerout", this._onPointerUp);
  11475. element.removeEventListener("pointermove", this._onPointerMove);
  11476. };
  11477. FreeCameraTouchInput.prototype.checkInputs = function () {
  11478. if (this._offsetX) {
  11479. var camera = this.camera;
  11480. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11481. if (this._pointerPressed.length > 1) {
  11482. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11483. }
  11484. else {
  11485. var speed = camera._computeLocalCameraSpeed();
  11486. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11487. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11488. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11489. }
  11490. }
  11491. };
  11492. FreeCameraTouchInput.prototype.getTypeName = function () {
  11493. return "FreeCameraTouchInput";
  11494. };
  11495. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11496. return "touch";
  11497. };
  11498. __decorate([
  11499. BABYLON.serialize()
  11500. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11501. __decorate([
  11502. BABYLON.serialize()
  11503. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11504. return FreeCameraTouchInput;
  11505. })();
  11506. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11507. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11508. })(BABYLON || (BABYLON = {}));
  11509. var BABYLON;
  11510. (function (BABYLON) {
  11511. var FreeCameraDeviceOrientationInput = (function () {
  11512. function FreeCameraDeviceOrientationInput() {
  11513. this._offsetX = null;
  11514. this._offsetY = null;
  11515. this._orientationGamma = 0;
  11516. this._orientationBeta = 0;
  11517. this._initialOrientationGamma = 0;
  11518. this._initialOrientationBeta = 0;
  11519. this.angularSensibility = 10000.0;
  11520. this.moveSensibility = 50.0;
  11521. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  11522. this._orientationChanged = this.orientationChanged.bind(this);
  11523. }
  11524. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11525. window.addEventListener("resize", this._resetOrientationGamma, false);
  11526. window.addEventListener("deviceorientation", this._orientationChanged);
  11527. };
  11528. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  11529. this._initialOrientationGamma = null;
  11530. };
  11531. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  11532. if (!this._initialOrientationGamma) {
  11533. this._initialOrientationGamma = evt.gamma;
  11534. this._initialOrientationBeta = evt.beta;
  11535. }
  11536. this._orientationGamma = evt.gamma;
  11537. this._orientationBeta = evt.beta;
  11538. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  11539. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  11540. };
  11541. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  11542. window.removeEventListener("resize", this._resetOrientationGamma);
  11543. window.removeEventListener("deviceorientation", this._orientationChanged);
  11544. this._orientationGamma = 0;
  11545. this._orientationBeta = 0;
  11546. this._initialOrientationGamma = 0;
  11547. this._initialOrientationBeta = 0;
  11548. };
  11549. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  11550. if (!this._offsetX) {
  11551. return;
  11552. }
  11553. var camera = this.camera;
  11554. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11555. var speed = camera._computeLocalCameraSpeed();
  11556. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11557. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11558. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11559. };
  11560. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  11561. return "FreeCameraDeviceOrientationInput";
  11562. };
  11563. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  11564. return "deviceOrientation";
  11565. };
  11566. __decorate([
  11567. BABYLON.serialize()
  11568. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  11569. __decorate([
  11570. BABYLON.serialize()
  11571. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  11572. return FreeCameraDeviceOrientationInput;
  11573. })();
  11574. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  11575. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  11576. })(BABYLON || (BABYLON = {}));
  11577. var BABYLON;
  11578. (function (BABYLON) {
  11579. var FreeCameraVRDeviceOrientationInput = (function () {
  11580. function FreeCameraVRDeviceOrientationInput() {
  11581. this.alphaCorrection = 1;
  11582. this.betaCorrection = 1;
  11583. this.gammaCorrection = 1;
  11584. this._alpha = 0;
  11585. this._beta = 0;
  11586. this._gamma = 0;
  11587. this._dirty = false;
  11588. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  11589. }
  11590. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11591. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  11592. };
  11593. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  11594. var camera = this.camera;
  11595. this._alpha = +evt.alpha | 0;
  11596. this._beta = +evt.beta | 0;
  11597. this._gamma = +evt.gamma | 0;
  11598. this._dirty = true;
  11599. };
  11600. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  11601. if (this._dirty) {
  11602. this._dirty = false;
  11603. var rotationX = this._gamma;
  11604. if (rotationX < 0) {
  11605. rotationX = 90 + rotationX;
  11606. }
  11607. else {
  11608. // Incline it in the correct angle.
  11609. rotationX = 270 - rotationX;
  11610. }
  11611. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  11612. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  11613. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  11614. }
  11615. };
  11616. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  11617. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  11618. };
  11619. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  11620. return "FreeCameraVRDeviceOrientationInput";
  11621. };
  11622. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  11623. return "VRDeviceOrientation";
  11624. };
  11625. return FreeCameraVRDeviceOrientationInput;
  11626. })();
  11627. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  11628. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  11629. })(BABYLON || (BABYLON = {}));
  11630. var BABYLON;
  11631. (function (BABYLON) {
  11632. var FreeCameraGamepadInput = (function () {
  11633. function FreeCameraGamepadInput() {
  11634. this.gamepadAngularSensibility = 200;
  11635. this.gamepadMoveSensibility = 40;
  11636. }
  11637. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  11638. var _this = this;
  11639. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11640. };
  11641. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  11642. if (this._gamepads) {
  11643. this._gamepads.dispose();
  11644. }
  11645. this.gamepad = null;
  11646. };
  11647. FreeCameraGamepadInput.prototype.checkInputs = function () {
  11648. if (this.gamepad) {
  11649. var camera = this.camera;
  11650. var LSValues = this.gamepad.leftStick;
  11651. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  11652. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  11653. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11654. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11655. var RSValues = this.gamepad.rightStick;
  11656. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  11657. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  11658. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11659. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11660. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  11661. var speed = camera._computeLocalCameraSpeed() * 50.0;
  11662. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11663. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  11664. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11665. }
  11666. };
  11667. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  11668. // Only the first gamepad can control the camera
  11669. if (gamepad.index === 0) {
  11670. this.gamepad = gamepad;
  11671. }
  11672. };
  11673. FreeCameraGamepadInput.prototype.getTypeName = function () {
  11674. return "FreeCameraGamepadInput";
  11675. };
  11676. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  11677. return "gamepad";
  11678. };
  11679. __decorate([
  11680. BABYLON.serialize()
  11681. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  11682. __decorate([
  11683. BABYLON.serialize()
  11684. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  11685. return FreeCameraGamepadInput;
  11686. })();
  11687. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  11688. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  11689. })(BABYLON || (BABYLON = {}));
  11690. var BABYLON;
  11691. (function (BABYLON) {
  11692. var FreeCameraVirtualJoystickInput = (function () {
  11693. function FreeCameraVirtualJoystickInput() {
  11694. }
  11695. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  11696. return this._leftjoystick;
  11697. };
  11698. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  11699. return this._rightjoystick;
  11700. };
  11701. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  11702. if (this._leftjoystick) {
  11703. var camera = this.camera;
  11704. var speed = camera._computeLocalCameraSpeed() * 50;
  11705. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  11706. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  11707. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  11708. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  11709. if (!this._leftjoystick.pressed) {
  11710. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  11711. }
  11712. if (!this._rightjoystick.pressed) {
  11713. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  11714. }
  11715. }
  11716. };
  11717. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  11718. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  11719. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  11720. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  11721. this._leftjoystick.setJoystickSensibility(0.15);
  11722. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  11723. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  11724. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  11725. this._rightjoystick.reverseUpDown = true;
  11726. this._rightjoystick.setJoystickSensibility(0.05);
  11727. this._rightjoystick.setJoystickColor("yellow");
  11728. };
  11729. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  11730. this._leftjoystick.releaseCanvas();
  11731. this._rightjoystick.releaseCanvas();
  11732. };
  11733. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  11734. return "FreeCameraVirtualJoystickInput";
  11735. };
  11736. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  11737. return "virtualJoystick";
  11738. };
  11739. return FreeCameraVirtualJoystickInput;
  11740. })();
  11741. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  11742. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  11743. })(BABYLON || (BABYLON = {}));
  11744. var BABYLON;
  11745. (function (BABYLON) {
  11746. var ArcRotateCameraKeyboardMoveInput = (function () {
  11747. function ArcRotateCameraKeyboardMoveInput() {
  11748. this._keys = [];
  11749. this.keysUp = [38];
  11750. this.keysDown = [40];
  11751. this.keysLeft = [37];
  11752. this.keysRight = [39];
  11753. }
  11754. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11755. var _this = this;
  11756. this._onKeyDown = function (evt) {
  11757. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11758. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11759. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11760. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11761. var index = _this._keys.indexOf(evt.keyCode);
  11762. if (index === -1) {
  11763. _this._keys.push(evt.keyCode);
  11764. }
  11765. if (evt.preventDefault) {
  11766. if (!noPreventDefault) {
  11767. evt.preventDefault();
  11768. }
  11769. }
  11770. }
  11771. };
  11772. this._onKeyUp = function (evt) {
  11773. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11774. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11775. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11776. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11777. var index = _this._keys.indexOf(evt.keyCode);
  11778. if (index >= 0) {
  11779. _this._keys.splice(index, 1);
  11780. }
  11781. if (evt.preventDefault) {
  11782. if (!noPreventDefault) {
  11783. evt.preventDefault();
  11784. }
  11785. }
  11786. }
  11787. };
  11788. this._onLostFocus = function () {
  11789. _this._keys = [];
  11790. };
  11791. BABYLON.Tools.RegisterTopRootEvents([
  11792. { name: "keydown", handler: this._onKeyDown },
  11793. { name: "keyup", handler: this._onKeyUp },
  11794. { name: "blur", handler: this._onLostFocus }
  11795. ]);
  11796. };
  11797. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11798. BABYLON.Tools.UnregisterTopRootEvents([
  11799. { name: "keydown", handler: this._onKeyDown },
  11800. { name: "keyup", handler: this._onKeyUp },
  11801. { name: "blur", handler: this._onLostFocus }
  11802. ]);
  11803. };
  11804. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11805. var camera = this.camera;
  11806. for (var index = 0; index < this._keys.length; index++) {
  11807. var keyCode = this._keys[index];
  11808. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11809. camera.inertialAlphaOffset -= 0.01;
  11810. }
  11811. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11812. camera.inertialBetaOffset -= 0.01;
  11813. }
  11814. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11815. camera.inertialAlphaOffset += 0.01;
  11816. }
  11817. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11818. camera.inertialBetaOffset += 0.01;
  11819. }
  11820. }
  11821. };
  11822. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11823. return "ArcRotateCameraKeyboardMoveInput";
  11824. };
  11825. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11826. return "keyboard";
  11827. };
  11828. __decorate([
  11829. BABYLON.serialize()
  11830. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11831. __decorate([
  11832. BABYLON.serialize()
  11833. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11834. __decorate([
  11835. BABYLON.serialize()
  11836. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11837. __decorate([
  11838. BABYLON.serialize()
  11839. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11840. return ArcRotateCameraKeyboardMoveInput;
  11841. })();
  11842. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  11843. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  11844. })(BABYLON || (BABYLON = {}));
  11845. var BABYLON;
  11846. (function (BABYLON) {
  11847. var ArcRotateCameraMouseWheelInput = (function () {
  11848. function ArcRotateCameraMouseWheelInput() {
  11849. this.wheelPrecision = 3.0;
  11850. }
  11851. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  11852. var _this = this;
  11853. this._wheel = function (event) {
  11854. var delta = 0;
  11855. if (event.wheelDelta) {
  11856. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11857. }
  11858. else if (event.detail) {
  11859. delta = -event.detail / _this.wheelPrecision;
  11860. }
  11861. if (delta)
  11862. _this.camera.inertialRadiusOffset += delta;
  11863. if (event.preventDefault) {
  11864. if (!_this.camera._noPreventDefault) {
  11865. event.preventDefault();
  11866. }
  11867. }
  11868. };
  11869. element.addEventListener('mousewheel', this._wheel, false);
  11870. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11871. };
  11872. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  11873. if (this._wheel && element) {
  11874. element.removeEventListener('mousewheel', this._wheel);
  11875. element.removeEventListener('DOMMouseScroll', this._wheel);
  11876. }
  11877. };
  11878. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  11879. return "ArcRotateCameraMouseWheelInput";
  11880. };
  11881. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  11882. return "mousewheel";
  11883. };
  11884. __decorate([
  11885. BABYLON.serialize()
  11886. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  11887. return ArcRotateCameraMouseWheelInput;
  11888. })();
  11889. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  11890. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  11891. })(BABYLON || (BABYLON = {}));
  11892. var BABYLON;
  11893. (function (BABYLON) {
  11894. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11895. var ArcRotateCameraPointersInput = (function () {
  11896. function ArcRotateCameraPointersInput() {
  11897. this._isRightClick = false;
  11898. this._isCtrlPushed = false;
  11899. this.pinchInwards = true;
  11900. this.angularSensibilityX = 1000.0;
  11901. this.angularSensibilityY = 1000.0;
  11902. this.pinchPrecision = 6.0;
  11903. this.panningSensibility = 50.0;
  11904. }
  11905. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  11906. var _this = this;
  11907. var engine = this.camera.getEngine();
  11908. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11909. var pointers = new BABYLON.SmartCollection();
  11910. var previousPinchDistance = 0;
  11911. if (!this.camera._useCtrlForPanning) {
  11912. element.addEventListener("contextmenu", this._onContextMenu, false);
  11913. }
  11914. this._onLostFocus = function () {
  11915. //this._keys = [];
  11916. pointers.empty();
  11917. previousPinchDistance = 0;
  11918. cacheSoloPointer = null;
  11919. };
  11920. this._onKeyDown = function (evt) {
  11921. _this._isCtrlPushed = evt.ctrlKey;
  11922. };
  11923. this._onKeyUp = function (evt) {
  11924. _this._isCtrlPushed = evt.ctrlKey;
  11925. };
  11926. this._onPointerDown = function (evt) {
  11927. // Manage panning with right click
  11928. _this._isRightClick = evt.button === 2;
  11929. // manage pointers
  11930. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11931. cacheSoloPointer = pointers.item(evt.pointerId);
  11932. if (!noPreventDefault) {
  11933. evt.preventDefault();
  11934. }
  11935. };
  11936. this._onPointerUp = function (evt) {
  11937. cacheSoloPointer = null;
  11938. previousPinchDistance = 0;
  11939. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11940. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11941. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11942. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11943. pointers.empty();
  11944. if (!noPreventDefault) {
  11945. evt.preventDefault();
  11946. }
  11947. };
  11948. this._onContextMenu = function (evt) {
  11949. evt.preventDefault();
  11950. };
  11951. this._onPointerMove = function (evt) {
  11952. if (!noPreventDefault) {
  11953. evt.preventDefault();
  11954. }
  11955. switch (pointers.count) {
  11956. case 1:
  11957. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) || (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  11958. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11959. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11960. }
  11961. else {
  11962. var offsetX = evt.clientX - cacheSoloPointer.x;
  11963. var offsetY = evt.clientY - cacheSoloPointer.y;
  11964. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11965. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11966. }
  11967. cacheSoloPointer.x = evt.clientX;
  11968. cacheSoloPointer.y = evt.clientY;
  11969. break;
  11970. case 2:
  11971. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11972. pointers.item(evt.pointerId).x = evt.clientX;
  11973. pointers.item(evt.pointerId).y = evt.clientY;
  11974. var direction = _this.pinchInwards ? 1 : -1;
  11975. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11976. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11977. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11978. if (previousPinchDistance === 0) {
  11979. previousPinchDistance = pinchSquaredDistance;
  11980. return;
  11981. }
  11982. if (pinchSquaredDistance !== previousPinchDistance) {
  11983. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11984. previousPinchDistance = pinchSquaredDistance;
  11985. }
  11986. break;
  11987. default:
  11988. if (pointers.item(evt.pointerId)) {
  11989. pointers.item(evt.pointerId).x = evt.clientX;
  11990. pointers.item(evt.pointerId).y = evt.clientY;
  11991. }
  11992. }
  11993. };
  11994. this._onMouseMove = function (evt) {
  11995. if (!engine.isPointerLock) {
  11996. return;
  11997. }
  11998. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11999. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12000. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12001. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12002. if (!noPreventDefault) {
  12003. evt.preventDefault();
  12004. }
  12005. };
  12006. this._onGestureStart = function (e) {
  12007. if (window.MSGesture === undefined) {
  12008. return;
  12009. }
  12010. if (!_this._MSGestureHandler) {
  12011. _this._MSGestureHandler = new MSGesture();
  12012. _this._MSGestureHandler.target = element;
  12013. }
  12014. _this._MSGestureHandler.addPointer(e.pointerId);
  12015. };
  12016. this._onGesture = function (e) {
  12017. _this.camera.radius *= e.scale;
  12018. if (e.preventDefault) {
  12019. if (!noPreventDefault) {
  12020. e.stopPropagation();
  12021. e.preventDefault();
  12022. }
  12023. }
  12024. };
  12025. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12026. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12027. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12028. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12029. element.addEventListener("mousemove", this._onMouseMove, false);
  12030. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12031. element.addEventListener("MSGestureChange", this._onGesture, false);
  12032. BABYLON.Tools.RegisterTopRootEvents([
  12033. { name: "blur", handler: this._onLostFocus }
  12034. ]);
  12035. };
  12036. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12037. this._MSGestureHandler = null;
  12038. if (element && this._onPointerDown) {
  12039. element.removeEventListener("contextmenu", this._onContextMenu);
  12040. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12041. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12042. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12043. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12044. element.removeEventListener("mousemove", this._onMouseMove);
  12045. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12046. element.removeEventListener("MSGestureChange", this._onGesture);
  12047. }
  12048. BABYLON.Tools.UnregisterTopRootEvents([
  12049. { name: "blur", handler: this._onLostFocus }
  12050. ]);
  12051. };
  12052. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12053. return "ArcRotateCameraPointersInput";
  12054. };
  12055. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12056. return "pointers";
  12057. };
  12058. __decorate([
  12059. BABYLON.serialize()
  12060. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12061. __decorate([
  12062. BABYLON.serialize()
  12063. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12064. __decorate([
  12065. BABYLON.serialize()
  12066. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12067. __decorate([
  12068. BABYLON.serialize()
  12069. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12070. return ArcRotateCameraPointersInput;
  12071. })();
  12072. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12073. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12074. })(BABYLON || (BABYLON = {}));
  12075. var BABYLON;
  12076. (function (BABYLON) {
  12077. var ArcRotateCameraGamepadInput = (function () {
  12078. function ArcRotateCameraGamepadInput() {
  12079. this.gamepadRotationSensibility = 80;
  12080. this.gamepadMoveSensibility = 40;
  12081. }
  12082. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12083. var _this = this;
  12084. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12085. };
  12086. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12087. if (this._gamepads) {
  12088. this._gamepads.dispose();
  12089. }
  12090. this.gamepad = null;
  12091. };
  12092. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12093. if (this.gamepad) {
  12094. var camera = this.camera;
  12095. var RSValues = this.gamepad.rightStick;
  12096. if (RSValues.x != 0) {
  12097. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12098. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12099. camera.inertialAlphaOffset += normalizedRX;
  12100. }
  12101. }
  12102. if (RSValues.y != 0) {
  12103. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12104. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12105. camera.inertialBetaOffset += normalizedRY;
  12106. }
  12107. }
  12108. var LSValues = this.gamepad.leftStick;
  12109. if (LSValues.y != 0) {
  12110. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12111. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12112. this.camera.inertialRadiusOffset -= normalizedLY;
  12113. }
  12114. }
  12115. }
  12116. };
  12117. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12118. // Only the first gamepad can control the camera
  12119. if (gamepad.index === 0) {
  12120. this.gamepad = gamepad;
  12121. }
  12122. };
  12123. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12124. return "ArcRotateCameraGamepadInput";
  12125. };
  12126. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12127. return "gamepad";
  12128. };
  12129. __decorate([
  12130. BABYLON.serialize()
  12131. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12132. __decorate([
  12133. BABYLON.serialize()
  12134. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12135. return ArcRotateCameraGamepadInput;
  12136. })();
  12137. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12138. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12139. })(BABYLON || (BABYLON = {}));
  12140. var BABYLON;
  12141. (function (BABYLON) {
  12142. var TargetCamera = (function (_super) {
  12143. __extends(TargetCamera, _super);
  12144. function TargetCamera(name, position, scene) {
  12145. _super.call(this, name, position, scene);
  12146. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12147. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12148. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12149. this.speed = 2.0;
  12150. this.noRotationConstraint = false;
  12151. this.lockedTarget = null;
  12152. this._currentTarget = BABYLON.Vector3.Zero();
  12153. this._viewMatrix = BABYLON.Matrix.Zero();
  12154. this._camMatrix = BABYLON.Matrix.Zero();
  12155. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12156. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12157. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12158. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12159. this._lookAtTemp = BABYLON.Matrix.Zero();
  12160. this._tempMatrix = BABYLON.Matrix.Zero();
  12161. }
  12162. TargetCamera.prototype.getFrontPosition = function (distance) {
  12163. var direction = this.getTarget().subtract(this.position);
  12164. direction.normalize();
  12165. direction.scaleInPlace(distance);
  12166. return this.globalPosition.add(direction);
  12167. };
  12168. TargetCamera.prototype._getLockedTargetPosition = function () {
  12169. if (!this.lockedTarget) {
  12170. return null;
  12171. }
  12172. return this.lockedTarget.position || this.lockedTarget;
  12173. };
  12174. // Cache
  12175. TargetCamera.prototype._initCache = function () {
  12176. _super.prototype._initCache.call(this);
  12177. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12178. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12179. };
  12180. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12181. if (!ignoreParentClass) {
  12182. _super.prototype._updateCache.call(this);
  12183. }
  12184. var lockedTargetPosition = this._getLockedTargetPosition();
  12185. if (!lockedTargetPosition) {
  12186. this._cache.lockedTarget = null;
  12187. }
  12188. else {
  12189. if (!this._cache.lockedTarget) {
  12190. this._cache.lockedTarget = lockedTargetPosition.clone();
  12191. }
  12192. else {
  12193. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12194. }
  12195. }
  12196. this._cache.rotation.copyFrom(this.rotation);
  12197. };
  12198. // Synchronized
  12199. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12200. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12201. return false;
  12202. }
  12203. var lockedTargetPosition = this._getLockedTargetPosition();
  12204. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12205. && this._cache.rotation.equals(this.rotation);
  12206. };
  12207. // Methods
  12208. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12209. var engine = this.getEngine();
  12210. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12211. };
  12212. // Target
  12213. TargetCamera.prototype.setTarget = function (target) {
  12214. this.upVector.normalize();
  12215. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12216. this._camMatrix.invert();
  12217. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12218. var vDir = target.subtract(this.position);
  12219. if (vDir.x >= 0.0) {
  12220. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12221. }
  12222. else {
  12223. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12224. }
  12225. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12226. if (isNaN(this.rotation.x)) {
  12227. this.rotation.x = 0;
  12228. }
  12229. if (isNaN(this.rotation.y)) {
  12230. this.rotation.y = 0;
  12231. }
  12232. if (isNaN(this.rotation.z)) {
  12233. this.rotation.z = 0;
  12234. }
  12235. };
  12236. TargetCamera.prototype.getTarget = function () {
  12237. return this._currentTarget;
  12238. };
  12239. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12240. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12241. };
  12242. TargetCamera.prototype._updatePosition = function () {
  12243. this.position.addInPlace(this.cameraDirection);
  12244. };
  12245. TargetCamera.prototype._checkInputs = function () {
  12246. var needToMove = this._decideIfNeedsToMove();
  12247. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12248. // Move
  12249. if (needToMove) {
  12250. this._updatePosition();
  12251. }
  12252. // Rotate
  12253. if (needToRotate) {
  12254. this.rotation.x += this.cameraRotation.x;
  12255. this.rotation.y += this.cameraRotation.y;
  12256. if (!this.noRotationConstraint) {
  12257. var limit = (Math.PI / 2) * 0.95;
  12258. if (this.rotation.x > limit)
  12259. this.rotation.x = limit;
  12260. if (this.rotation.x < -limit)
  12261. this.rotation.x = -limit;
  12262. }
  12263. }
  12264. // Inertia
  12265. if (needToMove) {
  12266. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12267. this.cameraDirection.x = 0;
  12268. }
  12269. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12270. this.cameraDirection.y = 0;
  12271. }
  12272. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12273. this.cameraDirection.z = 0;
  12274. }
  12275. this.cameraDirection.scaleInPlace(this.inertia);
  12276. }
  12277. if (needToRotate) {
  12278. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12279. this.cameraRotation.x = 0;
  12280. }
  12281. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12282. this.cameraRotation.y = 0;
  12283. }
  12284. this.cameraRotation.scaleInPlace(this.inertia);
  12285. }
  12286. _super.prototype._checkInputs.call(this);
  12287. };
  12288. TargetCamera.prototype._getViewMatrix = function () {
  12289. if (!this.lockedTarget) {
  12290. // Compute
  12291. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12292. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12293. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12294. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12295. this._lookAtTemp.invert();
  12296. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12297. }
  12298. else {
  12299. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12300. }
  12301. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12302. // Computing target and final matrix
  12303. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12304. }
  12305. else {
  12306. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12307. }
  12308. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12309. return this._viewMatrix;
  12310. };
  12311. TargetCamera.prototype._getVRViewMatrix = function () {
  12312. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12313. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12314. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12315. // Computing target and final matrix
  12316. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12317. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12318. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12319. return this._viewMatrix;
  12320. };
  12321. /**
  12322. * @override
  12323. * Override Camera.createRigCamera
  12324. */
  12325. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12326. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12327. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12328. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12329. rigCamera._cameraRigParams = {};
  12330. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12331. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12332. }
  12333. return rigCamera;
  12334. }
  12335. return null;
  12336. };
  12337. /**
  12338. * @override
  12339. * Override Camera._updateRigCameras
  12340. */
  12341. TargetCamera.prototype._updateRigCameras = function () {
  12342. switch (this.cameraRigMode) {
  12343. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12344. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12345. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12346. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12347. case BABYLON.Camera.RIG_MODE_VR:
  12348. var camLeft = this._rigCameras[0];
  12349. var camRight = this._rigCameras[1];
  12350. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12351. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12352. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12353. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12354. camLeft.position.copyFrom(this.position);
  12355. camRight.position.copyFrom(this.position);
  12356. }
  12357. else {
  12358. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12359. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12360. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12361. camLeft.setTarget(this.getTarget());
  12362. camRight.setTarget(this.getTarget());
  12363. }
  12364. break;
  12365. }
  12366. _super.prototype._updateRigCameras.call(this);
  12367. };
  12368. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12369. if (!this._rigCamTransformMatrix) {
  12370. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12371. }
  12372. var target = this.getTarget();
  12373. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12374. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12375. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12376. };
  12377. TargetCamera.prototype.getTypeName = function () {
  12378. return "TargetCamera";
  12379. };
  12380. __decorate([
  12381. BABYLON.serializeAsVector3()
  12382. ], TargetCamera.prototype, "rotation", void 0);
  12383. __decorate([
  12384. BABYLON.serialize()
  12385. ], TargetCamera.prototype, "speed", void 0);
  12386. __decorate([
  12387. BABYLON.serializeAsMeshReference("lockedTargetId")
  12388. ], TargetCamera.prototype, "lockedTarget", void 0);
  12389. return TargetCamera;
  12390. })(BABYLON.Camera);
  12391. BABYLON.TargetCamera = TargetCamera;
  12392. })(BABYLON || (BABYLON = {}));
  12393. var BABYLON;
  12394. (function (BABYLON) {
  12395. var FreeCamera = (function (_super) {
  12396. __extends(FreeCamera, _super);
  12397. function FreeCamera(name, position, scene) {
  12398. var _this = this;
  12399. _super.call(this, name, position, scene);
  12400. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12401. this.checkCollisions = false;
  12402. this.applyGravity = false;
  12403. this._collider = new BABYLON.Collider();
  12404. this._needMoveForGravity = false;
  12405. this._oldPosition = BABYLON.Vector3.Zero();
  12406. this._diffPosition = BABYLON.Vector3.Zero();
  12407. this._newPosition = BABYLON.Vector3.Zero();
  12408. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12409. if (collidedMesh === void 0) { collidedMesh = null; }
  12410. //TODO move this to the collision coordinator!
  12411. if (_this.getScene().workerCollisions)
  12412. newPosition.multiplyInPlace(_this._collider.radius);
  12413. var updatePosition = function (newPos) {
  12414. _this._newPosition.copyFrom(newPos);
  12415. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12416. var oldPosition = _this.position.clone();
  12417. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12418. _this.position.addInPlace(_this._diffPosition);
  12419. if (_this.onCollide && collidedMesh) {
  12420. _this.onCollide(collidedMesh);
  12421. }
  12422. }
  12423. };
  12424. updatePosition(newPosition);
  12425. };
  12426. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12427. this.inputs.addKeyboard().addMouse();
  12428. }
  12429. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  12430. //-- begin properties for backward compatibility for inputs
  12431. get: function () {
  12432. var mouse = this.inputs.attached["mouse"];
  12433. if (mouse)
  12434. return mouse.angularSensibility;
  12435. },
  12436. set: function (value) {
  12437. var mouse = this.inputs.attached["mouse"];
  12438. if (mouse)
  12439. mouse.angularSensibility = value;
  12440. },
  12441. enumerable: true,
  12442. configurable: true
  12443. });
  12444. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  12445. get: function () {
  12446. var keyboard = this.inputs.attached["keyboard"];
  12447. if (keyboard)
  12448. return keyboard.keysUp;
  12449. },
  12450. set: function (value) {
  12451. var keyboard = this.inputs.attached["keyboard"];
  12452. if (keyboard)
  12453. keyboard.keysUp = value;
  12454. },
  12455. enumerable: true,
  12456. configurable: true
  12457. });
  12458. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  12459. get: function () {
  12460. var keyboard = this.inputs.attached["keyboard"];
  12461. if (keyboard)
  12462. return keyboard.keysDown;
  12463. },
  12464. set: function (value) {
  12465. var keyboard = this.inputs.attached["keyboard"];
  12466. if (keyboard)
  12467. keyboard.keysDown = value;
  12468. },
  12469. enumerable: true,
  12470. configurable: true
  12471. });
  12472. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  12473. get: function () {
  12474. var keyboard = this.inputs.attached["keyboard"];
  12475. if (keyboard)
  12476. return keyboard.keysLeft;
  12477. },
  12478. set: function (value) {
  12479. var keyboard = this.inputs.attached["keyboard"];
  12480. if (keyboard)
  12481. keyboard.keysLeft = value;
  12482. },
  12483. enumerable: true,
  12484. configurable: true
  12485. });
  12486. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  12487. get: function () {
  12488. var keyboard = this.inputs.attached["keyboard"];
  12489. if (keyboard)
  12490. return keyboard.keysRight;
  12491. },
  12492. set: function (value) {
  12493. var keyboard = this.inputs.attached["keyboard"];
  12494. if (keyboard)
  12495. keyboard.keysRight = value;
  12496. },
  12497. enumerable: true,
  12498. configurable: true
  12499. });
  12500. // Controls
  12501. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  12502. if (this._attachedElement) {
  12503. return;
  12504. }
  12505. this._noPreventDefault = noPreventDefault;
  12506. this._attachedElement = element;
  12507. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12508. this.inputs.attachElement(element, noPreventDefault);
  12509. };
  12510. FreeCamera.prototype.detachControl = function (element) {
  12511. if (this._attachedElement !== element) {
  12512. return;
  12513. }
  12514. this.inputs.detachElement(this._attachedElement);
  12515. this._attachedElement = null;
  12516. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12517. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12518. };
  12519. FreeCamera.prototype._collideWithWorld = function (velocity) {
  12520. var globalPosition;
  12521. if (this.parent) {
  12522. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  12523. }
  12524. else {
  12525. globalPosition = this.position;
  12526. }
  12527. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  12528. this._collider.radius = this.ellipsoid;
  12529. //no need for clone, as long as gravity is not on.
  12530. var actualVelocity = velocity;
  12531. //add gravity to the velocity to prevent the dual-collision checking
  12532. if (this.applyGravity) {
  12533. //this prevents mending with cameraDirection, a global variable of the free camera class.
  12534. actualVelocity = velocity.add(this.getScene().gravity);
  12535. }
  12536. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12537. };
  12538. FreeCamera.prototype._checkInputs = function () {
  12539. if (!this._localDirection) {
  12540. this._localDirection = BABYLON.Vector3.Zero();
  12541. this._transformedDirection = BABYLON.Vector3.Zero();
  12542. }
  12543. this.inputs.checkInputs();
  12544. _super.prototype._checkInputs.call(this);
  12545. };
  12546. FreeCamera.prototype._decideIfNeedsToMove = function () {
  12547. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12548. };
  12549. FreeCamera.prototype._updatePosition = function () {
  12550. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  12551. this._collideWithWorld(this.cameraDirection);
  12552. }
  12553. else {
  12554. this.position.addInPlace(this.cameraDirection);
  12555. }
  12556. };
  12557. FreeCamera.prototype.dispose = function () {
  12558. this.inputs.clear();
  12559. _super.prototype.dispose.call(this);
  12560. };
  12561. FreeCamera.prototype.getTypeName = function () {
  12562. return "FreeCamera";
  12563. };
  12564. __decorate([
  12565. BABYLON.serializeAsVector3()
  12566. ], FreeCamera.prototype, "ellipsoid", void 0);
  12567. __decorate([
  12568. BABYLON.serialize()
  12569. ], FreeCamera.prototype, "checkCollisions", void 0);
  12570. __decorate([
  12571. BABYLON.serialize()
  12572. ], FreeCamera.prototype, "applyGravity", void 0);
  12573. return FreeCamera;
  12574. })(BABYLON.TargetCamera);
  12575. BABYLON.FreeCamera = FreeCamera;
  12576. })(BABYLON || (BABYLON = {}));
  12577. var BABYLON;
  12578. (function (BABYLON) {
  12579. var FreeCameraInputsManager = (function (_super) {
  12580. __extends(FreeCameraInputsManager, _super);
  12581. function FreeCameraInputsManager(camera) {
  12582. _super.call(this, camera);
  12583. }
  12584. FreeCameraInputsManager.prototype.addKeyboard = function () {
  12585. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  12586. return this;
  12587. };
  12588. FreeCameraInputsManager.prototype.addMouse = function () {
  12589. this.add(new BABYLON.FreeCameraMouseInput());
  12590. return this;
  12591. };
  12592. FreeCameraInputsManager.prototype.addGamepad = function () {
  12593. this.add(new BABYLON.FreeCameraGamepadInput());
  12594. return this;
  12595. };
  12596. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  12597. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  12598. return this;
  12599. };
  12600. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  12601. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  12602. return this;
  12603. };
  12604. FreeCameraInputsManager.prototype.addTouch = function () {
  12605. this.add(new BABYLON.FreeCameraTouchInput());
  12606. return this;
  12607. };
  12608. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  12609. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  12610. return this;
  12611. };
  12612. return FreeCameraInputsManager;
  12613. })(BABYLON.CameraInputsManager);
  12614. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  12615. })(BABYLON || (BABYLON = {}));
  12616. var BABYLON;
  12617. (function (BABYLON) {
  12618. var FollowCamera = (function (_super) {
  12619. __extends(FollowCamera, _super);
  12620. function FollowCamera(name, position, scene, target) {
  12621. _super.call(this, name, position, scene);
  12622. this.radius = 12;
  12623. this.rotationOffset = 0;
  12624. this.heightOffset = 4;
  12625. this.cameraAcceleration = 0.05;
  12626. this.maxCameraSpeed = 20;
  12627. this.target = target;
  12628. }
  12629. FollowCamera.prototype.getRadians = function (degrees) {
  12630. return degrees * Math.PI / 180;
  12631. };
  12632. FollowCamera.prototype.follow = function (cameraTarget) {
  12633. if (!cameraTarget)
  12634. return;
  12635. var yRotation;
  12636. if (cameraTarget.rotationQuaternion) {
  12637. var rotMatrix = new BABYLON.Matrix();
  12638. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  12639. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  12640. }
  12641. else {
  12642. yRotation = cameraTarget.rotation.y;
  12643. }
  12644. var radians = this.getRadians(this.rotationOffset) + yRotation;
  12645. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  12646. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  12647. var dx = targetX - this.position.x;
  12648. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  12649. var dz = (targetZ) - this.position.z;
  12650. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  12651. var vy = dy * this.cameraAcceleration;
  12652. var vz = dz * this.cameraAcceleration * 2;
  12653. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  12654. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12655. }
  12656. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  12657. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12658. }
  12659. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  12660. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12661. }
  12662. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  12663. this.setTarget(cameraTarget.position);
  12664. };
  12665. FollowCamera.prototype._checkInputs = function () {
  12666. _super.prototype._checkInputs.call(this);
  12667. this.follow(this.target);
  12668. };
  12669. FollowCamera.prototype.getTypeName = function () {
  12670. return "FollowCamera";
  12671. };
  12672. __decorate([
  12673. BABYLON.serialize()
  12674. ], FollowCamera.prototype, "radius", void 0);
  12675. __decorate([
  12676. BABYLON.serialize()
  12677. ], FollowCamera.prototype, "rotationOffset", void 0);
  12678. __decorate([
  12679. BABYLON.serialize()
  12680. ], FollowCamera.prototype, "heightOffset", void 0);
  12681. __decorate([
  12682. BABYLON.serialize()
  12683. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  12684. __decorate([
  12685. BABYLON.serialize()
  12686. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  12687. __decorate([
  12688. BABYLON.serializeAsMeshReference("lockedTargetId")
  12689. ], FollowCamera.prototype, "target", void 0);
  12690. return FollowCamera;
  12691. })(BABYLON.TargetCamera);
  12692. BABYLON.FollowCamera = FollowCamera;
  12693. var ArcFollowCamera = (function (_super) {
  12694. __extends(ArcFollowCamera, _super);
  12695. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  12696. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  12697. this.alpha = alpha;
  12698. this.beta = beta;
  12699. this.radius = radius;
  12700. this.target = target;
  12701. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  12702. this.follow();
  12703. }
  12704. ArcFollowCamera.prototype.follow = function () {
  12705. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  12706. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  12707. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  12708. this.position = this.target.position.add(this._cartesianCoordinates);
  12709. this.setTarget(this.target.position);
  12710. };
  12711. ArcFollowCamera.prototype._checkInputs = function () {
  12712. _super.prototype._checkInputs.call(this);
  12713. this.follow();
  12714. };
  12715. ArcFollowCamera.prototype.getTypeName = function () {
  12716. return "ArcFollowCamera";
  12717. };
  12718. return ArcFollowCamera;
  12719. })(BABYLON.TargetCamera);
  12720. BABYLON.ArcFollowCamera = ArcFollowCamera;
  12721. })(BABYLON || (BABYLON = {}));
  12722. var BABYLON;
  12723. (function (BABYLON) {
  12724. // We're mainly based on the logic defined into the FreeCamera code
  12725. var TouchCamera = (function (_super) {
  12726. __extends(TouchCamera, _super);
  12727. //-- end properties for backward compatibility for inputs
  12728. function TouchCamera(name, position, scene) {
  12729. _super.call(this, name, position, scene);
  12730. this.inputs.addTouch();
  12731. }
  12732. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  12733. //-- Begin properties for backward compatibility for inputs
  12734. get: function () {
  12735. var touch = this.inputs.attached["touch"];
  12736. if (touch)
  12737. return touch.touchAngularSensibility;
  12738. },
  12739. set: function (value) {
  12740. var touch = this.inputs.attached["touch"];
  12741. if (touch)
  12742. touch.touchAngularSensibility = value;
  12743. },
  12744. enumerable: true,
  12745. configurable: true
  12746. });
  12747. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  12748. get: function () {
  12749. var touch = this.inputs.attached["touch"];
  12750. if (touch)
  12751. return touch.touchMoveSensibility;
  12752. },
  12753. set: function (value) {
  12754. var touch = this.inputs.attached["touch"];
  12755. if (touch)
  12756. touch.touchMoveSensibility = value;
  12757. },
  12758. enumerable: true,
  12759. configurable: true
  12760. });
  12761. TouchCamera.prototype.getTypeName = function () {
  12762. return "TouchCamera";
  12763. };
  12764. return TouchCamera;
  12765. })(BABYLON.FreeCamera);
  12766. BABYLON.TouchCamera = TouchCamera;
  12767. })(BABYLON || (BABYLON = {}));
  12768. var BABYLON;
  12769. (function (BABYLON) {
  12770. var ArcRotateCamera = (function (_super) {
  12771. __extends(ArcRotateCamera, _super);
  12772. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  12773. var _this = this;
  12774. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  12775. this.inertialAlphaOffset = 0;
  12776. this.inertialBetaOffset = 0;
  12777. this.inertialRadiusOffset = 0;
  12778. this.lowerAlphaLimit = null;
  12779. this.upperAlphaLimit = null;
  12780. this.lowerBetaLimit = 0.01;
  12781. this.upperBetaLimit = Math.PI;
  12782. this.lowerRadiusLimit = null;
  12783. this.upperRadiusLimit = null;
  12784. this.inertialPanningX = 0;
  12785. this.inertialPanningY = 0;
  12786. //-- end properties for backward compatibility for inputs
  12787. this.zoomOnFactor = 1;
  12788. this.targetScreenOffset = BABYLON.Vector2.Zero();
  12789. this.allowUpsideDown = true;
  12790. this._viewMatrix = new BABYLON.Matrix();
  12791. // Panning
  12792. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  12793. this.checkCollisions = false;
  12794. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  12795. this._collider = new BABYLON.Collider();
  12796. this._previousPosition = BABYLON.Vector3.Zero();
  12797. this._collisionVelocity = BABYLON.Vector3.Zero();
  12798. this._newPosition = BABYLON.Vector3.Zero();
  12799. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12800. if (collidedMesh === void 0) { collidedMesh = null; }
  12801. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  12802. newPosition.multiplyInPlace(_this._collider.radius);
  12803. }
  12804. if (!collidedMesh) {
  12805. _this._previousPosition.copyFrom(_this.position);
  12806. }
  12807. else {
  12808. _this.setPosition(newPosition);
  12809. if (_this.onCollide) {
  12810. _this.onCollide(collidedMesh);
  12811. }
  12812. }
  12813. // Recompute because of constraints
  12814. var cosa = Math.cos(_this.alpha);
  12815. var sina = Math.sin(_this.alpha);
  12816. var cosb = Math.cos(_this.beta);
  12817. var sinb = Math.sin(_this.beta);
  12818. if (sinb === 0) {
  12819. sinb = 0.0001;
  12820. }
  12821. var target = _this._getTargetPosition();
  12822. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  12823. _this.position.copyFrom(_this._newPosition);
  12824. var up = _this.upVector;
  12825. if (_this.allowUpsideDown && _this.beta < 0) {
  12826. up = up.clone();
  12827. up = up.negate();
  12828. }
  12829. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  12830. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  12831. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  12832. _this._collisionTriggered = false;
  12833. };
  12834. if (!target) {
  12835. this.target = BABYLON.Vector3.Zero();
  12836. }
  12837. else {
  12838. this.target = target;
  12839. }
  12840. this.alpha = alpha;
  12841. this.beta = beta;
  12842. this.radius = radius;
  12843. this.getViewMatrix();
  12844. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  12845. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  12846. }
  12847. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  12848. //-- begin properties for backward compatibility for inputs
  12849. get: function () {
  12850. var pointers = this.inputs.attached["pointers"];
  12851. if (pointers)
  12852. return pointers.angularSensibilityX;
  12853. },
  12854. set: function (value) {
  12855. var pointers = this.inputs.attached["pointers"];
  12856. if (pointers) {
  12857. pointers.angularSensibilityX = value;
  12858. }
  12859. },
  12860. enumerable: true,
  12861. configurable: true
  12862. });
  12863. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  12864. get: function () {
  12865. var pointers = this.inputs.attached["pointers"];
  12866. if (pointers)
  12867. return pointers.angularSensibilityY;
  12868. },
  12869. set: function (value) {
  12870. var pointers = this.inputs.attached["pointers"];
  12871. if (pointers) {
  12872. pointers.angularSensibilityY = value;
  12873. }
  12874. },
  12875. enumerable: true,
  12876. configurable: true
  12877. });
  12878. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  12879. get: function () {
  12880. var pointers = this.inputs.attached["pointers"];
  12881. if (pointers)
  12882. return pointers.pinchPrecision;
  12883. },
  12884. set: function (value) {
  12885. var pointers = this.inputs.attached["pointers"];
  12886. if (pointers) {
  12887. pointers.pinchPrecision = value;
  12888. }
  12889. },
  12890. enumerable: true,
  12891. configurable: true
  12892. });
  12893. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  12894. get: function () {
  12895. var pointers = this.inputs.attached["pointers"];
  12896. if (pointers)
  12897. return pointers.panningSensibility;
  12898. },
  12899. set: function (value) {
  12900. var pointers = this.inputs.attached["pointers"];
  12901. if (pointers) {
  12902. pointers.panningSensibility = value;
  12903. }
  12904. },
  12905. enumerable: true,
  12906. configurable: true
  12907. });
  12908. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  12909. get: function () {
  12910. var keyboard = this.inputs.attached["keyboard"];
  12911. if (keyboard)
  12912. return keyboard.keysUp;
  12913. },
  12914. set: function (value) {
  12915. var keyboard = this.inputs.attached["keyboard"];
  12916. if (keyboard)
  12917. keyboard.keysUp = value;
  12918. },
  12919. enumerable: true,
  12920. configurable: true
  12921. });
  12922. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  12923. get: function () {
  12924. var keyboard = this.inputs.attached["keyboard"];
  12925. if (keyboard)
  12926. return keyboard.keysDown;
  12927. },
  12928. set: function (value) {
  12929. var keyboard = this.inputs.attached["keyboard"];
  12930. if (keyboard)
  12931. keyboard.keysDown = value;
  12932. },
  12933. enumerable: true,
  12934. configurable: true
  12935. });
  12936. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  12937. get: function () {
  12938. var keyboard = this.inputs.attached["keyboard"];
  12939. if (keyboard)
  12940. return keyboard.keysLeft;
  12941. },
  12942. set: function (value) {
  12943. var keyboard = this.inputs.attached["keyboard"];
  12944. if (keyboard)
  12945. keyboard.keysLeft = value;
  12946. },
  12947. enumerable: true,
  12948. configurable: true
  12949. });
  12950. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  12951. get: function () {
  12952. var keyboard = this.inputs.attached["keyboard"];
  12953. if (keyboard)
  12954. return keyboard.keysRight;
  12955. },
  12956. set: function (value) {
  12957. var keyboard = this.inputs.attached["keyboard"];
  12958. if (keyboard)
  12959. keyboard.keysRight = value;
  12960. },
  12961. enumerable: true,
  12962. configurable: true
  12963. });
  12964. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  12965. get: function () {
  12966. var mousewheel = this.inputs.attached["mousewheel"];
  12967. if (mousewheel)
  12968. return mousewheel.wheelPrecision;
  12969. },
  12970. set: function (value) {
  12971. var mousewheel = this.inputs.attached["mousewheel"];
  12972. if (mousewheel)
  12973. mousewheel.wheelPrecision = value;
  12974. },
  12975. enumerable: true,
  12976. configurable: true
  12977. });
  12978. // Cache
  12979. ArcRotateCamera.prototype._initCache = function () {
  12980. _super.prototype._initCache.call(this);
  12981. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12982. this._cache.alpha = undefined;
  12983. this._cache.beta = undefined;
  12984. this._cache.radius = undefined;
  12985. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  12986. };
  12987. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  12988. if (!ignoreParentClass) {
  12989. _super.prototype._updateCache.call(this);
  12990. }
  12991. this._cache.target.copyFrom(this._getTargetPosition());
  12992. this._cache.alpha = this.alpha;
  12993. this._cache.beta = this.beta;
  12994. this._cache.radius = this.radius;
  12995. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  12996. };
  12997. ArcRotateCamera.prototype._getTargetPosition = function () {
  12998. if (this.target.getAbsolutePosition) {
  12999. return this.target.getAbsolutePosition();
  13000. }
  13001. return this.target;
  13002. };
  13003. // Synchronized
  13004. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13005. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13006. return false;
  13007. return this._cache.target.equals(this.target)
  13008. && this._cache.alpha === this.alpha
  13009. && this._cache.beta === this.beta
  13010. && this._cache.radius === this.radius
  13011. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13012. };
  13013. // Methods
  13014. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13015. var _this = this;
  13016. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13017. if (this._attachedElement) {
  13018. return;
  13019. }
  13020. this._attachedElement = element;
  13021. this._noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13022. this._useCtrlForPanning = useCtrlForPanning;
  13023. this.inputs.attachElement(element, noPreventDefault);
  13024. this._reset = function () {
  13025. _this.inertialAlphaOffset = 0;
  13026. _this.inertialBetaOffset = 0;
  13027. _this.inertialRadiusOffset = 0;
  13028. };
  13029. };
  13030. ArcRotateCamera.prototype.detachControl = function (element) {
  13031. if (this._attachedElement !== element) {
  13032. return;
  13033. }
  13034. this.inputs.detachElement(this._attachedElement);
  13035. this._attachedElement = null;
  13036. if (this._reset) {
  13037. this._reset();
  13038. }
  13039. };
  13040. ArcRotateCamera.prototype._checkInputs = function () {
  13041. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13042. if (this._collisionTriggered) {
  13043. return;
  13044. }
  13045. this.inputs.checkInputs();
  13046. // Inertia
  13047. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13048. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13049. this.beta += this.inertialBetaOffset;
  13050. this.radius -= this.inertialRadiusOffset;
  13051. this.inertialAlphaOffset *= this.inertia;
  13052. this.inertialBetaOffset *= this.inertia;
  13053. this.inertialRadiusOffset *= this.inertia;
  13054. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13055. this.inertialAlphaOffset = 0;
  13056. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13057. this.inertialBetaOffset = 0;
  13058. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13059. this.inertialRadiusOffset = 0;
  13060. }
  13061. // Panning inertia
  13062. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13063. if (!this._localDirection) {
  13064. this._localDirection = BABYLON.Vector3.Zero();
  13065. this._transformedDirection = BABYLON.Vector3.Zero();
  13066. }
  13067. this.inertialPanningX *= this.inertia;
  13068. this.inertialPanningY *= this.inertia;
  13069. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13070. this.inertialPanningX = 0;
  13071. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13072. this.inertialPanningY = 0;
  13073. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13074. this._localDirection.multiplyInPlace(this.panningAxis);
  13075. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13076. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13077. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13078. if (!this.panningAxis.y) {
  13079. this._transformedDirection.y = 0;
  13080. }
  13081. this.target.addInPlace(this._transformedDirection);
  13082. }
  13083. // Limits
  13084. this._checkLimits();
  13085. _super.prototype._checkInputs.call(this);
  13086. };
  13087. ArcRotateCamera.prototype._checkLimits = function () {
  13088. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13089. if (this.allowUpsideDown && this.beta > Math.PI) {
  13090. this.beta = this.beta - (2 * Math.PI);
  13091. }
  13092. }
  13093. else {
  13094. if (this.beta < this.lowerBetaLimit) {
  13095. this.beta = this.lowerBetaLimit;
  13096. }
  13097. }
  13098. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13099. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13100. this.beta = this.beta + (2 * Math.PI);
  13101. }
  13102. }
  13103. else {
  13104. if (this.beta > this.upperBetaLimit) {
  13105. this.beta = this.upperBetaLimit;
  13106. }
  13107. }
  13108. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13109. this.alpha = this.lowerAlphaLimit;
  13110. }
  13111. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13112. this.alpha = this.upperAlphaLimit;
  13113. }
  13114. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13115. this.radius = this.lowerRadiusLimit;
  13116. }
  13117. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13118. this.radius = this.upperRadiusLimit;
  13119. }
  13120. };
  13121. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13122. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13123. this.radius = radiusv3.length();
  13124. // Alpha
  13125. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13126. if (radiusv3.z < 0) {
  13127. this.alpha = 2 * Math.PI - this.alpha;
  13128. }
  13129. // Beta
  13130. this.beta = Math.acos(radiusv3.y / this.radius);
  13131. this._checkLimits();
  13132. };
  13133. ArcRotateCamera.prototype.setPosition = function (position) {
  13134. if (this.position.equals(position)) {
  13135. return;
  13136. }
  13137. this.position = position;
  13138. this.rebuildAnglesAndRadius();
  13139. };
  13140. ArcRotateCamera.prototype.setTarget = function (target) {
  13141. if (this._getTargetPosition().equals(target)) {
  13142. return;
  13143. }
  13144. this.target = target;
  13145. this.rebuildAnglesAndRadius();
  13146. };
  13147. ArcRotateCamera.prototype._getViewMatrix = function () {
  13148. // Compute
  13149. var cosa = Math.cos(this.alpha);
  13150. var sina = Math.sin(this.alpha);
  13151. var cosb = Math.cos(this.beta);
  13152. var sinb = Math.sin(this.beta);
  13153. if (sinb === 0) {
  13154. sinb = 0.0001;
  13155. }
  13156. var target = this._getTargetPosition();
  13157. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13158. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13159. this._collider.radius = this.collisionRadius;
  13160. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13161. this._collisionTriggered = true;
  13162. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13163. }
  13164. else {
  13165. this.position.copyFrom(this._newPosition);
  13166. var up = this.upVector;
  13167. if (this.allowUpsideDown && this.beta < 0) {
  13168. up = up.clone();
  13169. up = up.negate();
  13170. }
  13171. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13172. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13173. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13174. }
  13175. return this._viewMatrix;
  13176. };
  13177. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13178. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13179. meshes = meshes || this.getScene().meshes;
  13180. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13181. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13182. this.radius = distance * this.zoomOnFactor;
  13183. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13184. };
  13185. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13186. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13187. var meshesOrMinMaxVector;
  13188. var distance;
  13189. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13190. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13191. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13192. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13193. }
  13194. else {
  13195. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13196. distance = meshesOrMinMaxVectorAndDistance.distance;
  13197. }
  13198. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13199. if (!doNotUpdateMaxZ) {
  13200. this.maxZ = distance * 2;
  13201. }
  13202. };
  13203. /**
  13204. * @override
  13205. * Override Camera.createRigCamera
  13206. */
  13207. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13208. switch (this.cameraRigMode) {
  13209. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13210. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13211. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13212. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13213. case BABYLON.Camera.RIG_MODE_VR:
  13214. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13215. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13216. }
  13217. return null;
  13218. };
  13219. /**
  13220. * @override
  13221. * Override Camera._updateRigCameras
  13222. */
  13223. ArcRotateCamera.prototype._updateRigCameras = function () {
  13224. switch (this.cameraRigMode) {
  13225. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13226. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13227. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13228. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13229. case BABYLON.Camera.RIG_MODE_VR:
  13230. var camLeft = this._rigCameras[0];
  13231. var camRight = this._rigCameras[1];
  13232. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13233. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13234. camLeft.beta = camRight.beta = this.beta;
  13235. camLeft.radius = camRight.radius = this.radius;
  13236. break;
  13237. }
  13238. _super.prototype._updateRigCameras.call(this);
  13239. };
  13240. ArcRotateCamera.prototype.dispose = function () {
  13241. this.inputs.clear();
  13242. _super.prototype.dispose.call(this);
  13243. };
  13244. ArcRotateCamera.prototype.getTypeName = function () {
  13245. return "ArcRotateCamera";
  13246. };
  13247. __decorate([
  13248. BABYLON.serialize()
  13249. ], ArcRotateCamera.prototype, "alpha", void 0);
  13250. __decorate([
  13251. BABYLON.serialize()
  13252. ], ArcRotateCamera.prototype, "beta", void 0);
  13253. __decorate([
  13254. BABYLON.serialize()
  13255. ], ArcRotateCamera.prototype, "radius", void 0);
  13256. __decorate([
  13257. BABYLON.serializeAsVector3()
  13258. ], ArcRotateCamera.prototype, "target", void 0);
  13259. __decorate([
  13260. BABYLON.serialize()
  13261. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13262. __decorate([
  13263. BABYLON.serialize()
  13264. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13265. __decorate([
  13266. BABYLON.serialize()
  13267. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13268. __decorate([
  13269. BABYLON.serialize()
  13270. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13271. __decorate([
  13272. BABYLON.serialize()
  13273. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13274. __decorate([
  13275. BABYLON.serialize()
  13276. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13277. __decorate([
  13278. BABYLON.serialize()
  13279. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13280. __decorate([
  13281. BABYLON.serialize()
  13282. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13283. __decorate([
  13284. BABYLON.serialize()
  13285. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13286. __decorate([
  13287. BABYLON.serialize()
  13288. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13289. __decorate([
  13290. BABYLON.serialize()
  13291. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13292. __decorate([
  13293. BABYLON.serialize()
  13294. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13295. __decorate([
  13296. BABYLON.serialize()
  13297. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13298. return ArcRotateCamera;
  13299. })(BABYLON.TargetCamera);
  13300. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13301. })(BABYLON || (BABYLON = {}));
  13302. var BABYLON;
  13303. (function (BABYLON) {
  13304. var ArcRotateCameraInputsManager = (function (_super) {
  13305. __extends(ArcRotateCameraInputsManager, _super);
  13306. function ArcRotateCameraInputsManager(camera) {
  13307. _super.call(this, camera);
  13308. }
  13309. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13310. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13311. return this;
  13312. };
  13313. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13314. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13315. return this;
  13316. };
  13317. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13318. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13319. return this;
  13320. };
  13321. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13322. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13323. return this;
  13324. };
  13325. return ArcRotateCameraInputsManager;
  13326. })(BABYLON.CameraInputsManager);
  13327. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13328. })(BABYLON || (BABYLON = {}));
  13329. var BABYLON;
  13330. (function (BABYLON) {
  13331. var RenderingManager = (function () {
  13332. function RenderingManager(scene) {
  13333. this._renderingGroups = new Array();
  13334. this._scene = scene;
  13335. }
  13336. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13337. if (this._scene._activeParticleSystems.length === 0) {
  13338. return;
  13339. }
  13340. // Particles
  13341. var activeCamera = this._scene.activeCamera;
  13342. var beforeParticlesDate = BABYLON.Tools.Now;
  13343. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13344. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13345. if (particleSystem.renderingGroupId !== index) {
  13346. continue;
  13347. }
  13348. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13349. continue;
  13350. }
  13351. this._clearDepthBuffer();
  13352. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13353. this._scene._activeParticles += particleSystem.render();
  13354. }
  13355. }
  13356. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13357. };
  13358. RenderingManager.prototype._renderSprites = function (index) {
  13359. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13360. return;
  13361. }
  13362. // Sprites
  13363. var activeCamera = this._scene.activeCamera;
  13364. var beforeSpritessDate = BABYLON.Tools.Now;
  13365. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13366. var spriteManager = this._scene.spriteManagers[id];
  13367. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13368. this._clearDepthBuffer();
  13369. spriteManager.render();
  13370. }
  13371. }
  13372. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13373. };
  13374. RenderingManager.prototype._clearDepthBuffer = function () {
  13375. if (this._depthBufferAlreadyCleaned) {
  13376. return;
  13377. }
  13378. this._scene.getEngine().clear(0, false, true);
  13379. this._depthBufferAlreadyCleaned = true;
  13380. };
  13381. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13382. if (this._currentRenderSprites) {
  13383. this._renderSprites(this._currentIndex);
  13384. }
  13385. if (this._currentRenderParticles) {
  13386. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13387. }
  13388. };
  13389. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13390. this._currentActiveMeshes = activeMeshes;
  13391. this._currentRenderParticles = renderParticles;
  13392. this._currentRenderSprites = renderSprites;
  13393. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13394. this._depthBufferAlreadyCleaned = index == 0;
  13395. var renderingGroup = this._renderingGroups[index];
  13396. var needToStepBack = false;
  13397. this._currentIndex = index;
  13398. if (renderingGroup) {
  13399. this._clearDepthBuffer();
  13400. if (!renderingGroup.onBeforeTransparentRendering) {
  13401. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13402. }
  13403. if (!renderingGroup.render(customRenderFunction)) {
  13404. this._renderingGroups.splice(index, 1);
  13405. needToStepBack = true;
  13406. this._renderSpritesAndParticles();
  13407. }
  13408. }
  13409. else {
  13410. this._renderSpritesAndParticles();
  13411. }
  13412. if (needToStepBack) {
  13413. index--;
  13414. }
  13415. }
  13416. };
  13417. RenderingManager.prototype.reset = function () {
  13418. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13419. if (renderingGroup) {
  13420. renderingGroup.prepare();
  13421. }
  13422. });
  13423. };
  13424. RenderingManager.prototype.dispatch = function (subMesh) {
  13425. var mesh = subMesh.getMesh();
  13426. var renderingGroupId = mesh.renderingGroupId || 0;
  13427. if (!this._renderingGroups[renderingGroupId]) {
  13428. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13429. }
  13430. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13431. };
  13432. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13433. return RenderingManager;
  13434. })();
  13435. BABYLON.RenderingManager = RenderingManager;
  13436. })(BABYLON || (BABYLON = {}));
  13437. var BABYLON;
  13438. (function (BABYLON) {
  13439. var RenderingGroup = (function () {
  13440. function RenderingGroup(index, scene) {
  13441. this.index = index;
  13442. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13443. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13444. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13445. this._scene = scene;
  13446. }
  13447. RenderingGroup.prototype.render = function (customRenderFunction) {
  13448. if (customRenderFunction) {
  13449. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13450. return true;
  13451. }
  13452. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  13453. if (this.onBeforeTransparentRendering) {
  13454. this.onBeforeTransparentRendering();
  13455. }
  13456. return false;
  13457. }
  13458. var engine = this._scene.getEngine();
  13459. // Opaque
  13460. var subIndex;
  13461. var submesh;
  13462. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  13463. submesh = this._opaqueSubMeshes.data[subIndex];
  13464. submesh.render(false);
  13465. }
  13466. // Alpha test
  13467. engine.setAlphaTesting(true);
  13468. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  13469. submesh = this._alphaTestSubMeshes.data[subIndex];
  13470. submesh.render(false);
  13471. }
  13472. engine.setAlphaTesting(false);
  13473. if (this.onBeforeTransparentRendering) {
  13474. this.onBeforeTransparentRendering();
  13475. }
  13476. // Transparent
  13477. if (this._transparentSubMeshes.length) {
  13478. // Sorting
  13479. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  13480. submesh = this._transparentSubMeshes.data[subIndex];
  13481. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  13482. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  13483. }
  13484. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  13485. sortedArray.sort(function (a, b) {
  13486. // Alpha index first
  13487. if (a._alphaIndex > b._alphaIndex) {
  13488. return 1;
  13489. }
  13490. if (a._alphaIndex < b._alphaIndex) {
  13491. return -1;
  13492. }
  13493. // Then distance to camera
  13494. if (a._distanceToCamera < b._distanceToCamera) {
  13495. return 1;
  13496. }
  13497. if (a._distanceToCamera > b._distanceToCamera) {
  13498. return -1;
  13499. }
  13500. return 0;
  13501. });
  13502. // Rendering
  13503. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  13504. submesh = sortedArray[subIndex];
  13505. submesh.render(true);
  13506. }
  13507. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13508. }
  13509. return true;
  13510. };
  13511. RenderingGroup.prototype.prepare = function () {
  13512. this._opaqueSubMeshes.reset();
  13513. this._transparentSubMeshes.reset();
  13514. this._alphaTestSubMeshes.reset();
  13515. };
  13516. RenderingGroup.prototype.dispatch = function (subMesh) {
  13517. var material = subMesh.getMaterial();
  13518. var mesh = subMesh.getMesh();
  13519. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  13520. this._transparentSubMeshes.push(subMesh);
  13521. }
  13522. else if (material.needAlphaTesting()) {
  13523. this._alphaTestSubMeshes.push(subMesh);
  13524. }
  13525. else {
  13526. this._opaqueSubMeshes.push(subMesh); // Opaque
  13527. }
  13528. };
  13529. return RenderingGroup;
  13530. })();
  13531. BABYLON.RenderingGroup = RenderingGroup;
  13532. })(BABYLON || (BABYLON = {}));
  13533. var BABYLON;
  13534. (function (BABYLON) {
  13535. /**
  13536. * Represents a scene to be rendered by the engine.
  13537. * @see http://doc.babylonjs.com/page.php?p=21911
  13538. */
  13539. var Scene = (function () {
  13540. /**
  13541. * @constructor
  13542. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  13543. */
  13544. function Scene(engine) {
  13545. // Members
  13546. this.autoClear = true;
  13547. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  13548. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13549. this.forceWireframe = false;
  13550. this.forcePointsCloud = false;
  13551. this.forceShowBoundingBoxes = false;
  13552. this.animationsEnabled = true;
  13553. this.constantlyUpdateMeshUnderPointer = false;
  13554. // Animations
  13555. this.animations = [];
  13556. 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
  13557. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  13558. this._startingPointerTime = 0;
  13559. // Fog
  13560. /**
  13561. * is fog enabled on this scene.
  13562. * @type {boolean}
  13563. */
  13564. this.fogEnabled = true;
  13565. this.fogMode = Scene.FOGMODE_NONE;
  13566. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  13567. this.fogDensity = 0.1;
  13568. this.fogStart = 0;
  13569. this.fogEnd = 1000.0;
  13570. // Lights
  13571. /**
  13572. * is shadow enabled on this scene.
  13573. * @type {boolean}
  13574. */
  13575. this.shadowsEnabled = true;
  13576. /**
  13577. * is light enabled on this scene.
  13578. * @type {boolean}
  13579. */
  13580. this.lightsEnabled = true;
  13581. /**
  13582. * All of the lights added to this scene.
  13583. * @see BABYLON.Light
  13584. * @type {BABYLON.Light[]}
  13585. */
  13586. this.lights = new Array();
  13587. // Cameras
  13588. /**
  13589. * All of the cameras added to this scene.
  13590. * @see BABYLON.Camera
  13591. * @type {BABYLON.Camera[]}
  13592. */
  13593. this.cameras = new Array();
  13594. this.activeCameras = new Array();
  13595. // Meshes
  13596. /**
  13597. * All of the (abstract) meshes added to this scene.
  13598. * @see BABYLON.AbstractMesh
  13599. * @type {BABYLON.AbstractMesh[]}
  13600. */
  13601. this.meshes = new Array();
  13602. // Geometries
  13603. this._geometries = new Array();
  13604. this.materials = new Array();
  13605. this.multiMaterials = new Array();
  13606. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  13607. // Textures
  13608. this.texturesEnabled = true;
  13609. this.textures = new Array();
  13610. // Particles
  13611. this.particlesEnabled = true;
  13612. this.particleSystems = new Array();
  13613. // Sprites
  13614. this.spritesEnabled = true;
  13615. this.spriteManagers = new Array();
  13616. // Layers
  13617. this.layers = new Array();
  13618. // Skeletons
  13619. this.skeletonsEnabled = true;
  13620. this.skeletons = new Array();
  13621. // Lens flares
  13622. this.lensFlaresEnabled = true;
  13623. this.lensFlareSystems = new Array();
  13624. // Collisions
  13625. this.collisionsEnabled = true;
  13626. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  13627. // Postprocesses
  13628. this.postProcessesEnabled = true;
  13629. // Customs render targets
  13630. this.renderTargetsEnabled = true;
  13631. this.dumpNextRenderTargets = false;
  13632. this.customRenderTargets = new Array();
  13633. // Imported meshes
  13634. this.importedMeshesFiles = new Array();
  13635. // Probes
  13636. this.probesEnabled = true;
  13637. this.reflectionProbes = new Array();
  13638. this._actionManagers = new Array();
  13639. this._meshesForIntersections = new BABYLON.SmartArray(256);
  13640. // Procedural textures
  13641. this.proceduralTexturesEnabled = true;
  13642. this._proceduralTextures = new Array();
  13643. this.soundTracks = new Array();
  13644. this._audioEnabled = true;
  13645. this._headphone = false;
  13646. this._totalVertices = 0;
  13647. this._activeIndices = 0;
  13648. this._activeParticles = 0;
  13649. this._lastFrameDuration = 0;
  13650. this._evaluateActiveMeshesDuration = 0;
  13651. this._renderTargetsDuration = 0;
  13652. this._particlesDuration = 0;
  13653. this._renderDuration = 0;
  13654. this._spritesDuration = 0;
  13655. this._animationRatio = 0;
  13656. this._renderId = 0;
  13657. this._executeWhenReadyTimeoutId = -1;
  13658. this._toBeDisposed = new BABYLON.SmartArray(256);
  13659. this._onReadyCallbacks = new Array();
  13660. this._pendingData = []; //ANY
  13661. this._onBeforeRenderCallbacks = new Array();
  13662. this._onAfterRenderCallbacks = new Array();
  13663. this._activeMeshes = new BABYLON.SmartArray(256);
  13664. this._processedMaterials = new BABYLON.SmartArray(256);
  13665. this._renderTargets = new BABYLON.SmartArray(256);
  13666. this._activeParticleSystems = new BABYLON.SmartArray(256);
  13667. this._activeSkeletons = new BABYLON.SmartArray(32);
  13668. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  13669. this._activeBones = 0;
  13670. this._activeAnimatables = new Array();
  13671. this._transformMatrix = BABYLON.Matrix.Zero();
  13672. this._edgesRenderers = new BABYLON.SmartArray(16);
  13673. this._uniqueIdCounter = 0;
  13674. this._engine = engine;
  13675. engine.scenes.push(this);
  13676. this._renderingManager = new BABYLON.RenderingManager(this);
  13677. this.postProcessManager = new BABYLON.PostProcessManager(this);
  13678. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  13679. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  13680. if (BABYLON.OutlineRenderer) {
  13681. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  13682. }
  13683. this.attachControl();
  13684. this._debugLayer = new BABYLON.DebugLayer(this);
  13685. if (BABYLON.SoundTrack) {
  13686. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  13687. }
  13688. //simplification queue
  13689. if (BABYLON.SimplificationQueue) {
  13690. this.simplificationQueue = new BABYLON.SimplificationQueue();
  13691. }
  13692. //collision coordinator initialization. For now legacy per default.
  13693. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  13694. }
  13695. Object.defineProperty(Scene, "FOGMODE_NONE", {
  13696. get: function () {
  13697. return Scene._FOGMODE_NONE;
  13698. },
  13699. enumerable: true,
  13700. configurable: true
  13701. });
  13702. Object.defineProperty(Scene, "FOGMODE_EXP", {
  13703. get: function () {
  13704. return Scene._FOGMODE_EXP;
  13705. },
  13706. enumerable: true,
  13707. configurable: true
  13708. });
  13709. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  13710. get: function () {
  13711. return Scene._FOGMODE_EXP2;
  13712. },
  13713. enumerable: true,
  13714. configurable: true
  13715. });
  13716. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  13717. get: function () {
  13718. return Scene._FOGMODE_LINEAR;
  13719. },
  13720. enumerable: true,
  13721. configurable: true
  13722. });
  13723. Object.defineProperty(Scene.prototype, "debugLayer", {
  13724. // Properties
  13725. get: function () {
  13726. return this._debugLayer;
  13727. },
  13728. enumerable: true,
  13729. configurable: true
  13730. });
  13731. Object.defineProperty(Scene.prototype, "workerCollisions", {
  13732. get: function () {
  13733. return this._workerCollisions;
  13734. },
  13735. set: function (enabled) {
  13736. enabled = (enabled && !!Worker);
  13737. this._workerCollisions = enabled;
  13738. if (this.collisionCoordinator) {
  13739. this.collisionCoordinator.destroy();
  13740. }
  13741. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  13742. this.collisionCoordinator.init(this);
  13743. },
  13744. enumerable: true,
  13745. configurable: true
  13746. });
  13747. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  13748. get: function () {
  13749. return this._selectionOctree;
  13750. },
  13751. enumerable: true,
  13752. configurable: true
  13753. });
  13754. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  13755. /**
  13756. * The mesh that is currently under the pointer.
  13757. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  13758. */
  13759. get: function () {
  13760. return this._pointerOverMesh;
  13761. },
  13762. enumerable: true,
  13763. configurable: true
  13764. });
  13765. Object.defineProperty(Scene.prototype, "pointerX", {
  13766. /**
  13767. * Current on-screen X position of the pointer
  13768. * @return {number} X position of the pointer
  13769. */
  13770. get: function () {
  13771. return this._pointerX;
  13772. },
  13773. enumerable: true,
  13774. configurable: true
  13775. });
  13776. Object.defineProperty(Scene.prototype, "pointerY", {
  13777. /**
  13778. * Current on-screen Y position of the pointer
  13779. * @return {number} Y position of the pointer
  13780. */
  13781. get: function () {
  13782. return this._pointerY;
  13783. },
  13784. enumerable: true,
  13785. configurable: true
  13786. });
  13787. Scene.prototype.getCachedMaterial = function () {
  13788. return this._cachedMaterial;
  13789. };
  13790. Scene.prototype.getBoundingBoxRenderer = function () {
  13791. return this._boundingBoxRenderer;
  13792. };
  13793. Scene.prototype.getOutlineRenderer = function () {
  13794. return this._outlineRenderer;
  13795. };
  13796. Scene.prototype.getEngine = function () {
  13797. return this._engine;
  13798. };
  13799. Scene.prototype.getTotalVertices = function () {
  13800. return this._totalVertices;
  13801. };
  13802. Scene.prototype.getActiveIndices = function () {
  13803. return this._activeIndices;
  13804. };
  13805. Scene.prototype.getActiveParticles = function () {
  13806. return this._activeParticles;
  13807. };
  13808. Scene.prototype.getActiveBones = function () {
  13809. return this._activeBones;
  13810. };
  13811. // Stats
  13812. Scene.prototype.getLastFrameDuration = function () {
  13813. return this._lastFrameDuration;
  13814. };
  13815. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  13816. return this._evaluateActiveMeshesDuration;
  13817. };
  13818. Scene.prototype.getActiveMeshes = function () {
  13819. return this._activeMeshes;
  13820. };
  13821. Scene.prototype.getRenderTargetsDuration = function () {
  13822. return this._renderTargetsDuration;
  13823. };
  13824. Scene.prototype.getRenderDuration = function () {
  13825. return this._renderDuration;
  13826. };
  13827. Scene.prototype.getParticlesDuration = function () {
  13828. return this._particlesDuration;
  13829. };
  13830. Scene.prototype.getSpritesDuration = function () {
  13831. return this._spritesDuration;
  13832. };
  13833. Scene.prototype.getAnimationRatio = function () {
  13834. return this._animationRatio;
  13835. };
  13836. Scene.prototype.getRenderId = function () {
  13837. return this._renderId;
  13838. };
  13839. Scene.prototype.incrementRenderId = function () {
  13840. this._renderId++;
  13841. };
  13842. Scene.prototype._updatePointerPosition = function (evt) {
  13843. var canvasRect = this._engine.getRenderingCanvasClientRect();
  13844. this._pointerX = evt.clientX - canvasRect.left;
  13845. this._pointerY = evt.clientY - canvasRect.top;
  13846. this._unTranslatedPointerX = this._pointerX;
  13847. this._unTranslatedPointerY = this._pointerY;
  13848. if (this.cameraToUseForPointers) {
  13849. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  13850. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  13851. }
  13852. };
  13853. // Pointers handling
  13854. Scene.prototype.attachControl = function () {
  13855. var _this = this;
  13856. var spritePredicate = function (sprite) {
  13857. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  13858. };
  13859. this._onPointerMove = function (evt) {
  13860. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13861. return;
  13862. }
  13863. var canvas = _this._engine.getRenderingCanvas();
  13864. _this._updatePointerPosition(evt);
  13865. if (!_this.pointerMovePredicate) {
  13866. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  13867. }
  13868. // Meshes
  13869. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  13870. if (pickResult.hit && pickResult.pickedMesh) {
  13871. _this.setPointerOverSprite(null);
  13872. _this.setPointerOverMesh(pickResult.pickedMesh);
  13873. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  13874. canvas.style.cursor = "pointer";
  13875. }
  13876. else {
  13877. canvas.style.cursor = "";
  13878. }
  13879. }
  13880. else {
  13881. _this.setPointerOverMesh(null);
  13882. // Sprites
  13883. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13884. if (pickResult.hit && pickResult.pickedSprite) {
  13885. canvas.style.cursor = "pointer";
  13886. _this.setPointerOverSprite(pickResult.pickedSprite);
  13887. }
  13888. else {
  13889. _this.setPointerOverSprite(null);
  13890. // Restore pointer
  13891. canvas.style.cursor = "";
  13892. }
  13893. }
  13894. if (_this.onPointerMove) {
  13895. _this.onPointerMove(evt, pickResult);
  13896. }
  13897. };
  13898. this._onPointerDown = function (evt) {
  13899. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13900. return;
  13901. }
  13902. _this._updatePointerPosition(evt);
  13903. _this._startingPointerPosition.x = _this._pointerX;
  13904. _this._startingPointerPosition.y = _this._pointerY;
  13905. _this._startingPointerTime = new Date().getTime();
  13906. if (!_this.pointerDownPredicate) {
  13907. _this.pointerDownPredicate = function (mesh) {
  13908. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  13909. };
  13910. }
  13911. // Meshes
  13912. _this._pickedDownMesh = null;
  13913. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  13914. if (pickResult.hit && pickResult.pickedMesh) {
  13915. if (pickResult.pickedMesh.actionManager) {
  13916. _this._pickedDownMesh = pickResult.pickedMesh;
  13917. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  13918. switch (evt.button) {
  13919. case 0:
  13920. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13921. break;
  13922. case 1:
  13923. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13924. break;
  13925. case 2:
  13926. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13927. break;
  13928. }
  13929. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13930. }
  13931. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  13932. var that = _this;
  13933. window.setTimeout(function () {
  13934. 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);
  13935. if (pickResult.hit && pickResult.pickedMesh) {
  13936. if (pickResult.pickedMesh.actionManager) {
  13937. 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)) {
  13938. that._startingPointerTime = 0;
  13939. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13940. }
  13941. }
  13942. }
  13943. }, BABYLON.ActionManager.LongPressDelay);
  13944. }
  13945. }
  13946. }
  13947. if (_this.onPointerDown) {
  13948. _this.onPointerDown(evt, pickResult);
  13949. }
  13950. // Sprites
  13951. _this._pickedDownSprite = null;
  13952. if (_this.spriteManagers.length > 0) {
  13953. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13954. if (pickResult.hit && pickResult.pickedSprite) {
  13955. if (pickResult.pickedSprite.actionManager) {
  13956. _this._pickedDownSprite = pickResult.pickedSprite;
  13957. switch (evt.button) {
  13958. case 0:
  13959. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13960. break;
  13961. case 1:
  13962. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13963. break;
  13964. case 2:
  13965. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13966. break;
  13967. }
  13968. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13969. }
  13970. }
  13971. }
  13972. };
  13973. this._onPointerUp = function (evt) {
  13974. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13975. return;
  13976. }
  13977. _this._updatePointerPosition(evt);
  13978. if (!_this.pointerUpPredicate) {
  13979. _this.pointerUpPredicate = function (mesh) {
  13980. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  13981. };
  13982. }
  13983. // Meshes
  13984. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  13985. if (pickResult.hit && pickResult.pickedMesh) {
  13986. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  13987. _this.onPointerPick(evt, pickResult);
  13988. }
  13989. if (pickResult.pickedMesh.actionManager) {
  13990. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13991. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13992. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13993. }
  13994. }
  13995. }
  13996. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  13997. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  13998. }
  13999. if (_this.onPointerUp) {
  14000. _this.onPointerUp(evt, pickResult);
  14001. }
  14002. _this._startingPointerTime = 0;
  14003. // Sprites
  14004. if (_this.spriteManagers.length > 0) {
  14005. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14006. if (pickResult.hit && pickResult.pickedSprite) {
  14007. if (pickResult.pickedSprite.actionManager) {
  14008. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14009. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14010. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14011. }
  14012. }
  14013. }
  14014. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14015. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14016. }
  14017. }
  14018. };
  14019. this._onKeyDown = function (evt) {
  14020. if (_this.actionManager) {
  14021. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14022. }
  14023. };
  14024. this._onKeyUp = function (evt) {
  14025. if (_this.actionManager) {
  14026. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14027. }
  14028. };
  14029. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14030. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14031. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14032. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14033. // Wheel
  14034. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14035. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14036. BABYLON.Tools.RegisterTopRootEvents([
  14037. { name: "keydown", handler: this._onKeyDown },
  14038. { name: "keyup", handler: this._onKeyUp }
  14039. ]);
  14040. };
  14041. Scene.prototype.detachControl = function () {
  14042. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14043. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14044. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14045. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14046. // Wheel
  14047. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14048. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14049. BABYLON.Tools.UnregisterTopRootEvents([
  14050. { name: "keydown", handler: this._onKeyDown },
  14051. { name: "keyup", handler: this._onKeyUp }
  14052. ]);
  14053. };
  14054. // Ready
  14055. Scene.prototype.isReady = function () {
  14056. if (this._pendingData.length > 0) {
  14057. return false;
  14058. }
  14059. var index;
  14060. for (index = 0; index < this._geometries.length; index++) {
  14061. var geometry = this._geometries[index];
  14062. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14063. return false;
  14064. }
  14065. }
  14066. for (index = 0; index < this.meshes.length; index++) {
  14067. var mesh = this.meshes[index];
  14068. if (!mesh.isReady()) {
  14069. return false;
  14070. }
  14071. var mat = mesh.material;
  14072. if (mat) {
  14073. if (!mat.isReady(mesh)) {
  14074. return false;
  14075. }
  14076. }
  14077. }
  14078. return true;
  14079. };
  14080. Scene.prototype.resetCachedMaterial = function () {
  14081. this._cachedMaterial = null;
  14082. };
  14083. Scene.prototype.registerBeforeRender = function (func) {
  14084. this._onBeforeRenderCallbacks.push(func);
  14085. };
  14086. Scene.prototype.unregisterBeforeRender = function (func) {
  14087. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14088. if (index > -1) {
  14089. this._onBeforeRenderCallbacks.splice(index, 1);
  14090. }
  14091. };
  14092. Scene.prototype.registerAfterRender = function (func) {
  14093. this._onAfterRenderCallbacks.push(func);
  14094. };
  14095. Scene.prototype.unregisterAfterRender = function (func) {
  14096. var index = this._onAfterRenderCallbacks.indexOf(func);
  14097. if (index > -1) {
  14098. this._onAfterRenderCallbacks.splice(index, 1);
  14099. }
  14100. };
  14101. Scene.prototype._addPendingData = function (data) {
  14102. this._pendingData.push(data);
  14103. };
  14104. Scene.prototype._removePendingData = function (data) {
  14105. var index = this._pendingData.indexOf(data);
  14106. if (index !== -1) {
  14107. this._pendingData.splice(index, 1);
  14108. }
  14109. };
  14110. Scene.prototype.getWaitingItemsCount = function () {
  14111. return this._pendingData.length;
  14112. };
  14113. /**
  14114. * Registers a function to be executed when the scene is ready.
  14115. * @param {Function} func - the function to be executed.
  14116. */
  14117. Scene.prototype.executeWhenReady = function (func) {
  14118. var _this = this;
  14119. this._onReadyCallbacks.push(func);
  14120. if (this._executeWhenReadyTimeoutId !== -1) {
  14121. return;
  14122. }
  14123. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14124. _this._checkIsReady();
  14125. }, 150);
  14126. };
  14127. Scene.prototype._checkIsReady = function () {
  14128. var _this = this;
  14129. if (this.isReady()) {
  14130. this._onReadyCallbacks.forEach(function (func) {
  14131. func();
  14132. });
  14133. this._onReadyCallbacks = [];
  14134. this._executeWhenReadyTimeoutId = -1;
  14135. return;
  14136. }
  14137. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14138. _this._checkIsReady();
  14139. }, 150);
  14140. };
  14141. // Animations
  14142. /**
  14143. * Will start the animation sequence of a given target
  14144. * @param target - the target
  14145. * @param {number} from - from which frame should animation start
  14146. * @param {number} to - till which frame should animation run.
  14147. * @param {boolean} [loop] - should the animation loop
  14148. * @param {number} [speedRatio] - the speed in which to run the animation
  14149. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14150. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14151. * @return {BABYLON.Animatable} the animatable object created for this animation
  14152. * @see BABYLON.Animatable
  14153. * @see http://doc.babylonjs.com/page.php?p=22081
  14154. */
  14155. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14156. if (speedRatio === void 0) { speedRatio = 1.0; }
  14157. this.stopAnimation(target);
  14158. if (!animatable) {
  14159. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14160. }
  14161. // Local animations
  14162. if (target.animations) {
  14163. animatable.appendAnimations(target, target.animations);
  14164. }
  14165. // Children animations
  14166. if (target.getAnimatables) {
  14167. var animatables = target.getAnimatables();
  14168. for (var index = 0; index < animatables.length; index++) {
  14169. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14170. }
  14171. }
  14172. animatable.reset();
  14173. return animatable;
  14174. };
  14175. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14176. if (speedRatio === undefined) {
  14177. speedRatio = 1.0;
  14178. }
  14179. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14180. return animatable;
  14181. };
  14182. Scene.prototype.getAnimatableByTarget = function (target) {
  14183. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14184. if (this._activeAnimatables[index].target === target) {
  14185. return this._activeAnimatables[index];
  14186. }
  14187. }
  14188. return null;
  14189. };
  14190. Object.defineProperty(Scene.prototype, "Animatables", {
  14191. get: function () {
  14192. return this._activeAnimatables;
  14193. },
  14194. enumerable: true,
  14195. configurable: true
  14196. });
  14197. /**
  14198. * Will stop the animation of the given target
  14199. * @param target - the target
  14200. * @see beginAnimation
  14201. */
  14202. Scene.prototype.stopAnimation = function (target) {
  14203. var animatable = this.getAnimatableByTarget(target);
  14204. if (animatable) {
  14205. animatable.stop();
  14206. }
  14207. };
  14208. Scene.prototype._animate = function () {
  14209. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14210. return;
  14211. }
  14212. if (!this._animationStartDate) {
  14213. if (this._pendingData.length > 0) {
  14214. return;
  14215. }
  14216. this._animationStartDate = BABYLON.Tools.Now;
  14217. }
  14218. // Getting time
  14219. var now = BABYLON.Tools.Now;
  14220. var delay = now - this._animationStartDate;
  14221. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14222. this._activeAnimatables[index]._animate(delay);
  14223. }
  14224. };
  14225. // Matrix
  14226. Scene.prototype.getViewMatrix = function () {
  14227. return this._viewMatrix;
  14228. };
  14229. Scene.prototype.getProjectionMatrix = function () {
  14230. return this._projectionMatrix;
  14231. };
  14232. Scene.prototype.getTransformMatrix = function () {
  14233. return this._transformMatrix;
  14234. };
  14235. Scene.prototype.setTransformMatrix = function (view, projection) {
  14236. this._viewMatrix = view;
  14237. this._projectionMatrix = projection;
  14238. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14239. };
  14240. // Methods
  14241. Scene.prototype.addMesh = function (newMesh) {
  14242. newMesh.uniqueId = this._uniqueIdCounter++;
  14243. var position = this.meshes.push(newMesh);
  14244. //notify the collision coordinator
  14245. this.collisionCoordinator.onMeshAdded(newMesh);
  14246. if (this.onNewMeshAdded) {
  14247. this.onNewMeshAdded(newMesh, position, this);
  14248. }
  14249. };
  14250. Scene.prototype.removeMesh = function (toRemove) {
  14251. var index = this.meshes.indexOf(toRemove);
  14252. if (index !== -1) {
  14253. // Remove from the scene if mesh found
  14254. this.meshes.splice(index, 1);
  14255. }
  14256. //notify the collision coordinator
  14257. this.collisionCoordinator.onMeshRemoved(toRemove);
  14258. if (this.onMeshRemoved) {
  14259. this.onMeshRemoved(toRemove);
  14260. }
  14261. return index;
  14262. };
  14263. Scene.prototype.removeSkeleton = function (toRemove) {
  14264. var index = this.skeletons.indexOf(toRemove);
  14265. if (index !== -1) {
  14266. // Remove from the scene if mesh found
  14267. this.skeletons.splice(index, 1);
  14268. }
  14269. return index;
  14270. };
  14271. Scene.prototype.removeLight = function (toRemove) {
  14272. var index = this.lights.indexOf(toRemove);
  14273. if (index !== -1) {
  14274. // Remove from the scene if mesh found
  14275. this.lights.splice(index, 1);
  14276. }
  14277. if (this.onLightRemoved) {
  14278. this.onLightRemoved(toRemove);
  14279. }
  14280. return index;
  14281. };
  14282. Scene.prototype.removeCamera = function (toRemove) {
  14283. var index = this.cameras.indexOf(toRemove);
  14284. if (index !== -1) {
  14285. // Remove from the scene if mesh found
  14286. this.cameras.splice(index, 1);
  14287. }
  14288. // Remove from activeCameras
  14289. var index2 = this.activeCameras.indexOf(toRemove);
  14290. if (index2 !== -1) {
  14291. // Remove from the scene if mesh found
  14292. this.activeCameras.splice(index2, 1);
  14293. }
  14294. // Reset the activeCamera
  14295. if (this.activeCamera === toRemove) {
  14296. if (this.cameras.length > 0) {
  14297. this.activeCamera = this.cameras[0];
  14298. }
  14299. else {
  14300. this.activeCamera = null;
  14301. }
  14302. }
  14303. if (this.onCameraRemoved) {
  14304. this.onCameraRemoved(toRemove);
  14305. }
  14306. return index;
  14307. };
  14308. Scene.prototype.addLight = function (newLight) {
  14309. newLight.uniqueId = this._uniqueIdCounter++;
  14310. var position = this.lights.push(newLight);
  14311. if (this.onNewLightAdded) {
  14312. this.onNewLightAdded(newLight, position, this);
  14313. }
  14314. };
  14315. Scene.prototype.addCamera = function (newCamera) {
  14316. newCamera.uniqueId = this._uniqueIdCounter++;
  14317. var position = this.cameras.push(newCamera);
  14318. if (this.onNewCameraAdded) {
  14319. this.onNewCameraAdded(newCamera, position, this);
  14320. }
  14321. };
  14322. /**
  14323. * Switch active camera
  14324. * @param {Camera} newCamera - new active camera
  14325. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  14326. */
  14327. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  14328. if (attachControl === void 0) { attachControl = true; }
  14329. var canvas = this._engine.getRenderingCanvas();
  14330. this.activeCamera.detachControl(canvas);
  14331. this.activeCamera = newCamera;
  14332. if (attachControl) {
  14333. newCamera.attachControl(canvas);
  14334. }
  14335. };
  14336. /**
  14337. * sets the active camera of the scene using its ID
  14338. * @param {string} id - the camera's ID
  14339. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14340. * @see activeCamera
  14341. */
  14342. Scene.prototype.setActiveCameraByID = function (id) {
  14343. var camera = this.getCameraByID(id);
  14344. if (camera) {
  14345. this.activeCamera = camera;
  14346. return camera;
  14347. }
  14348. return null;
  14349. };
  14350. /**
  14351. * sets the active camera of the scene using its name
  14352. * @param {string} name - the camera's name
  14353. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14354. * @see activeCamera
  14355. */
  14356. Scene.prototype.setActiveCameraByName = function (name) {
  14357. var camera = this.getCameraByName(name);
  14358. if (camera) {
  14359. this.activeCamera = camera;
  14360. return camera;
  14361. }
  14362. return null;
  14363. };
  14364. /**
  14365. * get a material using its id
  14366. * @param {string} the material's ID
  14367. * @return {BABYLON.Material|null} the material or null if none found.
  14368. */
  14369. Scene.prototype.getMaterialByID = function (id) {
  14370. for (var index = 0; index < this.materials.length; index++) {
  14371. if (this.materials[index].id === id) {
  14372. return this.materials[index];
  14373. }
  14374. }
  14375. return null;
  14376. };
  14377. /**
  14378. * get a material using its name
  14379. * @param {string} the material's name
  14380. * @return {BABYLON.Material|null} the material or null if none found.
  14381. */
  14382. Scene.prototype.getMaterialByName = function (name) {
  14383. for (var index = 0; index < this.materials.length; index++) {
  14384. if (this.materials[index].name === name) {
  14385. return this.materials[index];
  14386. }
  14387. }
  14388. return null;
  14389. };
  14390. Scene.prototype.getLensFlareSystemByName = function (name) {
  14391. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  14392. if (this.lensFlareSystems[index].name === name) {
  14393. return this.lensFlareSystems[index];
  14394. }
  14395. }
  14396. return null;
  14397. };
  14398. Scene.prototype.getCameraByID = function (id) {
  14399. for (var index = 0; index < this.cameras.length; index++) {
  14400. if (this.cameras[index].id === id) {
  14401. return this.cameras[index];
  14402. }
  14403. }
  14404. return null;
  14405. };
  14406. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  14407. for (var index = 0; index < this.cameras.length; index++) {
  14408. if (this.cameras[index].uniqueId === uniqueId) {
  14409. return this.cameras[index];
  14410. }
  14411. }
  14412. return null;
  14413. };
  14414. /**
  14415. * get a camera using its name
  14416. * @param {string} the camera's name
  14417. * @return {BABYLON.Camera|null} the camera or null if none found.
  14418. */
  14419. Scene.prototype.getCameraByName = function (name) {
  14420. for (var index = 0; index < this.cameras.length; index++) {
  14421. if (this.cameras[index].name === name) {
  14422. return this.cameras[index];
  14423. }
  14424. }
  14425. return null;
  14426. };
  14427. /**
  14428. * get a bone using its id
  14429. * @param {string} the bone's id
  14430. * @return {BABYLON.Bone|null} the bone or null if not found
  14431. */
  14432. Scene.prototype.getBoneByID = function (id) {
  14433. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  14434. var skeleton = this.skeletons[skeletonIndex];
  14435. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  14436. if (skeleton.bones[boneIndex].id === id) {
  14437. return skeleton.bones[boneIndex];
  14438. }
  14439. }
  14440. }
  14441. return null;
  14442. };
  14443. /**
  14444. * get a bone using its id
  14445. * @param {string} the bone's name
  14446. * @return {BABYLON.Bone|null} the bone or null if not found
  14447. */
  14448. Scene.prototype.getBoneByName = function (name) {
  14449. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  14450. var skeleton = this.skeletons[skeletonIndex];
  14451. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  14452. if (skeleton.bones[boneIndex].name === name) {
  14453. return skeleton.bones[boneIndex];
  14454. }
  14455. }
  14456. }
  14457. return null;
  14458. };
  14459. /**
  14460. * get a light node using its name
  14461. * @param {string} the light's name
  14462. * @return {BABYLON.Light|null} the light or null if none found.
  14463. */
  14464. Scene.prototype.getLightByName = function (name) {
  14465. for (var index = 0; index < this.lights.length; index++) {
  14466. if (this.lights[index].name === name) {
  14467. return this.lights[index];
  14468. }
  14469. }
  14470. return null;
  14471. };
  14472. /**
  14473. * get a light node using its ID
  14474. * @param {string} the light's id
  14475. * @return {BABYLON.Light|null} the light or null if none found.
  14476. */
  14477. Scene.prototype.getLightByID = function (id) {
  14478. for (var index = 0; index < this.lights.length; index++) {
  14479. if (this.lights[index].id === id) {
  14480. return this.lights[index];
  14481. }
  14482. }
  14483. return null;
  14484. };
  14485. /**
  14486. * get a light node using its scene-generated unique ID
  14487. * @param {number} the light's unique id
  14488. * @return {BABYLON.Light|null} the light or null if none found.
  14489. */
  14490. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  14491. for (var index = 0; index < this.lights.length; index++) {
  14492. if (this.lights[index].uniqueId === uniqueId) {
  14493. return this.lights[index];
  14494. }
  14495. }
  14496. return null;
  14497. };
  14498. /**
  14499. * get a particle system by id
  14500. * @param id {number} the particle system id
  14501. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  14502. */
  14503. Scene.prototype.getParticleSystemByID = function (id) {
  14504. for (var index = 0; index < this.particleSystems.length; index++) {
  14505. if (this.particleSystems[index].id === id) {
  14506. return this.particleSystems[index];
  14507. }
  14508. }
  14509. return null;
  14510. };
  14511. /**
  14512. * get a geometry using its ID
  14513. * @param {string} the geometry's id
  14514. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  14515. */
  14516. Scene.prototype.getGeometryByID = function (id) {
  14517. for (var index = 0; index < this._geometries.length; index++) {
  14518. if (this._geometries[index].id === id) {
  14519. return this._geometries[index];
  14520. }
  14521. }
  14522. return null;
  14523. };
  14524. /**
  14525. * add a new geometry to this scene.
  14526. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  14527. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  14528. * @return {boolean} was the geometry added or not
  14529. */
  14530. Scene.prototype.pushGeometry = function (geometry, force) {
  14531. if (!force && this.getGeometryByID(geometry.id)) {
  14532. return false;
  14533. }
  14534. this._geometries.push(geometry);
  14535. //notify the collision coordinator
  14536. this.collisionCoordinator.onGeometryAdded(geometry);
  14537. if (this.onGeometryAdded) {
  14538. this.onGeometryAdded(geometry);
  14539. }
  14540. return true;
  14541. };
  14542. /**
  14543. * Removes an existing geometry
  14544. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  14545. * @return {boolean} was the geometry removed or not
  14546. */
  14547. Scene.prototype.removeGeometry = function (geometry) {
  14548. var index = this._geometries.indexOf(geometry);
  14549. if (index > -1) {
  14550. this._geometries.splice(index, 1);
  14551. //notify the collision coordinator
  14552. this.collisionCoordinator.onGeometryDeleted(geometry);
  14553. if (this.onGeometryRemoved) {
  14554. this.onGeometryRemoved(geometry);
  14555. }
  14556. return true;
  14557. }
  14558. return false;
  14559. };
  14560. Scene.prototype.getGeometries = function () {
  14561. return this._geometries;
  14562. };
  14563. /**
  14564. * Get the first added mesh found of a given ID
  14565. * @param {string} id - the id to search for
  14566. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14567. */
  14568. Scene.prototype.getMeshByID = function (id) {
  14569. for (var index = 0; index < this.meshes.length; index++) {
  14570. if (this.meshes[index].id === id) {
  14571. return this.meshes[index];
  14572. }
  14573. }
  14574. return null;
  14575. };
  14576. /**
  14577. * Get a mesh with its auto-generated unique id
  14578. * @param {number} uniqueId - the unique id to search for
  14579. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14580. */
  14581. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  14582. for (var index = 0; index < this.meshes.length; index++) {
  14583. if (this.meshes[index].uniqueId === uniqueId) {
  14584. return this.meshes[index];
  14585. }
  14586. }
  14587. return null;
  14588. };
  14589. /**
  14590. * Get a the last added mesh found of a given ID
  14591. * @param {string} id - the id to search for
  14592. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14593. */
  14594. Scene.prototype.getLastMeshByID = function (id) {
  14595. for (var index = this.meshes.length - 1; index >= 0; index--) {
  14596. if (this.meshes[index].id === id) {
  14597. return this.meshes[index];
  14598. }
  14599. }
  14600. return null;
  14601. };
  14602. /**
  14603. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  14604. * @param {string} id - the id to search for
  14605. * @return {BABYLON.Node|null} the node found or null if not found at all.
  14606. */
  14607. Scene.prototype.getLastEntryByID = function (id) {
  14608. var index;
  14609. for (index = this.meshes.length - 1; index >= 0; index--) {
  14610. if (this.meshes[index].id === id) {
  14611. return this.meshes[index];
  14612. }
  14613. }
  14614. for (index = this.cameras.length - 1; index >= 0; index--) {
  14615. if (this.cameras[index].id === id) {
  14616. return this.cameras[index];
  14617. }
  14618. }
  14619. for (index = this.lights.length - 1; index >= 0; index--) {
  14620. if (this.lights[index].id === id) {
  14621. return this.lights[index];
  14622. }
  14623. }
  14624. return null;
  14625. };
  14626. Scene.prototype.getNodeByID = function (id) {
  14627. var mesh = this.getMeshByID(id);
  14628. if (mesh) {
  14629. return mesh;
  14630. }
  14631. var light = this.getLightByID(id);
  14632. if (light) {
  14633. return light;
  14634. }
  14635. var camera = this.getCameraByID(id);
  14636. if (camera) {
  14637. return camera;
  14638. }
  14639. var bone = this.getBoneByID(id);
  14640. return bone;
  14641. };
  14642. Scene.prototype.getNodeByName = function (name) {
  14643. var mesh = this.getMeshByName(name);
  14644. if (mesh) {
  14645. return mesh;
  14646. }
  14647. var light = this.getLightByName(name);
  14648. if (light) {
  14649. return light;
  14650. }
  14651. var camera = this.getCameraByName(name);
  14652. if (camera) {
  14653. return camera;
  14654. }
  14655. var bone = this.getBoneByName(name);
  14656. return bone;
  14657. };
  14658. Scene.prototype.getMeshByName = function (name) {
  14659. for (var index = 0; index < this.meshes.length; index++) {
  14660. if (this.meshes[index].name === name) {
  14661. return this.meshes[index];
  14662. }
  14663. }
  14664. return null;
  14665. };
  14666. Scene.prototype.getSoundByName = function (name) {
  14667. var index;
  14668. if (BABYLON.AudioEngine) {
  14669. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  14670. if (this.mainSoundTrack.soundCollection[index].name === name) {
  14671. return this.mainSoundTrack.soundCollection[index];
  14672. }
  14673. }
  14674. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  14675. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  14676. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  14677. return this.soundTracks[sdIndex].soundCollection[index];
  14678. }
  14679. }
  14680. }
  14681. }
  14682. return null;
  14683. };
  14684. Scene.prototype.getLastSkeletonByID = function (id) {
  14685. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  14686. if (this.skeletons[index].id === id) {
  14687. return this.skeletons[index];
  14688. }
  14689. }
  14690. return null;
  14691. };
  14692. Scene.prototype.getSkeletonById = function (id) {
  14693. for (var index = 0; index < this.skeletons.length; index++) {
  14694. if (this.skeletons[index].id === id) {
  14695. return this.skeletons[index];
  14696. }
  14697. }
  14698. return null;
  14699. };
  14700. Scene.prototype.getSkeletonByName = function (name) {
  14701. for (var index = 0; index < this.skeletons.length; index++) {
  14702. if (this.skeletons[index].name === name) {
  14703. return this.skeletons[index];
  14704. }
  14705. }
  14706. return null;
  14707. };
  14708. Scene.prototype.isActiveMesh = function (mesh) {
  14709. return (this._activeMeshes.indexOf(mesh) !== -1);
  14710. };
  14711. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  14712. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  14713. var material = subMesh.getMaterial();
  14714. if (mesh.showSubMeshesBoundingBox) {
  14715. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  14716. }
  14717. if (material) {
  14718. // Render targets
  14719. if (material.getRenderTargetTextures) {
  14720. if (this._processedMaterials.indexOf(material) === -1) {
  14721. this._processedMaterials.push(material);
  14722. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  14723. }
  14724. }
  14725. // Dispatch
  14726. this._activeIndices += subMesh.indexCount;
  14727. this._renderingManager.dispatch(subMesh);
  14728. }
  14729. }
  14730. };
  14731. Scene.prototype._evaluateActiveMeshes = function () {
  14732. this.activeCamera._activeMeshes.reset();
  14733. this._activeMeshes.reset();
  14734. this._renderingManager.reset();
  14735. this._processedMaterials.reset();
  14736. this._activeParticleSystems.reset();
  14737. this._activeSkeletons.reset();
  14738. this._softwareSkinnedMeshes.reset();
  14739. this._boundingBoxRenderer.reset();
  14740. this._edgesRenderers.reset();
  14741. if (!this._frustumPlanes) {
  14742. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14743. }
  14744. else {
  14745. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14746. }
  14747. // Meshes
  14748. var meshes;
  14749. var len;
  14750. if (this._selectionOctree) {
  14751. var selection = this._selectionOctree.select(this._frustumPlanes);
  14752. meshes = selection.data;
  14753. len = selection.length;
  14754. }
  14755. else {
  14756. len = this.meshes.length;
  14757. meshes = this.meshes;
  14758. }
  14759. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  14760. var mesh = meshes[meshIndex];
  14761. if (mesh.isBlocked) {
  14762. continue;
  14763. }
  14764. this._totalVertices += mesh.getTotalVertices();
  14765. if (!mesh.isReady() || !mesh.isEnabled()) {
  14766. continue;
  14767. }
  14768. mesh.computeWorldMatrix();
  14769. // Intersections
  14770. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  14771. this._meshesForIntersections.pushNoDuplicate(mesh);
  14772. }
  14773. // Switch to current LOD
  14774. var meshLOD = mesh.getLOD(this.activeCamera);
  14775. if (!meshLOD) {
  14776. continue;
  14777. }
  14778. mesh._preActivate();
  14779. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  14780. this._activeMeshes.push(mesh);
  14781. this.activeCamera._activeMeshes.push(mesh);
  14782. mesh._activate(this._renderId);
  14783. this._activeMesh(meshLOD);
  14784. }
  14785. }
  14786. // Particle systems
  14787. var beforeParticlesDate = BABYLON.Tools.Now;
  14788. if (this.particlesEnabled) {
  14789. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  14790. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  14791. var particleSystem = this.particleSystems[particleIndex];
  14792. if (!particleSystem.isStarted()) {
  14793. continue;
  14794. }
  14795. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  14796. this._activeParticleSystems.push(particleSystem);
  14797. particleSystem.animate();
  14798. }
  14799. }
  14800. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  14801. }
  14802. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  14803. };
  14804. Scene.prototype._activeMesh = function (mesh) {
  14805. if (mesh.skeleton && this.skeletonsEnabled) {
  14806. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  14807. if (!mesh.computeBonesUsingShaders) {
  14808. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  14809. }
  14810. }
  14811. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  14812. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  14813. }
  14814. if (mesh._edgesRenderer) {
  14815. this._edgesRenderers.push(mesh._edgesRenderer);
  14816. }
  14817. if (mesh && mesh.subMeshes) {
  14818. // Submeshes Octrees
  14819. var len;
  14820. var subMeshes;
  14821. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  14822. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  14823. len = intersections.length;
  14824. subMeshes = intersections.data;
  14825. }
  14826. else {
  14827. subMeshes = mesh.subMeshes;
  14828. len = subMeshes.length;
  14829. }
  14830. for (var subIndex = 0; subIndex < len; subIndex++) {
  14831. var subMesh = subMeshes[subIndex];
  14832. this._evaluateSubMesh(subMesh, mesh);
  14833. }
  14834. }
  14835. };
  14836. Scene.prototype.updateTransformMatrix = function (force) {
  14837. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  14838. };
  14839. Scene.prototype._renderForCamera = function (camera) {
  14840. var engine = this._engine;
  14841. this.activeCamera = camera;
  14842. if (!this.activeCamera)
  14843. throw new Error("Active camera not set");
  14844. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  14845. // Viewport
  14846. engine.setViewport(this.activeCamera.viewport);
  14847. // Camera
  14848. this.resetCachedMaterial();
  14849. this._renderId++;
  14850. this.updateTransformMatrix();
  14851. if (this.beforeCameraRender) {
  14852. this.beforeCameraRender(this.activeCamera);
  14853. }
  14854. // Meshes
  14855. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  14856. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  14857. this._evaluateActiveMeshes();
  14858. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  14859. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  14860. // Skeletons
  14861. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  14862. var skeleton = this._activeSkeletons.data[skeletonIndex];
  14863. skeleton.prepare();
  14864. }
  14865. // Software skinning
  14866. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  14867. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  14868. mesh.applySkeleton(mesh.skeleton);
  14869. }
  14870. // Render targets
  14871. var beforeRenderTargetDate = BABYLON.Tools.Now;
  14872. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  14873. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  14874. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  14875. var renderTarget = this._renderTargets.data[renderIndex];
  14876. if (renderTarget._shouldRender()) {
  14877. this._renderId++;
  14878. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  14879. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  14880. }
  14881. }
  14882. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  14883. this._renderId++;
  14884. engine.restoreDefaultFramebuffer(); // Restore back buffer
  14885. }
  14886. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  14887. // Prepare Frame
  14888. this.postProcessManager._prepareFrame();
  14889. var beforeRenderDate = BABYLON.Tools.Now;
  14890. // Backgrounds
  14891. var layerIndex;
  14892. var layer;
  14893. if (this.layers.length) {
  14894. engine.setDepthBuffer(false);
  14895. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  14896. layer = this.layers[layerIndex];
  14897. if (layer.isBackground) {
  14898. layer.render();
  14899. }
  14900. }
  14901. engine.setDepthBuffer(true);
  14902. }
  14903. // Render
  14904. BABYLON.Tools.StartPerformanceCounter("Main render");
  14905. this._renderingManager.render(null, null, true, true);
  14906. BABYLON.Tools.EndPerformanceCounter("Main render");
  14907. // Bounding boxes
  14908. this._boundingBoxRenderer.render();
  14909. // Edges
  14910. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14911. this._edgesRenderers.data[edgesRendererIndex].render();
  14912. }
  14913. // Lens flares
  14914. if (this.lensFlaresEnabled) {
  14915. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  14916. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  14917. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  14918. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  14919. lensFlareSystem.render();
  14920. }
  14921. }
  14922. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  14923. }
  14924. // Foregrounds
  14925. if (this.layers.length) {
  14926. engine.setDepthBuffer(false);
  14927. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  14928. layer = this.layers[layerIndex];
  14929. if (!layer.isBackground) {
  14930. layer.render();
  14931. }
  14932. }
  14933. engine.setDepthBuffer(true);
  14934. }
  14935. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  14936. // Finalize frame
  14937. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  14938. // Update camera
  14939. this.activeCamera._updateFromScene();
  14940. // Reset some special arrays
  14941. this._renderTargets.reset();
  14942. if (this.afterCameraRender) {
  14943. this.afterCameraRender(this.activeCamera);
  14944. }
  14945. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  14946. };
  14947. Scene.prototype._processSubCameras = function (camera) {
  14948. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  14949. this._renderForCamera(camera);
  14950. return;
  14951. }
  14952. // rig cameras
  14953. for (var index = 0; index < camera._rigCameras.length; index++) {
  14954. this._renderForCamera(camera._rigCameras[index]);
  14955. }
  14956. this.activeCamera = camera;
  14957. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  14958. // Update camera
  14959. this.activeCamera._updateFromScene();
  14960. };
  14961. Scene.prototype._checkIntersections = function () {
  14962. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  14963. var sourceMesh = this._meshesForIntersections.data[index];
  14964. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  14965. var action = sourceMesh.actionManager.actions[actionIndex];
  14966. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14967. var parameters = action.getTriggerParameter();
  14968. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  14969. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  14970. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  14971. if (areIntersecting && currentIntersectionInProgress === -1) {
  14972. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  14973. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14974. sourceMesh._intersectionsInProgress.push(otherMesh);
  14975. }
  14976. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14977. sourceMesh._intersectionsInProgress.push(otherMesh);
  14978. }
  14979. }
  14980. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  14981. //They intersected, and now they don't.
  14982. //is this trigger an exit trigger? execute an event.
  14983. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14984. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14985. }
  14986. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  14987. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14988. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  14989. }
  14990. }
  14991. }
  14992. }
  14993. }
  14994. };
  14995. Scene.prototype.render = function () {
  14996. var startDate = BABYLON.Tools.Now;
  14997. this._particlesDuration = 0;
  14998. this._spritesDuration = 0;
  14999. this._activeParticles = 0;
  15000. this._renderDuration = 0;
  15001. this._renderTargetsDuration = 0;
  15002. this._evaluateActiveMeshesDuration = 0;
  15003. this._totalVertices = 0;
  15004. this._activeIndices = 0;
  15005. this._activeBones = 0;
  15006. this.getEngine().resetDrawCalls();
  15007. this._meshesForIntersections.reset();
  15008. this.resetCachedMaterial();
  15009. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15010. // Actions
  15011. if (this.actionManager) {
  15012. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15013. }
  15014. //Simplification Queue
  15015. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15016. this.simplificationQueue.executeNext();
  15017. }
  15018. // Animations
  15019. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15020. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15021. this._animate();
  15022. // Physics
  15023. if (this._physicsEngine) {
  15024. BABYLON.Tools.StartPerformanceCounter("Physics");
  15025. this._physicsEngine._step(deltaTime / 1000.0);
  15026. BABYLON.Tools.EndPerformanceCounter("Physics");
  15027. }
  15028. // Before render
  15029. if (this.beforeRender) {
  15030. this.beforeRender();
  15031. }
  15032. var callbackIndex;
  15033. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15034. this._onBeforeRenderCallbacks[callbackIndex]();
  15035. }
  15036. // Customs render targets
  15037. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15038. var engine = this.getEngine();
  15039. var currentActiveCamera = this.activeCamera;
  15040. if (this.renderTargetsEnabled) {
  15041. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15042. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15043. var renderTarget = this.customRenderTargets[customIndex];
  15044. if (renderTarget._shouldRender()) {
  15045. this._renderId++;
  15046. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15047. if (!this.activeCamera)
  15048. throw new Error("Active camera not set");
  15049. // Viewport
  15050. engine.setViewport(this.activeCamera.viewport);
  15051. // Camera
  15052. this.updateTransformMatrix();
  15053. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15054. }
  15055. }
  15056. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15057. this._renderId++;
  15058. }
  15059. if (this.customRenderTargets.length > 0) {
  15060. engine.restoreDefaultFramebuffer();
  15061. }
  15062. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15063. this.activeCamera = currentActiveCamera;
  15064. // Procedural textures
  15065. if (this.proceduralTexturesEnabled) {
  15066. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15067. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15068. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15069. if (proceduralTexture._shouldRender()) {
  15070. proceduralTexture.render();
  15071. }
  15072. }
  15073. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15074. }
  15075. // Clear
  15076. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15077. // Shadows
  15078. if (this.shadowsEnabled) {
  15079. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15080. var light = this.lights[lightIndex];
  15081. var shadowGenerator = light.getShadowGenerator();
  15082. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15083. this._renderTargets.push(shadowGenerator.getShadowMap());
  15084. }
  15085. }
  15086. }
  15087. // Depth renderer
  15088. if (this._depthRenderer) {
  15089. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15090. }
  15091. // RenderPipeline
  15092. this.postProcessRenderPipelineManager.update();
  15093. // Multi-cameras?
  15094. if (this.activeCameras.length > 0) {
  15095. var currentRenderId = this._renderId;
  15096. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15097. this._renderId = currentRenderId;
  15098. if (cameraIndex > 0) {
  15099. this._engine.clear(0, false, true);
  15100. }
  15101. this._processSubCameras(this.activeCameras[cameraIndex]);
  15102. }
  15103. }
  15104. else {
  15105. if (!this.activeCamera) {
  15106. throw new Error("No camera defined");
  15107. }
  15108. this._processSubCameras(this.activeCamera);
  15109. }
  15110. // Intersection checks
  15111. this._checkIntersections();
  15112. // Update the audio listener attached to the camera
  15113. if (BABYLON.AudioEngine) {
  15114. this._updateAudioParameters();
  15115. }
  15116. // After render
  15117. if (this.afterRender) {
  15118. this.afterRender();
  15119. }
  15120. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15121. this._onAfterRenderCallbacks[callbackIndex]();
  15122. }
  15123. // Cleaning
  15124. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15125. this._toBeDisposed.data[index].dispose();
  15126. this._toBeDisposed[index] = null;
  15127. }
  15128. this._toBeDisposed.reset();
  15129. if (this.dumpNextRenderTargets) {
  15130. this.dumpNextRenderTargets = false;
  15131. }
  15132. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15133. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15134. };
  15135. Scene.prototype._updateAudioParameters = function () {
  15136. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15137. return;
  15138. }
  15139. var listeningCamera;
  15140. var audioEngine = BABYLON.Engine.audioEngine;
  15141. if (this.activeCameras.length > 0) {
  15142. listeningCamera = this.activeCameras[0];
  15143. }
  15144. else {
  15145. listeningCamera = this.activeCamera;
  15146. }
  15147. if (listeningCamera && audioEngine.canUseWebAudio) {
  15148. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15149. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15150. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15151. cameraDirection.normalize();
  15152. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15153. var i;
  15154. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15155. var sound = this.mainSoundTrack.soundCollection[i];
  15156. if (sound.useCustomAttenuation) {
  15157. sound.updateDistanceFromListener();
  15158. }
  15159. }
  15160. for (i = 0; i < this.soundTracks.length; i++) {
  15161. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15162. sound = this.soundTracks[i].soundCollection[j];
  15163. if (sound.useCustomAttenuation) {
  15164. sound.updateDistanceFromListener();
  15165. }
  15166. }
  15167. }
  15168. }
  15169. };
  15170. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15171. // Audio
  15172. get: function () {
  15173. return this._audioEnabled;
  15174. },
  15175. set: function (value) {
  15176. this._audioEnabled = value;
  15177. if (BABYLON.AudioEngine) {
  15178. if (this._audioEnabled) {
  15179. this._enableAudio();
  15180. }
  15181. else {
  15182. this._disableAudio();
  15183. }
  15184. }
  15185. },
  15186. enumerable: true,
  15187. configurable: true
  15188. });
  15189. Scene.prototype._disableAudio = function () {
  15190. var i;
  15191. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15192. this.mainSoundTrack.soundCollection[i].pause();
  15193. }
  15194. for (i = 0; i < this.soundTracks.length; i++) {
  15195. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15196. this.soundTracks[i].soundCollection[j].pause();
  15197. }
  15198. }
  15199. };
  15200. Scene.prototype._enableAudio = function () {
  15201. var i;
  15202. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15203. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15204. this.mainSoundTrack.soundCollection[i].play();
  15205. }
  15206. }
  15207. for (i = 0; i < this.soundTracks.length; i++) {
  15208. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15209. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15210. this.soundTracks[i].soundCollection[j].play();
  15211. }
  15212. }
  15213. }
  15214. };
  15215. Object.defineProperty(Scene.prototype, "headphone", {
  15216. get: function () {
  15217. return this._headphone;
  15218. },
  15219. set: function (value) {
  15220. this._headphone = value;
  15221. if (BABYLON.AudioEngine) {
  15222. if (this._headphone) {
  15223. this._switchAudioModeForHeadphones();
  15224. }
  15225. else {
  15226. this._switchAudioModeForNormalSpeakers();
  15227. }
  15228. }
  15229. },
  15230. enumerable: true,
  15231. configurable: true
  15232. });
  15233. Scene.prototype._switchAudioModeForHeadphones = function () {
  15234. this.mainSoundTrack.switchPanningModelToHRTF();
  15235. for (var i = 0; i < this.soundTracks.length; i++) {
  15236. this.soundTracks[i].switchPanningModelToHRTF();
  15237. }
  15238. };
  15239. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  15240. this.mainSoundTrack.switchPanningModelToEqualPower();
  15241. for (var i = 0; i < this.soundTracks.length; i++) {
  15242. this.soundTracks[i].switchPanningModelToEqualPower();
  15243. }
  15244. };
  15245. Scene.prototype.enableDepthRenderer = function () {
  15246. if (this._depthRenderer) {
  15247. return this._depthRenderer;
  15248. }
  15249. this._depthRenderer = new BABYLON.DepthRenderer(this);
  15250. return this._depthRenderer;
  15251. };
  15252. Scene.prototype.disableDepthRenderer = function () {
  15253. if (!this._depthRenderer) {
  15254. return;
  15255. }
  15256. this._depthRenderer.dispose();
  15257. this._depthRenderer = null;
  15258. };
  15259. Scene.prototype.freezeMaterials = function () {
  15260. for (var i = 0; i < this.materials.length; i++) {
  15261. this.materials[i].freeze();
  15262. }
  15263. };
  15264. Scene.prototype.unfreezeMaterials = function () {
  15265. for (var i = 0; i < this.materials.length; i++) {
  15266. this.materials[i].unfreeze();
  15267. }
  15268. };
  15269. Scene.prototype.dispose = function () {
  15270. this.beforeRender = null;
  15271. this.afterRender = null;
  15272. this.skeletons = [];
  15273. this._boundingBoxRenderer.dispose();
  15274. if (this._depthRenderer) {
  15275. this._depthRenderer.dispose();
  15276. }
  15277. // Debug layer
  15278. this.debugLayer.hide();
  15279. // Events
  15280. if (this.onDispose) {
  15281. this.onDispose();
  15282. }
  15283. this._onBeforeRenderCallbacks = [];
  15284. this._onAfterRenderCallbacks = [];
  15285. this.detachControl();
  15286. // Release sounds & sounds tracks
  15287. if (BABYLON.AudioEngine) {
  15288. this.disposeSounds();
  15289. }
  15290. // Detach cameras
  15291. var canvas = this._engine.getRenderingCanvas();
  15292. var index;
  15293. for (index = 0; index < this.cameras.length; index++) {
  15294. this.cameras[index].detachControl(canvas);
  15295. }
  15296. // Release lights
  15297. while (this.lights.length) {
  15298. this.lights[0].dispose();
  15299. }
  15300. // Release meshes
  15301. while (this.meshes.length) {
  15302. this.meshes[0].dispose(true);
  15303. }
  15304. // Release cameras
  15305. while (this.cameras.length) {
  15306. this.cameras[0].dispose();
  15307. }
  15308. // Release materials
  15309. while (this.materials.length) {
  15310. this.materials[0].dispose();
  15311. }
  15312. // Release particles
  15313. while (this.particleSystems.length) {
  15314. this.particleSystems[0].dispose();
  15315. }
  15316. // Release sprites
  15317. while (this.spriteManagers.length) {
  15318. this.spriteManagers[0].dispose();
  15319. }
  15320. // Release layers
  15321. while (this.layers.length) {
  15322. this.layers[0].dispose();
  15323. }
  15324. // Release textures
  15325. while (this.textures.length) {
  15326. this.textures[0].dispose();
  15327. }
  15328. // Post-processes
  15329. this.postProcessManager.dispose();
  15330. // Physics
  15331. if (this._physicsEngine) {
  15332. this.disablePhysicsEngine();
  15333. }
  15334. // Remove from engine
  15335. index = this._engine.scenes.indexOf(this);
  15336. if (index > -1) {
  15337. this._engine.scenes.splice(index, 1);
  15338. }
  15339. this._engine.wipeCaches();
  15340. };
  15341. // Release sounds & sounds tracks
  15342. Scene.prototype.disposeSounds = function () {
  15343. this.mainSoundTrack.dispose();
  15344. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  15345. this.soundTracks[scIndex].dispose();
  15346. }
  15347. };
  15348. // Octrees
  15349. Scene.prototype.getWorldExtends = function () {
  15350. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15351. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15352. for (var index = 0; index < this.meshes.length; index++) {
  15353. var mesh = this.meshes[index];
  15354. mesh.computeWorldMatrix(true);
  15355. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  15356. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  15357. BABYLON.Tools.CheckExtends(minBox, min, max);
  15358. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15359. }
  15360. return {
  15361. min: min,
  15362. max: max
  15363. };
  15364. };
  15365. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  15366. if (maxCapacity === void 0) { maxCapacity = 64; }
  15367. if (maxDepth === void 0) { maxDepth = 2; }
  15368. if (!this._selectionOctree) {
  15369. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  15370. }
  15371. var worldExtends = this.getWorldExtends();
  15372. // Update octree
  15373. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  15374. return this._selectionOctree;
  15375. };
  15376. // Picking
  15377. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  15378. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  15379. var engine = this._engine;
  15380. if (!camera) {
  15381. if (!this.activeCamera)
  15382. throw new Error("Active camera not set");
  15383. camera = this.activeCamera;
  15384. }
  15385. var cameraViewport = camera.viewport;
  15386. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15387. // Moving coordinates to local viewport world
  15388. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15389. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15390. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  15391. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  15392. };
  15393. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  15394. var engine = this._engine;
  15395. if (!camera) {
  15396. if (!this.activeCamera)
  15397. throw new Error("Active camera not set");
  15398. camera = this.activeCamera;
  15399. }
  15400. var cameraViewport = camera.viewport;
  15401. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15402. var identity = BABYLON.Matrix.Identity();
  15403. // Moving coordinates to local viewport world
  15404. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15405. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15406. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  15407. };
  15408. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  15409. var pickingInfo = null;
  15410. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  15411. var mesh = this.meshes[meshIndex];
  15412. if (predicate) {
  15413. if (!predicate(mesh)) {
  15414. continue;
  15415. }
  15416. }
  15417. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  15418. continue;
  15419. }
  15420. var world = mesh.getWorldMatrix();
  15421. var ray = rayFunction(world);
  15422. var result = mesh.intersects(ray, fastCheck);
  15423. if (!result || !result.hit)
  15424. continue;
  15425. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15426. continue;
  15427. pickingInfo = result;
  15428. if (fastCheck) {
  15429. break;
  15430. }
  15431. }
  15432. return pickingInfo || new BABYLON.PickingInfo();
  15433. };
  15434. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  15435. var pickingInfo = null;
  15436. camera = camera || this.activeCamera;
  15437. if (this.spriteManagers.length > 0) {
  15438. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  15439. var spriteManager = this.spriteManagers[spriteIndex];
  15440. if (!spriteManager.isPickable) {
  15441. continue;
  15442. }
  15443. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  15444. if (!result || !result.hit)
  15445. continue;
  15446. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15447. continue;
  15448. pickingInfo = result;
  15449. if (fastCheck) {
  15450. break;
  15451. }
  15452. }
  15453. }
  15454. return pickingInfo || new BABYLON.PickingInfo();
  15455. };
  15456. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  15457. var _this = this;
  15458. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  15459. /// <param name="x">X position on screen</param>
  15460. /// <param name="y">Y position on screen</param>
  15461. /// <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>
  15462. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  15463. /// <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>
  15464. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  15465. };
  15466. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  15467. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  15468. /// <param name="x">X position on screen</param>
  15469. /// <param name="y">Y position on screen</param>
  15470. /// <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>
  15471. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  15472. /// <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>
  15473. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  15474. };
  15475. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  15476. var _this = this;
  15477. return this._internalPick(function (world) {
  15478. if (!_this._pickWithRayInverseMatrix) {
  15479. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  15480. }
  15481. world.invertToRef(_this._pickWithRayInverseMatrix);
  15482. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  15483. }, predicate, fastCheck);
  15484. };
  15485. Scene.prototype.setPointerOverMesh = function (mesh) {
  15486. if (this._pointerOverMesh === mesh) {
  15487. return;
  15488. }
  15489. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  15490. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  15491. }
  15492. this._pointerOverMesh = mesh;
  15493. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  15494. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  15495. }
  15496. };
  15497. Scene.prototype.getPointerOverMesh = function () {
  15498. return this._pointerOverMesh;
  15499. };
  15500. Scene.prototype.setPointerOverSprite = function (sprite) {
  15501. if (this._pointerOverSprite === sprite) {
  15502. return;
  15503. }
  15504. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  15505. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  15506. }
  15507. this._pointerOverSprite = sprite;
  15508. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  15509. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  15510. }
  15511. };
  15512. Scene.prototype.getPointerOverSprite = function () {
  15513. return this._pointerOverSprite;
  15514. };
  15515. // Physics
  15516. Scene.prototype.getPhysicsEngine = function () {
  15517. return this._physicsEngine;
  15518. };
  15519. /**
  15520. * Enables physics to the current scene
  15521. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  15522. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  15523. * @return {boolean} was the physics engine initialized
  15524. */
  15525. Scene.prototype.enablePhysics = function (gravity, plugin) {
  15526. if (this._physicsEngine) {
  15527. return true;
  15528. }
  15529. try {
  15530. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  15531. return true;
  15532. }
  15533. catch (e) {
  15534. BABYLON.Tools.Error(e.message);
  15535. return false;
  15536. }
  15537. };
  15538. Scene.prototype.disablePhysicsEngine = function () {
  15539. if (!this._physicsEngine) {
  15540. return;
  15541. }
  15542. this._physicsEngine.dispose();
  15543. this._physicsEngine = undefined;
  15544. };
  15545. Scene.prototype.isPhysicsEnabled = function () {
  15546. return this._physicsEngine !== undefined;
  15547. };
  15548. /**
  15549. *
  15550. * Sets the gravity of the physics engine (and NOT of the scene)
  15551. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  15552. */
  15553. Scene.prototype.setGravity = function (gravity) {
  15554. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  15555. if (!this._physicsEngine) {
  15556. return;
  15557. }
  15558. this._physicsEngine.setGravity(gravity);
  15559. };
  15560. /**
  15561. * Legacy support, using the new API
  15562. * @Deprecated
  15563. */
  15564. Scene.prototype.createCompoundImpostor = function (parts, options) {
  15565. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  15566. if (parts.parts) {
  15567. options = parts;
  15568. parts = parts.parts;
  15569. }
  15570. var mainMesh = parts[0].mesh;
  15571. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options);
  15572. for (var index = 1; index < parts.length; index++) {
  15573. var mesh = parts[index].mesh;
  15574. if (mesh.parent !== mainMesh) {
  15575. mesh.position = mesh.position.subtract(mainMesh.position);
  15576. mesh.parent = mainMesh;
  15577. }
  15578. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options);
  15579. }
  15580. mainMesh.physicsImpostor.forceUpdate();
  15581. };
  15582. Scene.prototype.deleteCompoundImpostor = function (compound) {
  15583. var mesh = compound.parts[0].mesh;
  15584. mesh.physicsImpostor.dispose(true);
  15585. mesh.physicsImpostor = null;
  15586. };
  15587. // Misc.
  15588. Scene.prototype.createDefaultCameraOrLight = function () {
  15589. // Light
  15590. if (this.lights.length === 0) {
  15591. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  15592. }
  15593. // Camera
  15594. if (!this.activeCamera) {
  15595. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  15596. // Compute position
  15597. var worldExtends = this.getWorldExtends();
  15598. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  15599. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  15600. camera.setTarget(worldCenter);
  15601. this.activeCamera = camera;
  15602. }
  15603. };
  15604. // Tags
  15605. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  15606. if (tagsQuery === undefined) {
  15607. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  15608. return list;
  15609. }
  15610. var listByTags = [];
  15611. forEach = forEach || (function (item) { return; });
  15612. for (var i in list) {
  15613. var item = list[i];
  15614. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  15615. listByTags.push(item);
  15616. forEach(item);
  15617. }
  15618. }
  15619. return listByTags;
  15620. };
  15621. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  15622. return this._getByTags(this.meshes, tagsQuery, forEach);
  15623. };
  15624. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  15625. return this._getByTags(this.cameras, tagsQuery, forEach);
  15626. };
  15627. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  15628. return this._getByTags(this.lights, tagsQuery, forEach);
  15629. };
  15630. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  15631. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  15632. };
  15633. // Statics
  15634. Scene._FOGMODE_NONE = 0;
  15635. Scene._FOGMODE_EXP = 1;
  15636. Scene._FOGMODE_EXP2 = 2;
  15637. Scene._FOGMODE_LINEAR = 3;
  15638. Scene.MinDeltaTime = 1.0;
  15639. Scene.MaxDeltaTime = 1000.0;
  15640. return Scene;
  15641. })();
  15642. BABYLON.Scene = Scene;
  15643. })(BABYLON || (BABYLON = {}));
  15644. var BABYLON;
  15645. (function (BABYLON) {
  15646. var VertexBuffer = (function () {
  15647. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  15648. if (engine instanceof BABYLON.Mesh) {
  15649. this._engine = engine.getScene().getEngine();
  15650. }
  15651. else {
  15652. this._engine = engine;
  15653. }
  15654. this._updatable = updatable;
  15655. this._data = data;
  15656. if (!postponeInternalCreation) {
  15657. this.create();
  15658. }
  15659. this._kind = kind;
  15660. if (stride) {
  15661. this._strideSize = stride;
  15662. return;
  15663. }
  15664. // Deduce stride from kind
  15665. switch (kind) {
  15666. case VertexBuffer.PositionKind:
  15667. this._strideSize = 3;
  15668. break;
  15669. case VertexBuffer.NormalKind:
  15670. this._strideSize = 3;
  15671. break;
  15672. case VertexBuffer.UVKind:
  15673. case VertexBuffer.UV2Kind:
  15674. case VertexBuffer.UV3Kind:
  15675. case VertexBuffer.UV4Kind:
  15676. case VertexBuffer.UV5Kind:
  15677. case VertexBuffer.UV6Kind:
  15678. this._strideSize = 2;
  15679. break;
  15680. case VertexBuffer.ColorKind:
  15681. this._strideSize = 4;
  15682. break;
  15683. case VertexBuffer.MatricesIndicesKind:
  15684. case VertexBuffer.MatricesIndicesExtraKind:
  15685. this._strideSize = 4;
  15686. break;
  15687. case VertexBuffer.MatricesWeightsKind:
  15688. case VertexBuffer.MatricesWeightsExtraKind:
  15689. this._strideSize = 4;
  15690. break;
  15691. }
  15692. }
  15693. // Properties
  15694. VertexBuffer.prototype.isUpdatable = function () {
  15695. return this._updatable;
  15696. };
  15697. VertexBuffer.prototype.getData = function () {
  15698. return this._data;
  15699. };
  15700. VertexBuffer.prototype.getBuffer = function () {
  15701. return this._buffer;
  15702. };
  15703. VertexBuffer.prototype.getStrideSize = function () {
  15704. return this._strideSize;
  15705. };
  15706. // Methods
  15707. VertexBuffer.prototype.create = function (data) {
  15708. if (!data && this._buffer) {
  15709. return; // nothing to do
  15710. }
  15711. data = data || this._data;
  15712. if (!this._buffer) {
  15713. if (this._updatable) {
  15714. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  15715. }
  15716. else {
  15717. this._buffer = this._engine.createVertexBuffer(data);
  15718. }
  15719. }
  15720. if (this._updatable) {
  15721. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  15722. this._data = data;
  15723. }
  15724. };
  15725. VertexBuffer.prototype.update = function (data) {
  15726. this.create(data);
  15727. };
  15728. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  15729. if (!this._buffer) {
  15730. return;
  15731. }
  15732. if (this._updatable) {
  15733. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  15734. this._data = null;
  15735. }
  15736. };
  15737. VertexBuffer.prototype.dispose = function () {
  15738. if (!this._buffer) {
  15739. return;
  15740. }
  15741. if (this._engine._releaseBuffer(this._buffer)) {
  15742. this._buffer = null;
  15743. }
  15744. };
  15745. Object.defineProperty(VertexBuffer, "PositionKind", {
  15746. get: function () {
  15747. return VertexBuffer._PositionKind;
  15748. },
  15749. enumerable: true,
  15750. configurable: true
  15751. });
  15752. Object.defineProperty(VertexBuffer, "NormalKind", {
  15753. get: function () {
  15754. return VertexBuffer._NormalKind;
  15755. },
  15756. enumerable: true,
  15757. configurable: true
  15758. });
  15759. Object.defineProperty(VertexBuffer, "UVKind", {
  15760. get: function () {
  15761. return VertexBuffer._UVKind;
  15762. },
  15763. enumerable: true,
  15764. configurable: true
  15765. });
  15766. Object.defineProperty(VertexBuffer, "UV2Kind", {
  15767. get: function () {
  15768. return VertexBuffer._UV2Kind;
  15769. },
  15770. enumerable: true,
  15771. configurable: true
  15772. });
  15773. Object.defineProperty(VertexBuffer, "UV3Kind", {
  15774. get: function () {
  15775. return VertexBuffer._UV3Kind;
  15776. },
  15777. enumerable: true,
  15778. configurable: true
  15779. });
  15780. Object.defineProperty(VertexBuffer, "UV4Kind", {
  15781. get: function () {
  15782. return VertexBuffer._UV4Kind;
  15783. },
  15784. enumerable: true,
  15785. configurable: true
  15786. });
  15787. Object.defineProperty(VertexBuffer, "UV5Kind", {
  15788. get: function () {
  15789. return VertexBuffer._UV5Kind;
  15790. },
  15791. enumerable: true,
  15792. configurable: true
  15793. });
  15794. Object.defineProperty(VertexBuffer, "UV6Kind", {
  15795. get: function () {
  15796. return VertexBuffer._UV6Kind;
  15797. },
  15798. enumerable: true,
  15799. configurable: true
  15800. });
  15801. Object.defineProperty(VertexBuffer, "ColorKind", {
  15802. get: function () {
  15803. return VertexBuffer._ColorKind;
  15804. },
  15805. enumerable: true,
  15806. configurable: true
  15807. });
  15808. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  15809. get: function () {
  15810. return VertexBuffer._MatricesIndicesKind;
  15811. },
  15812. enumerable: true,
  15813. configurable: true
  15814. });
  15815. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  15816. get: function () {
  15817. return VertexBuffer._MatricesWeightsKind;
  15818. },
  15819. enumerable: true,
  15820. configurable: true
  15821. });
  15822. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  15823. get: function () {
  15824. return VertexBuffer._MatricesIndicesExtraKind;
  15825. },
  15826. enumerable: true,
  15827. configurable: true
  15828. });
  15829. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  15830. get: function () {
  15831. return VertexBuffer._MatricesWeightsExtraKind;
  15832. },
  15833. enumerable: true,
  15834. configurable: true
  15835. });
  15836. // Enums
  15837. VertexBuffer._PositionKind = "position";
  15838. VertexBuffer._NormalKind = "normal";
  15839. VertexBuffer._UVKind = "uv";
  15840. VertexBuffer._UV2Kind = "uv2";
  15841. VertexBuffer._UV3Kind = "uv3";
  15842. VertexBuffer._UV4Kind = "uv4";
  15843. VertexBuffer._UV5Kind = "uv5";
  15844. VertexBuffer._UV6Kind = "uv6";
  15845. VertexBuffer._ColorKind = "color";
  15846. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  15847. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  15848. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  15849. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  15850. return VertexBuffer;
  15851. })();
  15852. BABYLON.VertexBuffer = VertexBuffer;
  15853. })(BABYLON || (BABYLON = {}));
  15854. var BABYLON;
  15855. (function (BABYLON) {
  15856. /**
  15857. * Creates an instance based on a source mesh.
  15858. */
  15859. var InstancedMesh = (function (_super) {
  15860. __extends(InstancedMesh, _super);
  15861. function InstancedMesh(name, source) {
  15862. _super.call(this, name, source.getScene());
  15863. source.instances.push(this);
  15864. this._sourceMesh = source;
  15865. this.position.copyFrom(source.position);
  15866. this.rotation.copyFrom(source.rotation);
  15867. this.scaling.copyFrom(source.scaling);
  15868. if (source.rotationQuaternion) {
  15869. this.rotationQuaternion = source.rotationQuaternion.clone();
  15870. }
  15871. this.infiniteDistance = source.infiniteDistance;
  15872. this.setPivotMatrix(source.getPivotMatrix());
  15873. this.refreshBoundingInfo();
  15874. this._syncSubMeshes();
  15875. }
  15876. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  15877. // Methods
  15878. get: function () {
  15879. return this._sourceMesh.receiveShadows;
  15880. },
  15881. enumerable: true,
  15882. configurable: true
  15883. });
  15884. Object.defineProperty(InstancedMesh.prototype, "material", {
  15885. get: function () {
  15886. return this._sourceMesh.material;
  15887. },
  15888. enumerable: true,
  15889. configurable: true
  15890. });
  15891. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  15892. get: function () {
  15893. return this._sourceMesh.visibility;
  15894. },
  15895. enumerable: true,
  15896. configurable: true
  15897. });
  15898. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  15899. get: function () {
  15900. return this._sourceMesh.skeleton;
  15901. },
  15902. enumerable: true,
  15903. configurable: true
  15904. });
  15905. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  15906. get: function () {
  15907. return this._sourceMesh.renderingGroupId;
  15908. },
  15909. enumerable: true,
  15910. configurable: true
  15911. });
  15912. InstancedMesh.prototype.getTotalVertices = function () {
  15913. return this._sourceMesh.getTotalVertices();
  15914. };
  15915. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  15916. get: function () {
  15917. return this._sourceMesh;
  15918. },
  15919. enumerable: true,
  15920. configurable: true
  15921. });
  15922. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15923. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  15924. };
  15925. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  15926. return this._sourceMesh.isVerticesDataPresent(kind);
  15927. };
  15928. InstancedMesh.prototype.getIndices = function () {
  15929. return this._sourceMesh.getIndices();
  15930. };
  15931. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  15932. get: function () {
  15933. return this._sourceMesh._positions;
  15934. },
  15935. enumerable: true,
  15936. configurable: true
  15937. });
  15938. InstancedMesh.prototype.refreshBoundingInfo = function () {
  15939. var meshBB = this._sourceMesh.getBoundingInfo();
  15940. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  15941. this._updateBoundingInfo();
  15942. };
  15943. InstancedMesh.prototype._preActivate = function () {
  15944. if (this._currentLOD) {
  15945. this._currentLOD._preActivate();
  15946. }
  15947. };
  15948. InstancedMesh.prototype._activate = function (renderId) {
  15949. if (this._currentLOD) {
  15950. this._currentLOD._registerInstanceForRenderId(this, renderId);
  15951. }
  15952. };
  15953. InstancedMesh.prototype.getLOD = function (camera) {
  15954. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  15955. if (this._currentLOD === this.sourceMesh) {
  15956. return this;
  15957. }
  15958. return this._currentLOD;
  15959. };
  15960. InstancedMesh.prototype._syncSubMeshes = function () {
  15961. this.releaseSubMeshes();
  15962. if (this._sourceMesh.subMeshes) {
  15963. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  15964. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  15965. }
  15966. }
  15967. };
  15968. InstancedMesh.prototype._generatePointsArray = function () {
  15969. return this._sourceMesh._generatePointsArray();
  15970. };
  15971. // Clone
  15972. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15973. var result = this._sourceMesh.createInstance(name);
  15974. // Deep copy
  15975. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  15976. // Bounding info
  15977. this.refreshBoundingInfo();
  15978. // Parent
  15979. if (newParent) {
  15980. result.parent = newParent;
  15981. }
  15982. if (!doNotCloneChildren) {
  15983. // Children
  15984. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15985. var mesh = this.getScene().meshes[index];
  15986. if (mesh.parent === this) {
  15987. mesh.clone(mesh.name, result);
  15988. }
  15989. }
  15990. }
  15991. result.computeWorldMatrix(true);
  15992. return result;
  15993. };
  15994. // Dispoe
  15995. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  15996. // Remove from mesh
  15997. var index = this._sourceMesh.instances.indexOf(this);
  15998. this._sourceMesh.instances.splice(index, 1);
  15999. _super.prototype.dispose.call(this, doNotRecurse);
  16000. };
  16001. return InstancedMesh;
  16002. })(BABYLON.AbstractMesh);
  16003. BABYLON.InstancedMesh = InstancedMesh;
  16004. })(BABYLON || (BABYLON = {}));
  16005. var BABYLON;
  16006. (function (BABYLON) {
  16007. var _InstancesBatch = (function () {
  16008. function _InstancesBatch() {
  16009. this.mustReturn = false;
  16010. this.visibleInstances = new Array();
  16011. this.renderSelf = new Array();
  16012. }
  16013. return _InstancesBatch;
  16014. })();
  16015. BABYLON._InstancesBatch = _InstancesBatch;
  16016. var Mesh = (function (_super) {
  16017. __extends(Mesh, _super);
  16018. /**
  16019. * @constructor
  16020. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16021. * @param {Scene} scene - The scene to add this mesh to.
  16022. * @param {Node} parent - The parent of this mesh, if it has one
  16023. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16024. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16025. * When false, achieved by calling a clone(), also passing False.
  16026. * This will make creation of children, recursive.
  16027. */
  16028. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  16029. if (parent === void 0) { parent = null; }
  16030. _super.call(this, name, scene);
  16031. // Members
  16032. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16033. this.instances = new Array();
  16034. this._LODLevels = new Array();
  16035. this._onBeforeRenderCallbacks = new Array();
  16036. this._onAfterRenderCallbacks = new Array();
  16037. this._visibleInstances = {};
  16038. this._renderIdForInstances = new Array();
  16039. this._batchCache = new _InstancesBatch();
  16040. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16041. this._sideOrientation = Mesh._DEFAULTSIDE;
  16042. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16043. if (source) {
  16044. // Geometry
  16045. if (source._geometry) {
  16046. source._geometry.applyToMesh(this);
  16047. }
  16048. // Deep copy
  16049. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16050. // Pivot
  16051. this.setPivotMatrix(source.getPivotMatrix());
  16052. this.id = name + "." + source.id;
  16053. // Material
  16054. this.material = source.material;
  16055. var index;
  16056. if (!doNotCloneChildren) {
  16057. // Children
  16058. for (index = 0; index < scene.meshes.length; index++) {
  16059. var mesh = scene.meshes[index];
  16060. if (mesh.parent === source) {
  16061. // doNotCloneChildren is always going to be False
  16062. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16063. }
  16064. }
  16065. }
  16066. // Particles
  16067. for (index = 0; index < scene.particleSystems.length; index++) {
  16068. var system = scene.particleSystems[index];
  16069. if (system.emitter === source) {
  16070. system.clone(system.name, this);
  16071. }
  16072. }
  16073. this.computeWorldMatrix(true);
  16074. }
  16075. // Parent
  16076. if (parent !== null) {
  16077. this.parent = parent;
  16078. }
  16079. }
  16080. Object.defineProperty(Mesh, "FRONTSIDE", {
  16081. get: function () {
  16082. return Mesh._FRONTSIDE;
  16083. },
  16084. enumerable: true,
  16085. configurable: true
  16086. });
  16087. Object.defineProperty(Mesh, "BACKSIDE", {
  16088. get: function () {
  16089. return Mesh._BACKSIDE;
  16090. },
  16091. enumerable: true,
  16092. configurable: true
  16093. });
  16094. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16095. get: function () {
  16096. return Mesh._DOUBLESIDE;
  16097. },
  16098. enumerable: true,
  16099. configurable: true
  16100. });
  16101. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16102. get: function () {
  16103. return Mesh._DEFAULTSIDE;
  16104. },
  16105. enumerable: true,
  16106. configurable: true
  16107. });
  16108. Object.defineProperty(Mesh, "NO_CAP", {
  16109. get: function () {
  16110. return Mesh._NO_CAP;
  16111. },
  16112. enumerable: true,
  16113. configurable: true
  16114. });
  16115. Object.defineProperty(Mesh, "CAP_START", {
  16116. get: function () {
  16117. return Mesh._CAP_START;
  16118. },
  16119. enumerable: true,
  16120. configurable: true
  16121. });
  16122. Object.defineProperty(Mesh, "CAP_END", {
  16123. get: function () {
  16124. return Mesh._CAP_END;
  16125. },
  16126. enumerable: true,
  16127. configurable: true
  16128. });
  16129. Object.defineProperty(Mesh, "CAP_ALL", {
  16130. get: function () {
  16131. return Mesh._CAP_ALL;
  16132. },
  16133. enumerable: true,
  16134. configurable: true
  16135. });
  16136. // Methods
  16137. /**
  16138. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16139. */
  16140. Mesh.prototype.toString = function (fullDetails) {
  16141. var ret = _super.prototype.toString.call(this, fullDetails);
  16142. ret += ", n vertices: " + this.getTotalVertices();
  16143. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16144. if (this.animations) {
  16145. for (var i = 0; i < this.animations.length; i++) {
  16146. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16147. }
  16148. }
  16149. if (fullDetails) {
  16150. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16151. }
  16152. return ret;
  16153. };
  16154. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16155. get: function () {
  16156. return this._LODLevels.length > 0;
  16157. },
  16158. enumerable: true,
  16159. configurable: true
  16160. });
  16161. Mesh.prototype._sortLODLevels = function () {
  16162. this._LODLevels.sort(function (a, b) {
  16163. if (a.distance < b.distance) {
  16164. return 1;
  16165. }
  16166. if (a.distance > b.distance) {
  16167. return -1;
  16168. }
  16169. return 0;
  16170. });
  16171. };
  16172. /**
  16173. * Add a mesh as LOD level triggered at the given distance.
  16174. * @param {number} distance - the distance from the center of the object to show this level
  16175. * @param {Mesh} mesh - the mesh to be added as LOD level
  16176. * @return {Mesh} this mesh (for chaining)
  16177. */
  16178. Mesh.prototype.addLODLevel = function (distance, mesh) {
  16179. if (mesh && mesh._masterMesh) {
  16180. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  16181. return this;
  16182. }
  16183. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  16184. this._LODLevels.push(level);
  16185. if (mesh) {
  16186. mesh._masterMesh = this;
  16187. }
  16188. this._sortLODLevels();
  16189. return this;
  16190. };
  16191. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  16192. for (var index = 0; index < this._LODLevels.length; index++) {
  16193. var level = this._LODLevels[index];
  16194. if (level.distance === distance) {
  16195. return level.mesh;
  16196. }
  16197. }
  16198. return null;
  16199. };
  16200. /**
  16201. * Remove a mesh from the LOD array
  16202. * @param {Mesh} mesh - the mesh to be removed.
  16203. * @return {Mesh} this mesh (for chaining)
  16204. */
  16205. Mesh.prototype.removeLODLevel = function (mesh) {
  16206. for (var index = 0; index < this._LODLevels.length; index++) {
  16207. if (this._LODLevels[index].mesh === mesh) {
  16208. this._LODLevels.splice(index, 1);
  16209. if (mesh) {
  16210. mesh._masterMesh = null;
  16211. }
  16212. }
  16213. }
  16214. this._sortLODLevels();
  16215. return this;
  16216. };
  16217. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  16218. if (!this._LODLevels || this._LODLevels.length === 0) {
  16219. return this;
  16220. }
  16221. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  16222. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  16223. if (this.onLODLevelSelection) {
  16224. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  16225. }
  16226. return this;
  16227. }
  16228. for (var index = 0; index < this._LODLevels.length; index++) {
  16229. var level = this._LODLevels[index];
  16230. if (level.distance < distanceToCamera) {
  16231. if (level.mesh) {
  16232. level.mesh._preActivate();
  16233. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16234. }
  16235. if (this.onLODLevelSelection) {
  16236. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  16237. }
  16238. return level.mesh;
  16239. }
  16240. }
  16241. if (this.onLODLevelSelection) {
  16242. this.onLODLevelSelection(distanceToCamera, this, this);
  16243. }
  16244. return this;
  16245. };
  16246. Object.defineProperty(Mesh.prototype, "geometry", {
  16247. get: function () {
  16248. return this._geometry;
  16249. },
  16250. enumerable: true,
  16251. configurable: true
  16252. });
  16253. Mesh.prototype.getTotalVertices = function () {
  16254. if (!this._geometry) {
  16255. return 0;
  16256. }
  16257. return this._geometry.getTotalVertices();
  16258. };
  16259. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16260. if (!this._geometry) {
  16261. return null;
  16262. }
  16263. return this._geometry.getVerticesData(kind, copyWhenShared);
  16264. };
  16265. Mesh.prototype.getVertexBuffer = function (kind) {
  16266. if (!this._geometry) {
  16267. return undefined;
  16268. }
  16269. return this._geometry.getVertexBuffer(kind);
  16270. };
  16271. Mesh.prototype.isVerticesDataPresent = function (kind) {
  16272. if (!this._geometry) {
  16273. if (this._delayInfo) {
  16274. return this._delayInfo.indexOf(kind) !== -1;
  16275. }
  16276. return false;
  16277. }
  16278. return this._geometry.isVerticesDataPresent(kind);
  16279. };
  16280. Mesh.prototype.getVerticesDataKinds = function () {
  16281. if (!this._geometry) {
  16282. var result = [];
  16283. if (this._delayInfo) {
  16284. for (var kind in this._delayInfo) {
  16285. result.push(kind);
  16286. }
  16287. }
  16288. return result;
  16289. }
  16290. return this._geometry.getVerticesDataKinds();
  16291. };
  16292. Mesh.prototype.getTotalIndices = function () {
  16293. if (!this._geometry) {
  16294. return 0;
  16295. }
  16296. return this._geometry.getTotalIndices();
  16297. };
  16298. Mesh.prototype.getIndices = function (copyWhenShared) {
  16299. if (!this._geometry) {
  16300. return [];
  16301. }
  16302. return this._geometry.getIndices(copyWhenShared);
  16303. };
  16304. Object.defineProperty(Mesh.prototype, "isBlocked", {
  16305. get: function () {
  16306. return this._masterMesh !== null && this._masterMesh !== undefined;
  16307. },
  16308. enumerable: true,
  16309. configurable: true
  16310. });
  16311. Mesh.prototype.isReady = function () {
  16312. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16313. return false;
  16314. }
  16315. return _super.prototype.isReady.call(this);
  16316. };
  16317. Mesh.prototype.isDisposed = function () {
  16318. return this._isDisposed;
  16319. };
  16320. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  16321. get: function () {
  16322. return this._sideOrientation;
  16323. },
  16324. set: function (sideO) {
  16325. this._sideOrientation = sideO;
  16326. },
  16327. enumerable: true,
  16328. configurable: true
  16329. });
  16330. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  16331. get: function () {
  16332. return this._areNormalsFrozen;
  16333. },
  16334. enumerable: true,
  16335. configurable: true
  16336. });
  16337. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  16338. Mesh.prototype.freezeNormals = function () {
  16339. this._areNormalsFrozen = true;
  16340. };
  16341. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  16342. Mesh.prototype.unfreezeNormals = function () {
  16343. this._areNormalsFrozen = false;
  16344. };
  16345. // Methods
  16346. Mesh.prototype._preActivate = function () {
  16347. var sceneRenderId = this.getScene().getRenderId();
  16348. if (this._preActivateId === sceneRenderId) {
  16349. return;
  16350. }
  16351. this._preActivateId = sceneRenderId;
  16352. this._visibleInstances = null;
  16353. };
  16354. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  16355. if (!this._visibleInstances) {
  16356. this._visibleInstances = {};
  16357. this._visibleInstances.defaultRenderId = renderId;
  16358. this._visibleInstances.selfDefaultRenderId = this._renderId;
  16359. }
  16360. if (!this._visibleInstances[renderId]) {
  16361. this._visibleInstances[renderId] = new Array();
  16362. }
  16363. this._visibleInstances[renderId].push(instance);
  16364. };
  16365. Mesh.prototype.refreshBoundingInfo = function () {
  16366. if (this._boundingInfo.isLocked) {
  16367. return;
  16368. }
  16369. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16370. if (data) {
  16371. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  16372. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16373. }
  16374. if (this.subMeshes) {
  16375. for (var index = 0; index < this.subMeshes.length; index++) {
  16376. this.subMeshes[index].refreshBoundingInfo();
  16377. }
  16378. }
  16379. this._updateBoundingInfo();
  16380. };
  16381. Mesh.prototype._createGlobalSubMesh = function () {
  16382. var totalVertices = this.getTotalVertices();
  16383. if (!totalVertices || !this.getIndices()) {
  16384. return null;
  16385. }
  16386. this.releaseSubMeshes();
  16387. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  16388. };
  16389. Mesh.prototype.subdivide = function (count) {
  16390. if (count < 1) {
  16391. return;
  16392. }
  16393. var totalIndices = this.getTotalIndices();
  16394. var subdivisionSize = (totalIndices / count) | 0;
  16395. var offset = 0;
  16396. // Ensure that subdivisionSize is a multiple of 3
  16397. while (subdivisionSize % 3 !== 0) {
  16398. subdivisionSize++;
  16399. }
  16400. this.releaseSubMeshes();
  16401. for (var index = 0; index < count; index++) {
  16402. if (offset >= totalIndices) {
  16403. break;
  16404. }
  16405. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  16406. offset += subdivisionSize;
  16407. }
  16408. this.synchronizeInstances();
  16409. };
  16410. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16411. if (!this._geometry) {
  16412. var vertexData = new BABYLON.VertexData();
  16413. vertexData.set(data, kind);
  16414. var scene = this.getScene();
  16415. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  16416. }
  16417. else {
  16418. this._geometry.setVerticesData(kind, data, updatable, stride);
  16419. }
  16420. };
  16421. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16422. if (!this._geometry) {
  16423. return;
  16424. }
  16425. if (!makeItUnique) {
  16426. this._geometry.updateVerticesData(kind, data, updateExtends);
  16427. }
  16428. else {
  16429. this.makeGeometryUnique();
  16430. this.updateVerticesData(kind, data, updateExtends, false);
  16431. }
  16432. };
  16433. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  16434. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  16435. if (!this._geometry) {
  16436. return;
  16437. }
  16438. if (!makeItUnique) {
  16439. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  16440. }
  16441. else {
  16442. this.makeGeometryUnique();
  16443. this.updateVerticesDataDirectly(kind, data, offset, false);
  16444. }
  16445. };
  16446. // Mesh positions update function :
  16447. // updates the mesh positions according to the positionFunction returned values.
  16448. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  16449. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  16450. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  16451. if (computeNormals === void 0) { computeNormals = true; }
  16452. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16453. positionFunction(positions);
  16454. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16455. if (computeNormals) {
  16456. var indices = this.getIndices();
  16457. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16458. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16459. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16460. }
  16461. };
  16462. Mesh.prototype.makeGeometryUnique = function () {
  16463. if (!this._geometry) {
  16464. return;
  16465. }
  16466. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  16467. geometry.applyToMesh(this);
  16468. };
  16469. Mesh.prototype.setIndices = function (indices, totalVertices) {
  16470. if (!this._geometry) {
  16471. var vertexData = new BABYLON.VertexData();
  16472. vertexData.indices = indices;
  16473. var scene = this.getScene();
  16474. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  16475. }
  16476. else {
  16477. this._geometry.setIndices(indices, totalVertices);
  16478. }
  16479. };
  16480. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  16481. var engine = this.getScene().getEngine();
  16482. // Wireframe
  16483. var indexToBind;
  16484. if (this._unIndexed) {
  16485. indexToBind = null;
  16486. }
  16487. else {
  16488. switch (fillMode) {
  16489. case BABYLON.Material.PointFillMode:
  16490. indexToBind = null;
  16491. break;
  16492. case BABYLON.Material.WireFrameFillMode:
  16493. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  16494. break;
  16495. default:
  16496. case BABYLON.Material.TriangleFillMode:
  16497. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  16498. break;
  16499. }
  16500. }
  16501. // VBOs
  16502. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  16503. };
  16504. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  16505. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  16506. return;
  16507. }
  16508. if (this.onBeforeDraw) {
  16509. this.onBeforeDraw();
  16510. }
  16511. var engine = this.getScene().getEngine();
  16512. // Draw order
  16513. switch (fillMode) {
  16514. case BABYLON.Material.PointFillMode:
  16515. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16516. break;
  16517. case BABYLON.Material.WireFrameFillMode:
  16518. if (this._unIndexed) {
  16519. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16520. }
  16521. else {
  16522. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  16523. }
  16524. break;
  16525. default:
  16526. if (this._unIndexed) {
  16527. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16528. }
  16529. else {
  16530. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  16531. }
  16532. }
  16533. };
  16534. Mesh.prototype.registerBeforeRender = function (func) {
  16535. this._onBeforeRenderCallbacks.push(func);
  16536. };
  16537. Mesh.prototype.unregisterBeforeRender = function (func) {
  16538. var index = this._onBeforeRenderCallbacks.indexOf(func);
  16539. if (index > -1) {
  16540. this._onBeforeRenderCallbacks.splice(index, 1);
  16541. }
  16542. };
  16543. Mesh.prototype.registerAfterRender = function (func) {
  16544. this._onAfterRenderCallbacks.push(func);
  16545. };
  16546. Mesh.prototype.unregisterAfterRender = function (func) {
  16547. var index = this._onAfterRenderCallbacks.indexOf(func);
  16548. if (index > -1) {
  16549. this._onAfterRenderCallbacks.splice(index, 1);
  16550. }
  16551. };
  16552. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  16553. var scene = this.getScene();
  16554. this._batchCache.mustReturn = false;
  16555. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  16556. this._batchCache.visibleInstances[subMeshId] = null;
  16557. if (this._visibleInstances) {
  16558. var currentRenderId = scene.getRenderId();
  16559. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  16560. var selfRenderId = this._renderId;
  16561. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  16562. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  16563. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  16564. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  16565. }
  16566. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  16567. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  16568. this._batchCache.mustReturn = true;
  16569. return this._batchCache;
  16570. }
  16571. if (currentRenderId !== selfRenderId) {
  16572. this._batchCache.renderSelf[subMeshId] = false;
  16573. }
  16574. }
  16575. this._renderIdForInstances[subMeshId] = currentRenderId;
  16576. }
  16577. return this._batchCache;
  16578. };
  16579. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  16580. var visibleInstances = batch.visibleInstances[subMesh._id];
  16581. var matricesCount = visibleInstances.length + 1;
  16582. var bufferSize = matricesCount * 16 * 4;
  16583. while (this._instancesBufferSize < bufferSize) {
  16584. this._instancesBufferSize *= 2;
  16585. }
  16586. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  16587. if (this._worldMatricesInstancesBuffer) {
  16588. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  16589. }
  16590. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  16591. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  16592. }
  16593. var offset = 0;
  16594. var instancesCount = 0;
  16595. var world = this.getWorldMatrix();
  16596. if (batch.renderSelf[subMesh._id]) {
  16597. world.copyToArray(this._worldMatricesInstancesArray, offset);
  16598. offset += 16;
  16599. instancesCount++;
  16600. }
  16601. if (visibleInstances) {
  16602. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  16603. var instance = visibleInstances[instanceIndex];
  16604. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  16605. offset += 16;
  16606. instancesCount++;
  16607. }
  16608. }
  16609. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  16610. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  16611. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  16612. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  16613. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  16614. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  16615. this._draw(subMesh, fillMode, instancesCount);
  16616. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  16617. };
  16618. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  16619. var scene = this.getScene();
  16620. var engine = scene.getEngine();
  16621. if (hardwareInstancedRendering) {
  16622. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  16623. }
  16624. else {
  16625. if (batch.renderSelf[subMesh._id]) {
  16626. // Draw
  16627. if (onBeforeDraw) {
  16628. onBeforeDraw(false, this.getWorldMatrix());
  16629. }
  16630. this._draw(subMesh, fillMode);
  16631. }
  16632. if (batch.visibleInstances[subMesh._id]) {
  16633. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  16634. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  16635. // World
  16636. var world = instance.getWorldMatrix();
  16637. if (onBeforeDraw) {
  16638. onBeforeDraw(true, world);
  16639. }
  16640. // Draw
  16641. this._draw(subMesh, fillMode);
  16642. }
  16643. }
  16644. }
  16645. };
  16646. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  16647. var scene = this.getScene();
  16648. // Managing instances
  16649. var batch = this._getInstancesRenderList(subMesh._id);
  16650. if (batch.mustReturn) {
  16651. return;
  16652. }
  16653. // Checking geometry state
  16654. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  16655. return;
  16656. }
  16657. var callbackIndex;
  16658. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  16659. this._onBeforeRenderCallbacks[callbackIndex](this);
  16660. }
  16661. var engine = scene.getEngine();
  16662. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  16663. // Material
  16664. var effectiveMaterial = subMesh.getMaterial();
  16665. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  16666. return;
  16667. }
  16668. // Outline - step 1
  16669. var savedDepthWrite = engine.getDepthWrite();
  16670. if (this.renderOutline) {
  16671. engine.setDepthWrite(false);
  16672. scene.getOutlineRenderer().render(subMesh, batch);
  16673. engine.setDepthWrite(savedDepthWrite);
  16674. }
  16675. effectiveMaterial._preBind();
  16676. var effect = effectiveMaterial.getEffect();
  16677. // Bind
  16678. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  16679. this._bind(subMesh, effect, fillMode);
  16680. var world = this.getWorldMatrix();
  16681. effectiveMaterial.bind(world, this);
  16682. // Alpha mode
  16683. if (enableAlphaMode) {
  16684. engine.setAlphaMode(effectiveMaterial.alphaMode);
  16685. }
  16686. // Draw
  16687. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  16688. if (isInstance) {
  16689. effectiveMaterial.bindOnlyWorldMatrix(world);
  16690. }
  16691. });
  16692. // Unbind
  16693. effectiveMaterial.unbind();
  16694. // Outline - step 2
  16695. if (this.renderOutline && savedDepthWrite) {
  16696. engine.setDepthWrite(true);
  16697. engine.setColorWrite(false);
  16698. scene.getOutlineRenderer().render(subMesh, batch);
  16699. engine.setColorWrite(true);
  16700. }
  16701. // Overlay
  16702. if (this.renderOverlay) {
  16703. var currentMode = engine.getAlphaMode();
  16704. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16705. scene.getOutlineRenderer().render(subMesh, batch, true);
  16706. engine.setAlphaMode(currentMode);
  16707. }
  16708. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  16709. this._onAfterRenderCallbacks[callbackIndex](this);
  16710. }
  16711. };
  16712. Mesh.prototype.getEmittedParticleSystems = function () {
  16713. var results = new Array();
  16714. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  16715. var particleSystem = this.getScene().particleSystems[index];
  16716. if (particleSystem.emitter === this) {
  16717. results.push(particleSystem);
  16718. }
  16719. }
  16720. return results;
  16721. };
  16722. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  16723. var results = new Array();
  16724. var descendants = this.getDescendants();
  16725. descendants.push(this);
  16726. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  16727. var particleSystem = this.getScene().particleSystems[index];
  16728. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  16729. results.push(particleSystem);
  16730. }
  16731. }
  16732. return results;
  16733. };
  16734. Mesh.prototype._checkDelayState = function () {
  16735. var _this = this;
  16736. var that = this;
  16737. var scene = this.getScene();
  16738. if (this._geometry) {
  16739. this._geometry.load(scene);
  16740. }
  16741. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16742. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  16743. scene._addPendingData(that);
  16744. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  16745. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  16746. if (data instanceof ArrayBuffer) {
  16747. _this._delayLoadingFunction(data, _this);
  16748. }
  16749. else {
  16750. _this._delayLoadingFunction(JSON.parse(data), _this);
  16751. }
  16752. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16753. scene._removePendingData(_this);
  16754. }, function () { }, scene.database, getBinaryData);
  16755. }
  16756. };
  16757. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  16758. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16759. return false;
  16760. }
  16761. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  16762. return false;
  16763. }
  16764. this._checkDelayState();
  16765. return true;
  16766. };
  16767. Mesh.prototype.setMaterialByID = function (id) {
  16768. var materials = this.getScene().materials;
  16769. var index;
  16770. for (index = 0; index < materials.length; index++) {
  16771. if (materials[index].id === id) {
  16772. this.material = materials[index];
  16773. return;
  16774. }
  16775. }
  16776. // Multi
  16777. var multiMaterials = this.getScene().multiMaterials;
  16778. for (index = 0; index < multiMaterials.length; index++) {
  16779. if (multiMaterials[index].id === id) {
  16780. this.material = multiMaterials[index];
  16781. return;
  16782. }
  16783. }
  16784. };
  16785. Mesh.prototype.getAnimatables = function () {
  16786. var results = [];
  16787. if (this.material) {
  16788. results.push(this.material);
  16789. }
  16790. if (this.skeleton) {
  16791. results.push(this.skeleton);
  16792. }
  16793. return results;
  16794. };
  16795. // Geometry
  16796. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  16797. // Position
  16798. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16799. return;
  16800. }
  16801. this._resetPointsArrayCache();
  16802. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16803. var temp = [];
  16804. var index;
  16805. for (index = 0; index < data.length; index += 3) {
  16806. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  16807. }
  16808. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  16809. // Normals
  16810. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16811. return;
  16812. }
  16813. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16814. temp = [];
  16815. for (index = 0; index < data.length; index += 3) {
  16816. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  16817. }
  16818. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  16819. // flip faces?
  16820. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  16821. this.flipFaces();
  16822. }
  16823. };
  16824. // Will apply current transform to mesh and reset world matrix
  16825. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  16826. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  16827. this.scaling.copyFromFloats(1, 1, 1);
  16828. this.position.copyFromFloats(0, 0, 0);
  16829. this.rotation.copyFromFloats(0, 0, 0);
  16830. //only if quaternion is already set
  16831. if (this.rotationQuaternion) {
  16832. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  16833. }
  16834. this._worldMatrix = BABYLON.Matrix.Identity();
  16835. };
  16836. // Cache
  16837. Mesh.prototype._resetPointsArrayCache = function () {
  16838. this._positions = null;
  16839. };
  16840. Mesh.prototype._generatePointsArray = function () {
  16841. if (this._positions)
  16842. return true;
  16843. this._positions = [];
  16844. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16845. if (!data) {
  16846. return false;
  16847. }
  16848. for (var index = 0; index < data.length; index += 3) {
  16849. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  16850. }
  16851. return true;
  16852. };
  16853. // Clone
  16854. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16855. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  16856. };
  16857. // Dispose
  16858. Mesh.prototype.dispose = function (doNotRecurse) {
  16859. if (this._geometry) {
  16860. this._geometry.releaseForMesh(this, true);
  16861. }
  16862. // Instances
  16863. if (this._worldMatricesInstancesBuffer) {
  16864. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  16865. this._worldMatricesInstancesBuffer = null;
  16866. }
  16867. while (this.instances.length) {
  16868. this.instances[0].dispose();
  16869. }
  16870. _super.prototype.dispose.call(this, doNotRecurse);
  16871. };
  16872. // Geometric tools
  16873. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  16874. var _this = this;
  16875. var scene = this.getScene();
  16876. var onload = function (img) {
  16877. // Getting height map data
  16878. var canvas = document.createElement("canvas");
  16879. var context = canvas.getContext("2d");
  16880. var heightMapWidth = img.width;
  16881. var heightMapHeight = img.height;
  16882. canvas.width = heightMapWidth;
  16883. canvas.height = heightMapHeight;
  16884. context.drawImage(img, 0, 0);
  16885. // Create VertexData from map data
  16886. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16887. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  16888. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  16889. //execute success callback, if set
  16890. if (onSuccess) {
  16891. onSuccess(_this);
  16892. }
  16893. };
  16894. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16895. };
  16896. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  16897. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  16898. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  16899. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16900. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  16901. return;
  16902. }
  16903. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16904. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16905. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16906. var position = BABYLON.Vector3.Zero();
  16907. var normal = BABYLON.Vector3.Zero();
  16908. var uv = BABYLON.Vector2.Zero();
  16909. for (var index = 0; index < positions.length; index += 3) {
  16910. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  16911. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  16912. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  16913. // Compute height
  16914. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  16915. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  16916. var pos = (u + v * heightMapWidth) * 4;
  16917. var r = buffer[pos] / 255.0;
  16918. var g = buffer[pos + 1] / 255.0;
  16919. var b = buffer[pos + 2] / 255.0;
  16920. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16921. normal.normalize();
  16922. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  16923. position = position.add(normal);
  16924. position.toArray(positions, index);
  16925. }
  16926. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  16927. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  16928. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  16929. };
  16930. Mesh.prototype.convertToFlatShadedMesh = function () {
  16931. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  16932. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  16933. var kinds = this.getVerticesDataKinds();
  16934. var vbs = [];
  16935. var data = [];
  16936. var newdata = [];
  16937. var updatableNormals = false;
  16938. var kindIndex;
  16939. var kind;
  16940. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16941. kind = kinds[kindIndex];
  16942. var vertexBuffer = this.getVertexBuffer(kind);
  16943. if (kind === BABYLON.VertexBuffer.NormalKind) {
  16944. updatableNormals = vertexBuffer.isUpdatable();
  16945. kinds.splice(kindIndex, 1);
  16946. kindIndex--;
  16947. continue;
  16948. }
  16949. vbs[kind] = vertexBuffer;
  16950. data[kind] = vbs[kind].getData();
  16951. newdata[kind] = [];
  16952. }
  16953. // Save previous submeshes
  16954. var previousSubmeshes = this.subMeshes.slice(0);
  16955. var indices = this.getIndices();
  16956. var totalIndices = this.getTotalIndices();
  16957. // Generating unique vertices per face
  16958. var index;
  16959. for (index = 0; index < totalIndices; index++) {
  16960. var vertexIndex = indices[index];
  16961. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16962. kind = kinds[kindIndex];
  16963. var stride = vbs[kind].getStrideSize();
  16964. for (var offset = 0; offset < stride; offset++) {
  16965. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16966. }
  16967. }
  16968. }
  16969. // Updating faces & normal
  16970. var normals = [];
  16971. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  16972. for (index = 0; index < totalIndices; index += 3) {
  16973. indices[index] = index;
  16974. indices[index + 1] = index + 1;
  16975. indices[index + 2] = index + 2;
  16976. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  16977. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  16978. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  16979. var p1p2 = p1.subtract(p2);
  16980. var p3p2 = p3.subtract(p2);
  16981. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16982. // Store same normals for every vertex
  16983. for (var localIndex = 0; localIndex < 3; localIndex++) {
  16984. normals.push(normal.x);
  16985. normals.push(normal.y);
  16986. normals.push(normal.z);
  16987. }
  16988. }
  16989. this.setIndices(indices);
  16990. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  16991. // Updating vertex buffers
  16992. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16993. kind = kinds[kindIndex];
  16994. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16995. }
  16996. // Updating submeshes
  16997. this.releaseSubMeshes();
  16998. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16999. var previousOne = previousSubmeshes[submeshIndex];
  17000. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17001. }
  17002. this.synchronizeInstances();
  17003. };
  17004. Mesh.prototype.convertToUnIndexedMesh = function () {
  17005. /// <summary>Remove indices by unfolding faces into buffers</summary>
  17006. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17007. var kinds = this.getVerticesDataKinds();
  17008. var vbs = [];
  17009. var data = [];
  17010. var newdata = [];
  17011. var updatableNormals = false;
  17012. var kindIndex;
  17013. var kind;
  17014. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17015. kind = kinds[kindIndex];
  17016. var vertexBuffer = this.getVertexBuffer(kind);
  17017. vbs[kind] = vertexBuffer;
  17018. data[kind] = vbs[kind].getData();
  17019. newdata[kind] = [];
  17020. }
  17021. // Save previous submeshes
  17022. var previousSubmeshes = this.subMeshes.slice(0);
  17023. var indices = this.getIndices();
  17024. var totalIndices = this.getTotalIndices();
  17025. // Generating unique vertices per face
  17026. var index;
  17027. for (index = 0; index < totalIndices; index++) {
  17028. var vertexIndex = indices[index];
  17029. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17030. kind = kinds[kindIndex];
  17031. var stride = vbs[kind].getStrideSize();
  17032. for (var offset = 0; offset < stride; offset++) {
  17033. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17034. }
  17035. }
  17036. }
  17037. // Updating indices
  17038. for (index = 0; index < totalIndices; index += 3) {
  17039. indices[index] = index;
  17040. indices[index + 1] = index + 1;
  17041. indices[index + 2] = index + 2;
  17042. }
  17043. this.setIndices(indices);
  17044. // Updating vertex buffers
  17045. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17046. kind = kinds[kindIndex];
  17047. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17048. }
  17049. // Updating submeshes
  17050. this.releaseSubMeshes();
  17051. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17052. var previousOne = previousSubmeshes[submeshIndex];
  17053. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17054. }
  17055. this._unIndexed = true;
  17056. this.synchronizeInstances();
  17057. };
  17058. // will inverse faces orientations, and invert normals too if specified
  17059. Mesh.prototype.flipFaces = function (flipNormals) {
  17060. if (flipNormals === void 0) { flipNormals = false; }
  17061. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  17062. var i;
  17063. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17064. for (i = 0; i < vertex_data.normals.length; i++) {
  17065. vertex_data.normals[i] *= -1;
  17066. }
  17067. }
  17068. var temp;
  17069. for (i = 0; i < vertex_data.indices.length; i += 3) {
  17070. // reassign indices
  17071. temp = vertex_data.indices[i + 1];
  17072. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  17073. vertex_data.indices[i + 2] = temp;
  17074. }
  17075. vertex_data.applyToMesh(this);
  17076. };
  17077. // Instances
  17078. Mesh.prototype.createInstance = function (name) {
  17079. return new BABYLON.InstancedMesh(name, this);
  17080. };
  17081. Mesh.prototype.synchronizeInstances = function () {
  17082. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  17083. var instance = this.instances[instanceIndex];
  17084. instance._syncSubMeshes();
  17085. }
  17086. };
  17087. /**
  17088. * Simplify the mesh according to the given array of settings.
  17089. * Function will return immediately and will simplify async.
  17090. * @param settings a collection of simplification settings.
  17091. * @param parallelProcessing should all levels calculate parallel or one after the other.
  17092. * @param type the type of simplification to run.
  17093. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  17094. */
  17095. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  17096. if (parallelProcessing === void 0) { parallelProcessing = true; }
  17097. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  17098. this.getScene().simplificationQueue.addTask({
  17099. settings: settings,
  17100. parallelProcessing: parallelProcessing,
  17101. mesh: this,
  17102. simplificationType: simplificationType,
  17103. successCallback: successCallback
  17104. });
  17105. };
  17106. /**
  17107. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  17108. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  17109. * This should be used together with the simplification to avoid disappearing triangles.
  17110. * @param successCallback an optional success callback to be called after the optimization finished.
  17111. */
  17112. Mesh.prototype.optimizeIndices = function (successCallback) {
  17113. var _this = this;
  17114. var indices = this.getIndices();
  17115. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17116. var vectorPositions = [];
  17117. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  17118. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  17119. }
  17120. var dupes = [];
  17121. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  17122. var realPos = vectorPositions.length - 1 - iteration;
  17123. var testedPosition = vectorPositions[realPos];
  17124. for (var j = 0; j < realPos; ++j) {
  17125. var againstPosition = vectorPositions[j];
  17126. if (testedPosition.equals(againstPosition)) {
  17127. dupes[realPos] = j;
  17128. break;
  17129. }
  17130. }
  17131. }, function () {
  17132. for (var i = 0; i < indices.length; ++i) {
  17133. indices[i] = dupes[indices[i]] || indices[i];
  17134. }
  17135. //indices are now reordered
  17136. var originalSubMeshes = _this.subMeshes.slice(0);
  17137. _this.setIndices(indices);
  17138. _this.subMeshes = originalSubMeshes;
  17139. if (successCallback) {
  17140. successCallback(_this);
  17141. }
  17142. });
  17143. };
  17144. // Statics
  17145. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  17146. var mesh = new Mesh(parsedMesh.name, scene);
  17147. mesh.id = parsedMesh.id;
  17148. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17149. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17150. if (parsedMesh.rotationQuaternion) {
  17151. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17152. }
  17153. else if (parsedMesh.rotation) {
  17154. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17155. }
  17156. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17157. if (parsedMesh.localMatrix) {
  17158. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17159. }
  17160. else if (parsedMesh.pivotMatrix) {
  17161. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17162. }
  17163. mesh.setEnabled(parsedMesh.isEnabled);
  17164. mesh.isVisible = parsedMesh.isVisible;
  17165. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17166. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17167. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17168. if (parsedMesh.applyFog !== undefined) {
  17169. mesh.applyFog = parsedMesh.applyFog;
  17170. }
  17171. if (parsedMesh.pickable !== undefined) {
  17172. mesh.isPickable = parsedMesh.pickable;
  17173. }
  17174. if (parsedMesh.alphaIndex !== undefined) {
  17175. mesh.alphaIndex = parsedMesh.alphaIndex;
  17176. }
  17177. mesh.receiveShadows = parsedMesh.receiveShadows;
  17178. mesh.billboardMode = parsedMesh.billboardMode;
  17179. if (parsedMesh.visibility !== undefined) {
  17180. mesh.visibility = parsedMesh.visibility;
  17181. }
  17182. mesh.checkCollisions = parsedMesh.checkCollisions;
  17183. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17184. // freezeWorldMatrix
  17185. if (parsedMesh.freezeWorldMatrix) {
  17186. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  17187. }
  17188. // Parent
  17189. if (parsedMesh.parentId) {
  17190. mesh._waitingParentId = parsedMesh.parentId;
  17191. }
  17192. // Actions
  17193. if (parsedMesh.actions !== undefined) {
  17194. mesh._waitingActions = parsedMesh.actions;
  17195. }
  17196. // Geometry
  17197. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17198. if (parsedMesh.delayLoadingFile) {
  17199. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17200. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17201. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17202. if (parsedMesh._binaryInfo) {
  17203. mesh._binaryInfo = parsedMesh._binaryInfo;
  17204. }
  17205. mesh._delayInfo = [];
  17206. if (parsedMesh.hasUVs) {
  17207. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17208. }
  17209. if (parsedMesh.hasUVs2) {
  17210. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17211. }
  17212. if (parsedMesh.hasUVs3) {
  17213. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  17214. }
  17215. if (parsedMesh.hasUVs4) {
  17216. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  17217. }
  17218. if (parsedMesh.hasUVs5) {
  17219. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  17220. }
  17221. if (parsedMesh.hasUVs6) {
  17222. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  17223. }
  17224. if (parsedMesh.hasColors) {
  17225. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17226. }
  17227. if (parsedMesh.hasMatricesIndices) {
  17228. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17229. }
  17230. if (parsedMesh.hasMatricesWeights) {
  17231. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17232. }
  17233. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  17234. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17235. mesh._checkDelayState();
  17236. }
  17237. }
  17238. else {
  17239. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  17240. }
  17241. // Material
  17242. if (parsedMesh.materialId) {
  17243. mesh.setMaterialByID(parsedMesh.materialId);
  17244. }
  17245. else {
  17246. mesh.material = null;
  17247. }
  17248. // Skeleton
  17249. if (parsedMesh.skeletonId > -1) {
  17250. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17251. if (parsedMesh.numBoneInfluencers) {
  17252. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  17253. }
  17254. }
  17255. // Animations
  17256. if (parsedMesh.animations) {
  17257. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17258. var parsedAnimation = parsedMesh.animations[animationIndex];
  17259. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17260. }
  17261. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  17262. }
  17263. if (parsedMesh.autoAnimate) {
  17264. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  17265. }
  17266. // Layer Mask
  17267. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17268. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17269. }
  17270. else {
  17271. mesh.layerMask = 0x0FFFFFFF;
  17272. }
  17273. // Instances
  17274. if (parsedMesh.instances) {
  17275. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17276. var parsedInstance = parsedMesh.instances[index];
  17277. var instance = mesh.createInstance(parsedInstance.name);
  17278. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17279. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17280. if (parsedInstance.rotationQuaternion) {
  17281. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17282. }
  17283. else if (parsedInstance.rotation) {
  17284. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17285. }
  17286. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17287. instance.checkCollisions = mesh.checkCollisions;
  17288. if (parsedMesh.animations) {
  17289. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17290. parsedAnimation = parsedMesh.animations[animationIndex];
  17291. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17292. }
  17293. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  17294. }
  17295. }
  17296. }
  17297. return mesh;
  17298. };
  17299. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  17300. return BABYLON.MeshBuilder.CreateRibbon(name, {
  17301. pathArray: pathArray,
  17302. closeArray: closeArray,
  17303. closePath: closePath,
  17304. offset: offset,
  17305. updatable: updatable,
  17306. sideOrientation: sideOrientation,
  17307. instance: instance
  17308. }, scene);
  17309. };
  17310. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  17311. var options = {
  17312. radius: radius,
  17313. tessellation: tessellation,
  17314. sideOrientation: sideOrientation,
  17315. updatable: updatable
  17316. };
  17317. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  17318. };
  17319. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  17320. var options = {
  17321. size: size,
  17322. sideOrientation: sideOrientation,
  17323. updatable: updatable
  17324. };
  17325. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  17326. };
  17327. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  17328. var options = {
  17329. segments: segments,
  17330. diameterX: diameter,
  17331. diameterY: diameter,
  17332. diameterZ: diameter,
  17333. sideOrientation: sideOrientation,
  17334. updatable: updatable
  17335. };
  17336. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  17337. };
  17338. // Cylinder and cone
  17339. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  17340. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  17341. if (scene !== undefined) {
  17342. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  17343. updatable = scene;
  17344. }
  17345. scene = subdivisions;
  17346. subdivisions = 1;
  17347. }
  17348. var options = {
  17349. height: height,
  17350. diameterTop: diameterTop,
  17351. diameterBottom: diameterBottom,
  17352. tessellation: tessellation,
  17353. subdivisions: subdivisions,
  17354. sideOrientation: sideOrientation,
  17355. updatable: updatable
  17356. };
  17357. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  17358. };
  17359. // Torus (Code from SharpDX.org)
  17360. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  17361. var options = {
  17362. diameter: diameter,
  17363. thickness: thickness,
  17364. tessellation: tessellation,
  17365. sideOrientation: sideOrientation,
  17366. updatable: updatable
  17367. };
  17368. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  17369. };
  17370. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  17371. var options = {
  17372. radius: radius,
  17373. tube: tube,
  17374. radialSegments: radialSegments,
  17375. tubularSegments: tubularSegments,
  17376. p: p,
  17377. q: q,
  17378. sideOrientation: sideOrientation,
  17379. updatable: updatable
  17380. };
  17381. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  17382. };
  17383. // Lines
  17384. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  17385. var options = {
  17386. points: points,
  17387. updatable: updatable,
  17388. instance: instance
  17389. };
  17390. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  17391. };
  17392. // Dashed Lines
  17393. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  17394. var options = {
  17395. points: points,
  17396. dashSize: dashSize,
  17397. gapSize: gapSize,
  17398. dashNb: dashNb,
  17399. updatable: updatable
  17400. };
  17401. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  17402. };
  17403. // Extrusion
  17404. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  17405. var options = {
  17406. shape: shape,
  17407. path: path,
  17408. scale: scale,
  17409. rotation: rotation,
  17410. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  17411. sideOrientation: sideOrientation,
  17412. instance: instance,
  17413. updatable: updatable
  17414. };
  17415. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  17416. };
  17417. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  17418. var options = {
  17419. shape: shape,
  17420. path: path,
  17421. scaleFunction: scaleFunction,
  17422. rotationFunction: rotationFunction,
  17423. ribbonCloseArray: ribbonCloseArray,
  17424. ribbonClosePath: ribbonClosePath,
  17425. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  17426. sideOrientation: sideOrientation,
  17427. instance: instance,
  17428. updatable: updatable
  17429. };
  17430. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  17431. };
  17432. // Lathe
  17433. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  17434. var options = {
  17435. shape: shape,
  17436. radius: radius,
  17437. tessellation: tessellation,
  17438. sideOrientation: sideOrientation,
  17439. updatable: updatable
  17440. };
  17441. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  17442. };
  17443. // Plane & ground
  17444. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  17445. var options = {
  17446. size: size,
  17447. width: size,
  17448. height: size,
  17449. sideOrientation: sideOrientation,
  17450. updatable: updatable
  17451. };
  17452. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  17453. };
  17454. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  17455. var options = {
  17456. width: width,
  17457. height: height,
  17458. subdivisions: subdivisions,
  17459. updatable: updatable
  17460. };
  17461. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  17462. };
  17463. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  17464. var options = {
  17465. xmin: xmin,
  17466. zmin: zmin,
  17467. xmax: xmax,
  17468. zmax: zmax,
  17469. subdivisions: subdivisions,
  17470. precision: precision,
  17471. updatable: updatable
  17472. };
  17473. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  17474. };
  17475. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  17476. var options = {
  17477. width: width,
  17478. height: height,
  17479. subdivisions: subdivisions,
  17480. minHeight: minHeight,
  17481. maxHeight: maxHeight,
  17482. updatable: updatable,
  17483. onReady: onReady
  17484. };
  17485. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  17486. };
  17487. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  17488. var options = {
  17489. path: path,
  17490. radius: radius,
  17491. tessellation: tessellation,
  17492. radiusFunction: radiusFunction,
  17493. arc: 1,
  17494. cap: cap,
  17495. updatable: updatable,
  17496. sideOrientation: sideOrientation,
  17497. instance: instance
  17498. };
  17499. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  17500. };
  17501. Mesh.CreatePolyhedron = function (name, options, scene) {
  17502. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  17503. };
  17504. Mesh.CreateIcoSphere = function (name, options, scene) {
  17505. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  17506. };
  17507. // Decals
  17508. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  17509. var options = {
  17510. position: position,
  17511. normal: normal,
  17512. size: size,
  17513. angle: angle
  17514. };
  17515. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  17516. };
  17517. // Skeletons
  17518. /**
  17519. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  17520. */
  17521. Mesh.prototype.setPositionsForCPUSkinning = function () {
  17522. var source;
  17523. if (!this._sourcePositions) {
  17524. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17525. this._sourcePositions = new Float32Array(source);
  17526. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  17527. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  17528. }
  17529. }
  17530. return this._sourcePositions;
  17531. };
  17532. /**
  17533. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  17534. */
  17535. Mesh.prototype.setNormalsForCPUSkinning = function () {
  17536. var source;
  17537. if (!this._sourceNormals) {
  17538. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17539. this._sourceNormals = new Float32Array(source);
  17540. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  17541. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  17542. }
  17543. }
  17544. return this._sourceNormals;
  17545. };
  17546. /**
  17547. * Update the vertex buffers by applying transformation from the bones
  17548. * @param {skeleton} skeleton to apply
  17549. */
  17550. Mesh.prototype.applySkeleton = function (skeleton) {
  17551. if (!this.geometry) {
  17552. return;
  17553. }
  17554. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  17555. return;
  17556. }
  17557. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  17558. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17559. return this;
  17560. }
  17561. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17562. return this;
  17563. }
  17564. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17565. return this;
  17566. }
  17567. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17568. return this;
  17569. }
  17570. if (!this._sourcePositions) {
  17571. this.setPositionsForCPUSkinning();
  17572. }
  17573. if (!this._sourceNormals) {
  17574. this.setNormalsForCPUSkinning();
  17575. }
  17576. // positionsData checks for not being Float32Array will only pass at most once
  17577. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17578. if (!(positionsData instanceof Float32Array)) {
  17579. positionsData = new Float32Array(positionsData);
  17580. }
  17581. // normalsData checks for not being Float32Array will only pass at most once
  17582. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17583. if (!(normalsData instanceof Float32Array)) {
  17584. normalsData = new Float32Array(normalsData);
  17585. }
  17586. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17587. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17588. var needExtras = this.numBoneInfluencers > 4;
  17589. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  17590. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  17591. var skeletonMatrices = skeleton.getTransformMatrices(this);
  17592. var tempVector3 = BABYLON.Vector3.Zero();
  17593. var finalMatrix = new BABYLON.Matrix();
  17594. var tempMatrix = new BABYLON.Matrix();
  17595. var matWeightIdx = 0;
  17596. var inf;
  17597. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  17598. var weight;
  17599. for (inf = 0; inf < 4; inf++) {
  17600. weight = matricesWeightsData[matWeightIdx + inf];
  17601. if (weight > 0) {
  17602. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  17603. finalMatrix.addToSelf(tempMatrix);
  17604. }
  17605. else
  17606. break;
  17607. }
  17608. if (needExtras) {
  17609. for (inf = 0; inf < 4; inf++) {
  17610. weight = matricesWeightsExtraData[matWeightIdx + inf];
  17611. if (weight > 0) {
  17612. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  17613. finalMatrix.addToSelf(tempMatrix);
  17614. }
  17615. else
  17616. break;
  17617. }
  17618. }
  17619. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  17620. tempVector3.toArray(positionsData, index);
  17621. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  17622. tempVector3.toArray(normalsData, index);
  17623. finalMatrix.reset();
  17624. }
  17625. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  17626. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  17627. return this;
  17628. };
  17629. // Tools
  17630. Mesh.MinMax = function (meshes) {
  17631. var minVector = null;
  17632. var maxVector = null;
  17633. for (var i in meshes) {
  17634. var mesh = meshes[i];
  17635. var boundingBox = mesh.getBoundingInfo().boundingBox;
  17636. if (!minVector) {
  17637. minVector = boundingBox.minimumWorld;
  17638. maxVector = boundingBox.maximumWorld;
  17639. continue;
  17640. }
  17641. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  17642. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  17643. }
  17644. return {
  17645. min: minVector,
  17646. max: maxVector
  17647. };
  17648. };
  17649. Mesh.Center = function (meshesOrMinMaxVector) {
  17650. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  17651. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  17652. };
  17653. /**
  17654. * Merge the array of meshes into a single mesh for performance reasons.
  17655. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  17656. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  17657. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  17658. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  17659. */
  17660. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  17661. if (disposeSource === void 0) { disposeSource = true; }
  17662. var index;
  17663. if (!allow32BitsIndices) {
  17664. var totalVertices = 0;
  17665. // Counting vertices
  17666. for (index = 0; index < meshes.length; index++) {
  17667. if (meshes[index]) {
  17668. totalVertices += meshes[index].getTotalVertices();
  17669. if (totalVertices > 65536) {
  17670. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  17671. return null;
  17672. }
  17673. }
  17674. }
  17675. }
  17676. // Merge
  17677. var vertexData;
  17678. var otherVertexData;
  17679. var source;
  17680. for (index = 0; index < meshes.length; index++) {
  17681. if (meshes[index]) {
  17682. meshes[index].computeWorldMatrix(true);
  17683. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  17684. otherVertexData.transform(meshes[index].getWorldMatrix());
  17685. if (vertexData) {
  17686. vertexData.merge(otherVertexData);
  17687. }
  17688. else {
  17689. vertexData = otherVertexData;
  17690. source = meshes[index];
  17691. }
  17692. }
  17693. }
  17694. if (!meshSubclass) {
  17695. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  17696. }
  17697. vertexData.applyToMesh(meshSubclass);
  17698. // Setting properties
  17699. meshSubclass.material = source.material;
  17700. meshSubclass.checkCollisions = source.checkCollisions;
  17701. // Cleaning
  17702. if (disposeSource) {
  17703. for (index = 0; index < meshes.length; index++) {
  17704. if (meshes[index]) {
  17705. meshes[index].dispose();
  17706. }
  17707. }
  17708. }
  17709. return meshSubclass;
  17710. };
  17711. // Consts
  17712. Mesh._FRONTSIDE = 0;
  17713. Mesh._BACKSIDE = 1;
  17714. Mesh._DOUBLESIDE = 2;
  17715. Mesh._DEFAULTSIDE = 0;
  17716. Mesh._NO_CAP = 0;
  17717. Mesh._CAP_START = 1;
  17718. Mesh._CAP_END = 2;
  17719. Mesh._CAP_ALL = 3;
  17720. return Mesh;
  17721. })(BABYLON.AbstractMesh);
  17722. BABYLON.Mesh = Mesh;
  17723. })(BABYLON || (BABYLON = {}));
  17724. var BABYLON;
  17725. (function (BABYLON) {
  17726. var SubMesh = (function () {
  17727. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  17728. if (createBoundingBox === void 0) { createBoundingBox = true; }
  17729. this.materialIndex = materialIndex;
  17730. this.verticesStart = verticesStart;
  17731. this.verticesCount = verticesCount;
  17732. this.indexStart = indexStart;
  17733. this.indexCount = indexCount;
  17734. this._renderId = 0;
  17735. this._mesh = mesh;
  17736. this._renderingMesh = renderingMesh || mesh;
  17737. mesh.subMeshes.push(this);
  17738. this._trianglePlanes = [];
  17739. this._id = mesh.subMeshes.length - 1;
  17740. if (createBoundingBox) {
  17741. this.refreshBoundingInfo();
  17742. mesh.computeWorldMatrix(true);
  17743. }
  17744. }
  17745. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  17746. get: function () {
  17747. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  17748. },
  17749. enumerable: true,
  17750. configurable: true
  17751. });
  17752. SubMesh.prototype.getBoundingInfo = function () {
  17753. if (this.IsGlobal) {
  17754. return this._mesh.getBoundingInfo();
  17755. }
  17756. return this._boundingInfo;
  17757. };
  17758. SubMesh.prototype.getMesh = function () {
  17759. return this._mesh;
  17760. };
  17761. SubMesh.prototype.getRenderingMesh = function () {
  17762. return this._renderingMesh;
  17763. };
  17764. SubMesh.prototype.getMaterial = function () {
  17765. var rootMaterial = this._renderingMesh.material;
  17766. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  17767. var multiMaterial = rootMaterial;
  17768. return multiMaterial.getSubMaterial(this.materialIndex);
  17769. }
  17770. if (!rootMaterial) {
  17771. return this._mesh.getScene().defaultMaterial;
  17772. }
  17773. return rootMaterial;
  17774. };
  17775. // Methods
  17776. SubMesh.prototype.refreshBoundingInfo = function () {
  17777. this._lastColliderWorldVertices = null;
  17778. if (this.IsGlobal) {
  17779. return;
  17780. }
  17781. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17782. if (!data) {
  17783. this._boundingInfo = this._mesh._boundingInfo;
  17784. return;
  17785. }
  17786. var indices = this._renderingMesh.getIndices();
  17787. var extend;
  17788. //is this the only submesh?
  17789. if (this.indexStart === 0 && this.indexCount === indices.length) {
  17790. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  17791. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  17792. }
  17793. else {
  17794. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  17795. }
  17796. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17797. };
  17798. SubMesh.prototype._checkCollision = function (collider) {
  17799. return this.getBoundingInfo()._checkCollision(collider);
  17800. };
  17801. SubMesh.prototype.updateBoundingInfo = function (world) {
  17802. if (!this.getBoundingInfo()) {
  17803. this.refreshBoundingInfo();
  17804. }
  17805. this.getBoundingInfo().update(world);
  17806. };
  17807. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  17808. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  17809. };
  17810. SubMesh.prototype.render = function (enableAlphaMode) {
  17811. this._renderingMesh.render(this, enableAlphaMode);
  17812. };
  17813. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  17814. if (!this._linesIndexBuffer) {
  17815. var linesIndices = [];
  17816. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  17817. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  17818. }
  17819. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  17820. this.linesIndexCount = linesIndices.length;
  17821. }
  17822. return this._linesIndexBuffer;
  17823. };
  17824. SubMesh.prototype.canIntersects = function (ray) {
  17825. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  17826. };
  17827. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  17828. var intersectInfo = null;
  17829. // Triangles test
  17830. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  17831. var p0 = positions[indices[index]];
  17832. var p1 = positions[indices[index + 1]];
  17833. var p2 = positions[indices[index + 2]];
  17834. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  17835. if (currentIntersectInfo) {
  17836. if (currentIntersectInfo.distance < 0) {
  17837. continue;
  17838. }
  17839. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17840. intersectInfo = currentIntersectInfo;
  17841. intersectInfo.faceId = index / 3;
  17842. if (fastCheck) {
  17843. break;
  17844. }
  17845. }
  17846. }
  17847. }
  17848. return intersectInfo;
  17849. };
  17850. // Clone
  17851. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  17852. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  17853. if (!this.IsGlobal) {
  17854. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  17855. }
  17856. return result;
  17857. };
  17858. // Dispose
  17859. SubMesh.prototype.dispose = function () {
  17860. if (this._linesIndexBuffer) {
  17861. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  17862. this._linesIndexBuffer = null;
  17863. }
  17864. // Remove from mesh
  17865. var index = this._mesh.subMeshes.indexOf(this);
  17866. this._mesh.subMeshes.splice(index, 1);
  17867. };
  17868. // Statics
  17869. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  17870. var minVertexIndex = Number.MAX_VALUE;
  17871. var maxVertexIndex = -Number.MAX_VALUE;
  17872. renderingMesh = renderingMesh || mesh;
  17873. var indices = renderingMesh.getIndices();
  17874. for (var index = startIndex; index < startIndex + indexCount; index++) {
  17875. var vertexIndex = indices[index];
  17876. if (vertexIndex < minVertexIndex)
  17877. minVertexIndex = vertexIndex;
  17878. if (vertexIndex > maxVertexIndex)
  17879. maxVertexIndex = vertexIndex;
  17880. }
  17881. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  17882. };
  17883. return SubMesh;
  17884. })();
  17885. BABYLON.SubMesh = SubMesh;
  17886. })(BABYLON || (BABYLON = {}));
  17887. var BABYLON;
  17888. (function (BABYLON) {
  17889. var MeshBuilder = (function () {
  17890. function MeshBuilder() {
  17891. }
  17892. /**
  17893. * Creates a box mesh.
  17894. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  17895. * The parameter "size" sets the size (float) of each box side (default 1).
  17896. * You can set some different box dimensions by using the parameters "width", "height" and "depth" (all by default have the same value than "size").
  17897. * 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).
  17898. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  17899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17900. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17901. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17902. */
  17903. MeshBuilder.CreateBox = function (name, options, scene) {
  17904. var box = new BABYLON.Mesh(name, scene);
  17905. var vertexData = BABYLON.VertexData.CreateBox(options);
  17906. vertexData.applyToMesh(box, options.updatable);
  17907. return box;
  17908. };
  17909. /**
  17910. * Creates a sphere mesh.
  17911. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  17912. * The parameter "diameter" sets the diameter size (float) of the sphere (default 1).
  17913. * 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").
  17914. * The parameter "segments" sets the sphere number of horizontal stripes (positive integer, default 32).
  17915. * 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
  17916. * 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).
  17917. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17918. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17919. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17920. */
  17921. MeshBuilder.CreateSphere = function (name, options, scene) {
  17922. var sphere = new BABYLON.Mesh(name, scene);
  17923. var vertexData = BABYLON.VertexData.CreateSphere(options);
  17924. vertexData.applyToMesh(sphere, options.updatable);
  17925. return sphere;
  17926. };
  17927. /**
  17928. * Creates a plane polygonal mesh. By default, this is a disc.
  17929. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  17930. * The parameter "radius" sets the radius size (float) of the polygon (default 0.5).
  17931. * 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.
  17932. * 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
  17933. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17934. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17935. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17936. */
  17937. MeshBuilder.CreateDisc = function (name, options, scene) {
  17938. var disc = new BABYLON.Mesh(name, scene);
  17939. var vertexData = BABYLON.VertexData.CreateDisc(options);
  17940. vertexData.applyToMesh(disc, options.updatable);
  17941. return disc;
  17942. };
  17943. /**
  17944. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  17945. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  17946. * The parameter "radius" sets the radius size (float) of the icosphere (default 1).
  17947. * 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").
  17948. * The parameter "subdivisions" sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  17949. * 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.
  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.CreateIcoSphere = function (name, options, scene) {
  17955. var sphere = new BABYLON.Mesh(name, scene);
  17956. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  17957. vertexData.applyToMesh(sphere, options.updatable);
  17958. return sphere;
  17959. };
  17960. ;
  17961. /**
  17962. * Creates a ribbon mesh.
  17963. * 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.
  17964. *
  17965. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  17966. * The parameter "pathArray" is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  17967. * The parameter "closeArray" (boolean, default false) creates a seam between the first and the last paths of the path array.
  17968. * The parameter "closePath" (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  17969. * 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
  17970. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17971. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17972. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  17973. */
  17974. MeshBuilder.CreateRibbon = function (name, options, scene) {
  17975. var pathArray = options.pathArray;
  17976. var closeArray = options.closeArray;
  17977. var closePath = options.closePath;
  17978. var offset = options.offset;
  17979. var sideOrientation = options.sideOrientation;
  17980. var instance = options.instance;
  17981. var updatable = options.updatable;
  17982. if (instance) {
  17983. // positionFunction : ribbon case
  17984. // only pathArray and sideOrientation parameters are taken into account for positions update
  17985. var positionFunction = function (positions) {
  17986. var minlg = pathArray[0].length;
  17987. var i = 0;
  17988. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  17989. for (var si = 1; si <= ns; si++) {
  17990. for (var p = 0; p < pathArray.length; p++) {
  17991. var path = pathArray[p];
  17992. var l = path.length;
  17993. minlg = (minlg < l) ? minlg : l;
  17994. var j = 0;
  17995. while (j < minlg) {
  17996. positions[i] = path[j].x;
  17997. positions[i + 1] = path[j].y;
  17998. positions[i + 2] = path[j].z;
  17999. j++;
  18000. i += 3;
  18001. }
  18002. if (instance._closePath) {
  18003. positions[i] = path[0].x;
  18004. positions[i + 1] = path[0].y;
  18005. positions[i + 2] = path[0].z;
  18006. i += 3;
  18007. }
  18008. }
  18009. }
  18010. };
  18011. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18012. positionFunction(positions);
  18013. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18014. if (!(instance.areNormalsFrozen)) {
  18015. var indices = instance.getIndices();
  18016. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18017. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18018. if (instance._closePath) {
  18019. var indexFirst = 0;
  18020. var indexLast = 0;
  18021. for (var p = 0; p < pathArray.length; p++) {
  18022. indexFirst = instance._idx[p] * 3;
  18023. if (p + 1 < pathArray.length) {
  18024. indexLast = (instance._idx[p + 1] - 1) * 3;
  18025. }
  18026. else {
  18027. indexLast = normals.length - 3;
  18028. }
  18029. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  18030. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  18031. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  18032. normals[indexLast] = normals[indexFirst];
  18033. normals[indexLast + 1] = normals[indexFirst + 1];
  18034. normals[indexLast + 2] = normals[indexFirst + 2];
  18035. }
  18036. }
  18037. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18038. }
  18039. return instance;
  18040. }
  18041. else {
  18042. var ribbon = new BABYLON.Mesh(name, scene);
  18043. ribbon.sideOrientation = sideOrientation;
  18044. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  18045. if (closePath) {
  18046. ribbon._idx = vertexData._idx;
  18047. }
  18048. ribbon._closePath = closePath;
  18049. ribbon._closeArray = closeArray;
  18050. vertexData.applyToMesh(ribbon, updatable);
  18051. return ribbon;
  18052. }
  18053. };
  18054. /**
  18055. * Creates a cylinder or a cone mesh.
  18056. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  18057. * The parameter "height" sets the height size (float) of the cylinder/cone (float, default 2).
  18058. * The parameter "diameter" sets the diameter of the top and bottom cap at once (float, default 1).
  18059. * 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.
  18060. * The parameter "tessellation" sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18061. * The parameter "subdivisions" sets the number of rings along the cylinder height (positive integer, default 1).
  18062. * The parameter "hasRings" (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  18063. * The parameter "enclose" (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  18064. * The parameter "arc" (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  18065. * 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).
  18066. * 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
  18067. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  18068. * 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
  18069. * 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.
  18070. * If enclose is false, a ring surface is one element.
  18071. * If enclose true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  18072. * 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
  18073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18074. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18075. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18076. */
  18077. MeshBuilder.CreateCylinder = function (name, options, scene) {
  18078. var cylinder = new BABYLON.Mesh(name, scene);
  18079. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  18080. vertexData.applyToMesh(cylinder, options.updatable);
  18081. return cylinder;
  18082. };
  18083. /**
  18084. * Creates a torus mesh.
  18085. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  18086. * The parameter "diameter" sets the diameter size (float) of the torus (default 1).
  18087. * The parameter "thickness" sets the diameter size of the tube of the torus (float, default 0.5).
  18088. * The parameter "tessellation" sets the number of torus sides (postive integer, default 16).
  18089. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18090. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18091. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18092. */
  18093. MeshBuilder.CreateTorus = function (name, options, scene) {
  18094. var torus = new BABYLON.Mesh(name, scene);
  18095. var vertexData = BABYLON.VertexData.CreateTorus(options);
  18096. vertexData.applyToMesh(torus, options.updatable);
  18097. return torus;
  18098. };
  18099. /**
  18100. * Creates a torus knot mesh.
  18101. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  18102. * The parameter "radius" sets the global radius size (float) of the torus knot (default 2).
  18103. * The parameter "radialSegments" sets the number of sides on each tube segments (positive integer, default 32).
  18104. * The parameter "tubularSegments" sets the number of tubes to decompose the knot into (positive integer, default 32).
  18105. * The parameters "p" and "q" are the number of windings on each axis (positive integers, default 2 and 3).
  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.CreateTorusKnot = function (name, options, scene) {
  18111. var torusKnot = new BABYLON.Mesh(name, scene);
  18112. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  18113. vertexData.applyToMesh(torusKnot, options.updatable);
  18114. return torusKnot;
  18115. };
  18116. /**
  18117. * Creates a line system mesh.
  18118. * A line system is a pool of many lines gathered in a single mesh.
  18119. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  18120. * 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.
  18121. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  18122. * The parameter "lines" is an array of lines, each line being an array of successive Vector3.
  18123. * 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
  18124. * 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
  18125. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  18126. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18127. */
  18128. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  18129. var instance = options.instance;
  18130. var lines = options.lines;
  18131. if (instance) {
  18132. var positionFunction = function (positions) {
  18133. var i = 0;
  18134. for (var l = 0; l < lines.length; l++) {
  18135. var points = lines[l];
  18136. for (var p = 0; p < points.length; p++) {
  18137. positions[i] = points[p].x;
  18138. positions[i + 1] = points[p].y;
  18139. positions[i + 2] = points[p].z;
  18140. i += 3;
  18141. }
  18142. }
  18143. };
  18144. instance.updateMeshPositions(positionFunction, false);
  18145. return instance;
  18146. }
  18147. // line system creation
  18148. var lineSystem = new BABYLON.LinesMesh(name, scene);
  18149. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  18150. vertexData.applyToMesh(lineSystem, options.updatable);
  18151. return lineSystem;
  18152. };
  18153. /**
  18154. * Creates a line mesh.
  18155. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  18156. * 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.
  18157. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18158. * The parameter "points" is an array successive Vector3.
  18159. * 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
  18160. * When updating an instance, remember that only point positions can change, not the number of points.
  18161. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18162. */
  18163. MeshBuilder.CreateLines = function (name, options, scene) {
  18164. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  18165. return lines;
  18166. };
  18167. /**
  18168. * Creates a dashed line mesh.
  18169. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  18170. * 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.
  18171. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18172. * The parameter "points" is an array successive Vector3.
  18173. * The parameter "dashNb" is the intended total number of dashes (positive integer, default 200).
  18174. * The parameter "dashSize" is the size of the dashes relatively the dash number (positive float, default 3).
  18175. * The parameter "gapSize" is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18176. * 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
  18177. * When updating an instance, remember that only point positions can change, not the number of points.
  18178. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18179. */
  18180. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  18181. var points = options.points;
  18182. var instance = options.instance;
  18183. var gapSize = options.gapSize;
  18184. var dashNb = options.dashNb;
  18185. var dashSize = options.dashSize;
  18186. if (instance) {
  18187. var positionFunction = function (positions) {
  18188. var curvect = BABYLON.Vector3.Zero();
  18189. var nbSeg = positions.length / 6;
  18190. var lg = 0;
  18191. var nb = 0;
  18192. var shft = 0;
  18193. var dashshft = 0;
  18194. var curshft = 0;
  18195. var p = 0;
  18196. var i = 0;
  18197. var j = 0;
  18198. for (i = 0; i < points.length - 1; i++) {
  18199. points[i + 1].subtractToRef(points[i], curvect);
  18200. lg += curvect.length();
  18201. }
  18202. shft = lg / nbSeg;
  18203. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  18204. for (i = 0; i < points.length - 1; i++) {
  18205. points[i + 1].subtractToRef(points[i], curvect);
  18206. nb = Math.floor(curvect.length() / shft);
  18207. curvect.normalize();
  18208. j = 0;
  18209. while (j < nb && p < positions.length) {
  18210. curshft = shft * j;
  18211. positions[p] = points[i].x + curshft * curvect.x;
  18212. positions[p + 1] = points[i].y + curshft * curvect.y;
  18213. positions[p + 2] = points[i].z + curshft * curvect.z;
  18214. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  18215. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  18216. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  18217. p += 6;
  18218. j++;
  18219. }
  18220. }
  18221. while (p < positions.length) {
  18222. positions[p] = points[i].x;
  18223. positions[p + 1] = points[i].y;
  18224. positions[p + 2] = points[i].z;
  18225. p += 3;
  18226. }
  18227. };
  18228. instance.updateMeshPositions(positionFunction, false);
  18229. return instance;
  18230. }
  18231. // dashed lines creation
  18232. var dashedLines = new BABYLON.LinesMesh(name, scene);
  18233. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  18234. vertexData.applyToMesh(dashedLines, options.updatable);
  18235. dashedLines.dashSize = dashSize;
  18236. dashedLines.gapSize = gapSize;
  18237. return dashedLines;
  18238. };
  18239. /**
  18240. * Creates an extruded shape mesh.
  18241. * 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.
  18242. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  18243. *
  18244. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18245. * 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
  18246. * extruded along the Z axis.
  18247. * The parameter "path" is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18248. * 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.
  18249. * The parameter "scale" (float, default 1) is the value to scale the shape.
  18250. * 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
  18251. * 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
  18252. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18253. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18254. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18255. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18256. */
  18257. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  18258. var path = options.path;
  18259. var shape = options.shape;
  18260. var scale = options.scale || 1;
  18261. var rotation = options.rotation || 0;
  18262. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  18263. var updatable = options.updatable;
  18264. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18265. var instance = options.instance;
  18266. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  18267. };
  18268. /**
  18269. * Creates an custom extruded shape mesh.
  18270. * 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.
  18271. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  18272. *
  18273. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18274. * 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
  18275. * extruded along the Z axis.
  18276. * The parameter "path" is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18277. * 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
  18278. * and the distance of this point from the begining of the path : rotationFunction = function(i, distance) {}.
  18279. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18280. * 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
  18281. * and the distance of this point from the begining of the path : scaleFunction = function(i, distance) {}.
  18282. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18283. * The parameter "ribbonClosePath" (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its pathArray.
  18284. * The parameter "ribbonCloseArray" (boolean, default false) forces the extrusion underlying ribbon to close its pathArray.
  18285. * 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
  18286. * 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
  18287. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18288. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18289. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18290. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18291. */
  18292. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  18293. var path = options.path;
  18294. var shape = options.shape;
  18295. var scaleFunction = options.scaleFunction || (function () { return 1; });
  18296. var rotationFunction = options.rotationFunction || (function () { return 0; });
  18297. var ribbonCloseArray = options.ribbonCloseArray || false;
  18298. var ribbonClosePath = options.ribbonClosePath || false;
  18299. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  18300. var updatable = options.updatable;
  18301. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18302. var instance = options.instance;
  18303. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  18304. };
  18305. /**
  18306. * Creates lathe mesh.
  18307. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18308. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  18309. *
  18310. * 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
  18311. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18312. * The parameter "radius" (positive float, default 1) is the radius value of the lathe.
  18313. * The parameter "tessellation" (positive integer, default 64) is the side number of the lathe.
  18314. * 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.
  18315. * The parameter "closed" (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  18316. * 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
  18317. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18318. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18319. * The mesh can be set to updatable with the boolean parameter "updatable" (default false) if its internal geometry is supposed to change once created.
  18320. */
  18321. MeshBuilder.CreateLathe = function (name, options, scene) {
  18322. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  18323. var closed = (options.closed === undefined) ? true : options.closed;
  18324. var shape = options.shape;
  18325. var radius = options.radius || 1;
  18326. var tessellation = options.tessellation || 64;
  18327. var updatable = options.updatable;
  18328. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18329. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  18330. var pi2 = Math.PI * 2;
  18331. var paths = new Array();
  18332. var i = 0;
  18333. var p = 0;
  18334. var step = pi2 / tessellation * arc;
  18335. var rotated;
  18336. var path = new Array();
  18337. ;
  18338. for (i = 0; i <= tessellation; i++) {
  18339. var path = [];
  18340. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  18341. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  18342. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  18343. }
  18344. for (p = 0; p < shape.length; p++) {
  18345. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  18346. path.push(rotated);
  18347. }
  18348. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  18349. 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));
  18350. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  18351. }
  18352. paths.push(path);
  18353. }
  18354. // lathe ribbon
  18355. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  18356. return lathe;
  18357. };
  18358. MeshBuilder.CreatePlane = function (name, options, scene) {
  18359. var plane = new BABYLON.Mesh(name, scene);
  18360. var vertexData = BABYLON.VertexData.CreatePlane(options);
  18361. vertexData.applyToMesh(plane, options.updatable);
  18362. if (options.sourcePlane) {
  18363. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  18364. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  18365. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  18366. plane.rotate(vectorProduct, product);
  18367. }
  18368. return plane;
  18369. };
  18370. MeshBuilder.CreateGround = function (name, options, scene) {
  18371. var ground = new BABYLON.GroundMesh(name, scene);
  18372. ground._setReady(false);
  18373. ground._subdivisions = options.subdivisions || 1;
  18374. ground._width = options.width || 1;
  18375. ground._height = options.height || 1;
  18376. ground._maxX = ground._width / 2;
  18377. ground._maxZ = ground._height / 2;
  18378. ground._minX = -ground._maxX;
  18379. ground._minZ = -ground._maxZ;
  18380. var vertexData = BABYLON.VertexData.CreateGround(options);
  18381. vertexData.applyToMesh(ground, options.updatable);
  18382. ground._setReady(true);
  18383. return ground;
  18384. };
  18385. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  18386. var tiledGround = new BABYLON.Mesh(name, scene);
  18387. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  18388. vertexData.applyToMesh(tiledGround, options.updatable);
  18389. return tiledGround;
  18390. };
  18391. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  18392. var width = options.width || 10;
  18393. var height = options.height || 10;
  18394. var subdivisions = options.subdivisions || 1;
  18395. var minHeight = options.minHeight;
  18396. var maxHeight = options.maxHeight || 10;
  18397. var updatable = options.updatable;
  18398. var onReady = options.onReady;
  18399. var ground = new BABYLON.GroundMesh(name, scene);
  18400. ground._subdivisions = subdivisions;
  18401. ground._width = width;
  18402. ground._height = height;
  18403. ground._maxX = ground._width / 2;
  18404. ground._maxZ = ground._height / 2;
  18405. ground._minX = -ground._maxX;
  18406. ground._minZ = -ground._maxZ;
  18407. ground._setReady(false);
  18408. var onload = function (img) {
  18409. // Getting height map data
  18410. var canvas = document.createElement("canvas");
  18411. var context = canvas.getContext("2d");
  18412. var bufferWidth = img.width;
  18413. var bufferHeight = img.height;
  18414. canvas.width = bufferWidth;
  18415. canvas.height = bufferHeight;
  18416. context.drawImage(img, 0, 0);
  18417. // Create VertexData from map data
  18418. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  18419. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  18420. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  18421. width: width, height: height,
  18422. subdivisions: subdivisions,
  18423. minHeight: minHeight, maxHeight: maxHeight,
  18424. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  18425. });
  18426. vertexData.applyToMesh(ground, updatable);
  18427. ground._setReady(true);
  18428. //execute ready callback, if set
  18429. if (onReady) {
  18430. onReady(ground);
  18431. }
  18432. };
  18433. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  18434. return ground;
  18435. };
  18436. MeshBuilder.CreateTube = function (name, options, scene) {
  18437. var path = options.path;
  18438. var radius = options.radius || 1;
  18439. var tessellation = options.tessellation || 64;
  18440. var radiusFunction = options.radiusFunction;
  18441. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  18442. var updatable = options.updatable;
  18443. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18444. var instance = options.instance;
  18445. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  18446. // tube geometry
  18447. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  18448. var tangents = path3D.getTangents();
  18449. var normals = path3D.getNormals();
  18450. var distances = path3D.getDistances();
  18451. var pi2 = Math.PI * 2;
  18452. var step = pi2 / tessellation * arc;
  18453. var returnRadius = function () { return radius; };
  18454. var radiusFunctionFinal = radiusFunction || returnRadius;
  18455. var circlePath;
  18456. var rad;
  18457. var normal;
  18458. var rotated;
  18459. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  18460. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  18461. for (var i = 0; i < path.length; i++) {
  18462. rad = radiusFunctionFinal(i, distances[i]); // current radius
  18463. circlePath = Array(); // current circle array
  18464. normal = normals[i]; // current normal
  18465. for (var t = 0; t < tessellation; t++) {
  18466. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  18467. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  18468. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  18469. rotated.scaleInPlace(rad).addInPlace(path[i]);
  18470. circlePath[t] = rotated;
  18471. }
  18472. circlePaths[index] = circlePath;
  18473. index++;
  18474. }
  18475. // cap
  18476. var capPath = function (nbPoints, pathIndex) {
  18477. var pointCap = Array();
  18478. for (var i = 0; i < nbPoints; i++) {
  18479. pointCap.push(path[pathIndex]);
  18480. }
  18481. return pointCap;
  18482. };
  18483. switch (cap) {
  18484. case BABYLON.Mesh.NO_CAP:
  18485. break;
  18486. case BABYLON.Mesh.CAP_START:
  18487. circlePaths[0] = capPath(tessellation, 0);
  18488. circlePaths[1] = circlePaths[2].slice(0);
  18489. break;
  18490. case BABYLON.Mesh.CAP_END:
  18491. circlePaths[index] = circlePaths[index - 1].slice(0);
  18492. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  18493. break;
  18494. case BABYLON.Mesh.CAP_ALL:
  18495. circlePaths[0] = capPath(tessellation, 0);
  18496. circlePaths[1] = circlePaths[2].slice(0);
  18497. circlePaths[index] = circlePaths[index - 1].slice(0);
  18498. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  18499. break;
  18500. default:
  18501. break;
  18502. }
  18503. return circlePaths;
  18504. };
  18505. var path3D;
  18506. var pathArray;
  18507. if (instance) {
  18508. var arc = options.arc || instance.arc;
  18509. path3D = (instance.path3D).update(path);
  18510. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  18511. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  18512. instance.path3D = path3D;
  18513. instance.pathArray = pathArray;
  18514. instance.arc = arc;
  18515. return instance;
  18516. }
  18517. // tube creation
  18518. path3D = new BABYLON.Path3D(path);
  18519. var newPathArray = new Array();
  18520. cap = (cap < 0 || cap > 3) ? 0 : cap;
  18521. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  18522. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  18523. tube.pathArray = pathArray;
  18524. tube.path3D = path3D;
  18525. tube.tessellation = tessellation;
  18526. tube.cap = cap;
  18527. tube.arc = options.arc;
  18528. return tube;
  18529. };
  18530. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  18531. var polyhedron = new BABYLON.Mesh(name, scene);
  18532. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  18533. vertexData.applyToMesh(polyhedron, options.updatable);
  18534. return polyhedron;
  18535. };
  18536. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  18537. var indices = sourceMesh.getIndices();
  18538. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18539. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18540. var position = options.position || BABYLON.Vector3.Zero();
  18541. var normal = options.normal || BABYLON.Vector3.Up();
  18542. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  18543. var angle = options.angle || 0;
  18544. // Getting correct rotation
  18545. if (!normal) {
  18546. var target = new BABYLON.Vector3(0, 0, 1);
  18547. var camera = sourceMesh.getScene().activeCamera;
  18548. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  18549. normal = camera.globalPosition.subtract(cameraWorldTarget);
  18550. }
  18551. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  18552. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  18553. var pitch = Math.atan2(normal.y, len);
  18554. // Matrix
  18555. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  18556. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  18557. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  18558. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  18559. var vertexData = new BABYLON.VertexData();
  18560. vertexData.indices = [];
  18561. vertexData.positions = [];
  18562. vertexData.normals = [];
  18563. vertexData.uvs = [];
  18564. var currentVertexDataIndex = 0;
  18565. var extractDecalVector3 = function (indexId) {
  18566. var vertexId = indices[indexId];
  18567. var result = new BABYLON.PositionNormalVertex();
  18568. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  18569. // Send vector to decal local world
  18570. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  18571. // Get normal
  18572. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  18573. return result;
  18574. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  18575. var clip = function (vertices, axis) {
  18576. if (vertices.length === 0) {
  18577. return vertices;
  18578. }
  18579. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  18580. var clipVertices = function (v0, v1) {
  18581. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  18582. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  18583. };
  18584. var result = new Array();
  18585. for (var index = 0; index < vertices.length; index += 3) {
  18586. var v1Out;
  18587. var v2Out;
  18588. var v3Out;
  18589. var total = 0;
  18590. var nV1, nV2, nV3, nV4;
  18591. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  18592. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  18593. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  18594. v1Out = d1 > 0;
  18595. v2Out = d2 > 0;
  18596. v3Out = d3 > 0;
  18597. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  18598. switch (total) {
  18599. case 0:
  18600. result.push(vertices[index]);
  18601. result.push(vertices[index + 1]);
  18602. result.push(vertices[index + 2]);
  18603. break;
  18604. case 1:
  18605. if (v1Out) {
  18606. nV1 = vertices[index + 1];
  18607. nV2 = vertices[index + 2];
  18608. nV3 = clipVertices(vertices[index], nV1);
  18609. nV4 = clipVertices(vertices[index], nV2);
  18610. }
  18611. if (v2Out) {
  18612. nV1 = vertices[index];
  18613. nV2 = vertices[index + 2];
  18614. nV3 = clipVertices(vertices[index + 1], nV1);
  18615. nV4 = clipVertices(vertices[index + 1], nV2);
  18616. result.push(nV3);
  18617. result.push(nV2.clone());
  18618. result.push(nV1.clone());
  18619. result.push(nV2.clone());
  18620. result.push(nV3.clone());
  18621. result.push(nV4);
  18622. break;
  18623. }
  18624. if (v3Out) {
  18625. nV1 = vertices[index];
  18626. nV2 = vertices[index + 1];
  18627. nV3 = clipVertices(vertices[index + 2], nV1);
  18628. nV4 = clipVertices(vertices[index + 2], nV2);
  18629. }
  18630. result.push(nV1.clone());
  18631. result.push(nV2.clone());
  18632. result.push(nV3);
  18633. result.push(nV4);
  18634. result.push(nV3.clone());
  18635. result.push(nV2.clone());
  18636. break;
  18637. case 2:
  18638. if (!v1Out) {
  18639. nV1 = vertices[index].clone();
  18640. nV2 = clipVertices(nV1, vertices[index + 1]);
  18641. nV3 = clipVertices(nV1, vertices[index + 2]);
  18642. result.push(nV1);
  18643. result.push(nV2);
  18644. result.push(nV3);
  18645. }
  18646. if (!v2Out) {
  18647. nV1 = vertices[index + 1].clone();
  18648. nV2 = clipVertices(nV1, vertices[index + 2]);
  18649. nV3 = clipVertices(nV1, vertices[index]);
  18650. result.push(nV1);
  18651. result.push(nV2);
  18652. result.push(nV3);
  18653. }
  18654. if (!v3Out) {
  18655. nV1 = vertices[index + 2].clone();
  18656. nV2 = clipVertices(nV1, vertices[index]);
  18657. nV3 = clipVertices(nV1, vertices[index + 1]);
  18658. result.push(nV1);
  18659. result.push(nV2);
  18660. result.push(nV3);
  18661. }
  18662. break;
  18663. case 3:
  18664. break;
  18665. }
  18666. }
  18667. return result;
  18668. };
  18669. for (var index = 0; index < indices.length; index += 3) {
  18670. var faceVertices = new Array();
  18671. faceVertices.push(extractDecalVector3(index));
  18672. faceVertices.push(extractDecalVector3(index + 1));
  18673. faceVertices.push(extractDecalVector3(index + 2));
  18674. // Clip
  18675. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  18676. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  18677. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  18678. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  18679. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  18680. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  18681. if (faceVertices.length === 0) {
  18682. continue;
  18683. }
  18684. // Add UVs and get back to world
  18685. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  18686. var vertex = faceVertices[vIndex];
  18687. //TODO check for Int32Array
  18688. vertexData.indices.push(currentVertexDataIndex);
  18689. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  18690. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  18691. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  18692. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  18693. currentVertexDataIndex++;
  18694. }
  18695. }
  18696. // Return mesh
  18697. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  18698. vertexData.applyToMesh(decal);
  18699. decal.position = position.clone();
  18700. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  18701. return decal;
  18702. };
  18703. // Privates
  18704. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  18705. // extrusion geometry
  18706. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  18707. var tangents = path3D.getTangents();
  18708. var normals = path3D.getNormals();
  18709. var binormals = path3D.getBinormals();
  18710. var distances = path3D.getDistances();
  18711. var angle = 0;
  18712. var returnScale = function () { return scale; };
  18713. var returnRotation = function () { return rotation; };
  18714. var rotate = custom ? rotateFunction : returnRotation;
  18715. var scl = custom ? scaleFunction : returnScale;
  18716. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  18717. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  18718. for (var i = 0; i < curve.length; i++) {
  18719. var shapePath = new Array();
  18720. var angleStep = rotate(i, distances[i]);
  18721. var scaleRatio = scl(i, distances[i]);
  18722. for (var p = 0; p < shape.length; p++) {
  18723. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  18724. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  18725. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  18726. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  18727. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  18728. shapePath[p] = rotated;
  18729. }
  18730. shapePaths[index] = shapePath;
  18731. angle += angleStep;
  18732. index++;
  18733. }
  18734. // cap
  18735. var capPath = function (shapePath) {
  18736. var pointCap = Array();
  18737. var barycenter = BABYLON.Vector3.Zero();
  18738. var i;
  18739. for (i = 0; i < shapePath.length; i++) {
  18740. barycenter.addInPlace(shapePath[i]);
  18741. }
  18742. barycenter.scaleInPlace(1 / shapePath.length);
  18743. for (i = 0; i < shapePath.length; i++) {
  18744. pointCap.push(barycenter);
  18745. }
  18746. return pointCap;
  18747. };
  18748. switch (cap) {
  18749. case BABYLON.Mesh.NO_CAP:
  18750. break;
  18751. case BABYLON.Mesh.CAP_START:
  18752. shapePaths[0] = capPath(shapePaths[2]);
  18753. shapePaths[1] = shapePaths[2].slice(0);
  18754. break;
  18755. case BABYLON.Mesh.CAP_END:
  18756. shapePaths[index] = shapePaths[index - 1];
  18757. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  18758. break;
  18759. case BABYLON.Mesh.CAP_ALL:
  18760. shapePaths[0] = capPath(shapePaths[2]);
  18761. shapePaths[1] = shapePaths[2].slice(0);
  18762. shapePaths[index] = shapePaths[index - 1];
  18763. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  18764. break;
  18765. default:
  18766. break;
  18767. }
  18768. return shapePaths;
  18769. };
  18770. var path3D;
  18771. var pathArray;
  18772. if (instance) {
  18773. path3D = (instance.path3D).update(curve);
  18774. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  18775. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  18776. return instance;
  18777. }
  18778. // extruded shape creation
  18779. path3D = new BABYLON.Path3D(curve);
  18780. var newShapePaths = new Array();
  18781. cap = (cap < 0 || cap > 3) ? 0 : cap;
  18782. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  18783. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  18784. extrudedGeneric.pathArray = pathArray;
  18785. extrudedGeneric.path3D = path3D;
  18786. extrudedGeneric.cap = cap;
  18787. return extrudedGeneric;
  18788. };
  18789. return MeshBuilder;
  18790. })();
  18791. BABYLON.MeshBuilder = MeshBuilder;
  18792. })(BABYLON || (BABYLON = {}));
  18793. var BABYLON;
  18794. (function (BABYLON) {
  18795. var BaseTexture = (function () {
  18796. function BaseTexture(scene) {
  18797. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18798. this.hasAlpha = false;
  18799. this.getAlphaFromRGB = false;
  18800. this.level = 1;
  18801. this.isCube = false;
  18802. this.isRenderTarget = false;
  18803. this.animations = new Array();
  18804. this.coordinatesIndex = 0;
  18805. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18806. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18807. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18808. this.anisotropicFilteringLevel = 4;
  18809. this._scene = scene;
  18810. this._scene.textures.push(this);
  18811. }
  18812. BaseTexture.prototype.getScene = function () {
  18813. return this._scene;
  18814. };
  18815. BaseTexture.prototype.getTextureMatrix = function () {
  18816. return null;
  18817. };
  18818. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18819. return null;
  18820. };
  18821. BaseTexture.prototype.getInternalTexture = function () {
  18822. return this._texture;
  18823. };
  18824. BaseTexture.prototype.isReady = function () {
  18825. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18826. return true;
  18827. }
  18828. if (this._texture) {
  18829. return this._texture.isReady;
  18830. }
  18831. return false;
  18832. };
  18833. BaseTexture.prototype.getSize = function () {
  18834. if (this._texture._width) {
  18835. return { width: this._texture._width, height: this._texture._height };
  18836. }
  18837. if (this._texture._size) {
  18838. return { width: this._texture._size, height: this._texture._size };
  18839. }
  18840. return { width: 0, height: 0 };
  18841. };
  18842. BaseTexture.prototype.getBaseSize = function () {
  18843. if (!this.isReady())
  18844. return { width: 0, height: 0 };
  18845. if (this._texture._size) {
  18846. return { width: this._texture._size, height: this._texture._size };
  18847. }
  18848. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  18849. };
  18850. BaseTexture.prototype.scale = function (ratio) {
  18851. };
  18852. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18853. get: function () {
  18854. return false;
  18855. },
  18856. enumerable: true,
  18857. configurable: true
  18858. });
  18859. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18860. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18861. for (var index = 0; index < texturesCache.length; index++) {
  18862. var texturesCacheEntry = texturesCache[index];
  18863. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18864. texturesCache.splice(index, 1);
  18865. return;
  18866. }
  18867. }
  18868. };
  18869. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18870. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18871. for (var index = 0; index < texturesCache.length; index++) {
  18872. var texturesCacheEntry = texturesCache[index];
  18873. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18874. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18875. texturesCacheEntry.references++;
  18876. return texturesCacheEntry;
  18877. }
  18878. }
  18879. }
  18880. return null;
  18881. };
  18882. BaseTexture.prototype.delayLoad = function () {
  18883. };
  18884. BaseTexture.prototype.clone = function () {
  18885. return null;
  18886. };
  18887. BaseTexture.prototype.releaseInternalTexture = function () {
  18888. if (this._texture) {
  18889. this._scene.getEngine().releaseInternalTexture(this._texture);
  18890. delete this._texture;
  18891. }
  18892. };
  18893. BaseTexture.prototype.dispose = function () {
  18894. // Animations
  18895. this.getScene().stopAnimation(this);
  18896. // Remove from scene
  18897. var index = this._scene.textures.indexOf(this);
  18898. if (index >= 0) {
  18899. this._scene.textures.splice(index, 1);
  18900. }
  18901. if (this._texture === undefined) {
  18902. return;
  18903. }
  18904. // Release
  18905. this.releaseInternalTexture();
  18906. // Callback
  18907. if (this.onDispose) {
  18908. this.onDispose();
  18909. }
  18910. };
  18911. BaseTexture.prototype.serialize = function () {
  18912. var serializationObject = {};
  18913. if (!this.name) {
  18914. return null;
  18915. }
  18916. serializationObject.name = this.name;
  18917. serializationObject.hasAlpha = this.hasAlpha;
  18918. serializationObject.level = this.level;
  18919. serializationObject.coordinatesIndex = this.coordinatesIndex;
  18920. serializationObject.coordinatesMode = this.coordinatesMode;
  18921. serializationObject.wrapU = this.wrapU;
  18922. serializationObject.wrapV = this.wrapV;
  18923. // Animations
  18924. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18925. return serializationObject;
  18926. };
  18927. return BaseTexture;
  18928. })();
  18929. BABYLON.BaseTexture = BaseTexture;
  18930. })(BABYLON || (BABYLON = {}));
  18931. var BABYLON;
  18932. (function (BABYLON) {
  18933. var Texture = (function (_super) {
  18934. __extends(Texture, _super);
  18935. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  18936. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18937. if (onLoad === void 0) { onLoad = null; }
  18938. if (onError === void 0) { onError = null; }
  18939. if (buffer === void 0) { buffer = null; }
  18940. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18941. _super.call(this, scene);
  18942. this.uOffset = 0;
  18943. this.vOffset = 0;
  18944. this.uScale = 1.0;
  18945. this.vScale = 1.0;
  18946. this.uAng = 0;
  18947. this.vAng = 0;
  18948. this.wAng = 0;
  18949. this.name = url;
  18950. this.url = url;
  18951. this._noMipmap = noMipmap;
  18952. this._invertY = invertY;
  18953. this._samplingMode = samplingMode;
  18954. this._buffer = buffer;
  18955. this._deleteBuffer = deleteBuffer;
  18956. if (!url) {
  18957. return;
  18958. }
  18959. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  18960. if (!this._texture) {
  18961. if (!scene.useDelayedTextureLoading) {
  18962. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  18963. if (deleteBuffer) {
  18964. delete this._buffer;
  18965. }
  18966. }
  18967. else {
  18968. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18969. this._delayedOnLoad = onLoad;
  18970. this._delayedOnError = onError;
  18971. }
  18972. }
  18973. else {
  18974. BABYLON.Tools.SetImmediate(function () {
  18975. if (onLoad) {
  18976. onLoad();
  18977. }
  18978. });
  18979. }
  18980. }
  18981. Texture.prototype.delayLoad = function () {
  18982. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18983. return;
  18984. }
  18985. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18986. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  18987. if (!this._texture) {
  18988. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  18989. if (this._deleteBuffer) {
  18990. delete this._buffer;
  18991. }
  18992. }
  18993. };
  18994. Texture.prototype.updateSamplingMode = function (samplingMode) {
  18995. if (!this._texture) {
  18996. return;
  18997. }
  18998. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  18999. };
  19000. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19001. x *= this.uScale;
  19002. y *= this.vScale;
  19003. x -= 0.5 * this.uScale;
  19004. y -= 0.5 * this.vScale;
  19005. z -= 0.5;
  19006. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19007. t.x += 0.5 * this.uScale + this.uOffset;
  19008. t.y += 0.5 * this.vScale + this.vOffset;
  19009. t.z += 0.5;
  19010. };
  19011. Texture.prototype.getTextureMatrix = function () {
  19012. if (this.uOffset === this._cachedUOffset &&
  19013. this.vOffset === this._cachedVOffset &&
  19014. this.uScale === this._cachedUScale &&
  19015. this.vScale === this._cachedVScale &&
  19016. this.uAng === this._cachedUAng &&
  19017. this.vAng === this._cachedVAng &&
  19018. this.wAng === this._cachedWAng) {
  19019. return this._cachedTextureMatrix;
  19020. }
  19021. this._cachedUOffset = this.uOffset;
  19022. this._cachedVOffset = this.vOffset;
  19023. this._cachedUScale = this.uScale;
  19024. this._cachedVScale = this.vScale;
  19025. this._cachedUAng = this.uAng;
  19026. this._cachedVAng = this.vAng;
  19027. this._cachedWAng = this.wAng;
  19028. if (!this._cachedTextureMatrix) {
  19029. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19030. this._rowGenerationMatrix = new BABYLON.Matrix();
  19031. this._t0 = BABYLON.Vector3.Zero();
  19032. this._t1 = BABYLON.Vector3.Zero();
  19033. this._t2 = BABYLON.Vector3.Zero();
  19034. }
  19035. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19036. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19037. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19038. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19039. this._t1.subtractInPlace(this._t0);
  19040. this._t2.subtractInPlace(this._t0);
  19041. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19042. this._cachedTextureMatrix.m[0] = this._t1.x;
  19043. this._cachedTextureMatrix.m[1] = this._t1.y;
  19044. this._cachedTextureMatrix.m[2] = this._t1.z;
  19045. this._cachedTextureMatrix.m[4] = this._t2.x;
  19046. this._cachedTextureMatrix.m[5] = this._t2.y;
  19047. this._cachedTextureMatrix.m[6] = this._t2.z;
  19048. this._cachedTextureMatrix.m[8] = this._t0.x;
  19049. this._cachedTextureMatrix.m[9] = this._t0.y;
  19050. this._cachedTextureMatrix.m[10] = this._t0.z;
  19051. return this._cachedTextureMatrix;
  19052. };
  19053. Texture.prototype.getReflectionTextureMatrix = function () {
  19054. if (this.uOffset === this._cachedUOffset &&
  19055. this.vOffset === this._cachedVOffset &&
  19056. this.uScale === this._cachedUScale &&
  19057. this.vScale === this._cachedVScale &&
  19058. this.coordinatesMode === this._cachedCoordinatesMode) {
  19059. return this._cachedTextureMatrix;
  19060. }
  19061. if (!this._cachedTextureMatrix) {
  19062. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19063. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19064. }
  19065. this._cachedCoordinatesMode = this.coordinatesMode;
  19066. switch (this.coordinatesMode) {
  19067. case Texture.PLANAR_MODE:
  19068. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19069. this._cachedTextureMatrix[0] = this.uScale;
  19070. this._cachedTextureMatrix[5] = this.vScale;
  19071. this._cachedTextureMatrix[12] = this.uOffset;
  19072. this._cachedTextureMatrix[13] = this.vOffset;
  19073. break;
  19074. case Texture.PROJECTION_MODE:
  19075. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19076. this._projectionModeMatrix.m[0] = 0.5;
  19077. this._projectionModeMatrix.m[5] = -0.5;
  19078. this._projectionModeMatrix.m[10] = 0.0;
  19079. this._projectionModeMatrix.m[12] = 0.5;
  19080. this._projectionModeMatrix.m[13] = 0.5;
  19081. this._projectionModeMatrix.m[14] = 1.0;
  19082. this._projectionModeMatrix.m[15] = 1.0;
  19083. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19084. break;
  19085. default:
  19086. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19087. break;
  19088. }
  19089. return this._cachedTextureMatrix;
  19090. };
  19091. Texture.prototype.clone = function () {
  19092. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  19093. // Base texture
  19094. newTexture.hasAlpha = this.hasAlpha;
  19095. newTexture.level = this.level;
  19096. newTexture.wrapU = this.wrapU;
  19097. newTexture.wrapV = this.wrapV;
  19098. newTexture.coordinatesIndex = this.coordinatesIndex;
  19099. newTexture.coordinatesMode = this.coordinatesMode;
  19100. // Texture
  19101. newTexture.uOffset = this.uOffset;
  19102. newTexture.vOffset = this.vOffset;
  19103. newTexture.uScale = this.uScale;
  19104. newTexture.vScale = this.vScale;
  19105. newTexture.uAng = this.uAng;
  19106. newTexture.vAng = this.vAng;
  19107. newTexture.wAng = this.wAng;
  19108. return newTexture;
  19109. };
  19110. Texture.prototype.serialize = function () {
  19111. if (!this.name) {
  19112. return null;
  19113. }
  19114. var serializationObject = _super.prototype.serialize.call(this);
  19115. serializationObject.uOffset = this.uOffset;
  19116. serializationObject.vOffset = this.vOffset;
  19117. serializationObject.uScale = this.uScale;
  19118. serializationObject.vScale = this.vScale;
  19119. serializationObject.uAng = this.uAng;
  19120. serializationObject.vAng = this.vAng;
  19121. serializationObject.wAng = this.wAng;
  19122. return serializationObject;
  19123. };
  19124. // Statics
  19125. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  19126. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19127. if (onLoad === void 0) { onLoad = null; }
  19128. if (onError === void 0) { onError = null; }
  19129. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  19130. };
  19131. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19132. if (parsedTexture.isCube) {
  19133. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19134. }
  19135. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19136. return null;
  19137. }
  19138. var texture;
  19139. if (parsedTexture.mirrorPlane) {
  19140. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19141. texture._waitingRenderList = parsedTexture.renderList;
  19142. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19143. }
  19144. else if (parsedTexture.isRenderTarget) {
  19145. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19146. texture._waitingRenderList = parsedTexture.renderList;
  19147. }
  19148. else {
  19149. if (parsedTexture.base64String) {
  19150. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19151. }
  19152. else {
  19153. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19154. }
  19155. }
  19156. texture.name = parsedTexture.name;
  19157. texture.hasAlpha = parsedTexture.hasAlpha;
  19158. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19159. texture.level = parsedTexture.level;
  19160. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19161. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19162. texture.uOffset = parsedTexture.uOffset;
  19163. texture.vOffset = parsedTexture.vOffset;
  19164. texture.uScale = parsedTexture.uScale;
  19165. texture.vScale = parsedTexture.vScale;
  19166. texture.uAng = parsedTexture.uAng;
  19167. texture.vAng = parsedTexture.vAng;
  19168. texture.wAng = parsedTexture.wAng;
  19169. texture.wrapU = parsedTexture.wrapU;
  19170. texture.wrapV = parsedTexture.wrapV;
  19171. // Animations
  19172. if (parsedTexture.animations) {
  19173. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19174. var parsedAnimation = parsedTexture.animations[animationIndex];
  19175. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19176. }
  19177. }
  19178. return texture;
  19179. };
  19180. // Constants
  19181. Texture.NEAREST_SAMPLINGMODE = 1;
  19182. Texture.BILINEAR_SAMPLINGMODE = 2;
  19183. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19184. Texture.EXPLICIT_MODE = 0;
  19185. Texture.SPHERICAL_MODE = 1;
  19186. Texture.PLANAR_MODE = 2;
  19187. Texture.CUBIC_MODE = 3;
  19188. Texture.PROJECTION_MODE = 4;
  19189. Texture.SKYBOX_MODE = 5;
  19190. Texture.INVCUBIC_MODE = 6;
  19191. Texture.EQUIRECTANGULAR_MODE = 7;
  19192. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19193. Texture.CLAMP_ADDRESSMODE = 0;
  19194. Texture.WRAP_ADDRESSMODE = 1;
  19195. Texture.MIRROR_ADDRESSMODE = 2;
  19196. return Texture;
  19197. })(BABYLON.BaseTexture);
  19198. BABYLON.Texture = Texture;
  19199. })(BABYLON || (BABYLON = {}));
  19200. var BABYLON;
  19201. (function (BABYLON) {
  19202. var CubeTexture = (function (_super) {
  19203. __extends(CubeTexture, _super);
  19204. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  19205. _super.call(this, scene);
  19206. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  19207. this.name = rootUrl;
  19208. this.url = rootUrl;
  19209. this._noMipmap = noMipmap;
  19210. this.hasAlpha = false;
  19211. if (!rootUrl && !files) {
  19212. return;
  19213. }
  19214. this._texture = this._getFromCache(rootUrl, noMipmap);
  19215. if (!files) {
  19216. if (!extensions) {
  19217. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  19218. }
  19219. files = [];
  19220. for (var index = 0; index < extensions.length; index++) {
  19221. files.push(rootUrl + extensions[index]);
  19222. }
  19223. this._extensions = extensions;
  19224. }
  19225. this._files = files;
  19226. if (!this._texture) {
  19227. if (!scene.useDelayedTextureLoading) {
  19228. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  19229. }
  19230. else {
  19231. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19232. }
  19233. }
  19234. this.isCube = true;
  19235. this._textureMatrix = BABYLON.Matrix.Identity();
  19236. }
  19237. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  19238. return new CubeTexture("", scene, null, noMipmap, files);
  19239. };
  19240. CubeTexture.prototype.clone = function () {
  19241. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  19242. // Base texture
  19243. newTexture.level = this.level;
  19244. newTexture.wrapU = this.wrapU;
  19245. newTexture.wrapV = this.wrapV;
  19246. newTexture.coordinatesIndex = this.coordinatesIndex;
  19247. newTexture.coordinatesMode = this.coordinatesMode;
  19248. return newTexture;
  19249. };
  19250. // Methods
  19251. CubeTexture.prototype.delayLoad = function () {
  19252. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19253. return;
  19254. }
  19255. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19256. this._texture = this._getFromCache(this.url, this._noMipmap);
  19257. if (!this._texture) {
  19258. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  19259. }
  19260. };
  19261. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  19262. return this._textureMatrix;
  19263. };
  19264. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  19265. var texture = null;
  19266. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19267. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19268. texture.name = parsedTexture.name;
  19269. texture.hasAlpha = parsedTexture.hasAlpha;
  19270. texture.level = parsedTexture.level;
  19271. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19272. }
  19273. return texture;
  19274. };
  19275. CubeTexture.prototype.serialize = function () {
  19276. if (!this.name) {
  19277. return null;
  19278. }
  19279. var serializationObject = {};
  19280. serializationObject.name = this.name;
  19281. serializationObject.hasAlpha = this.hasAlpha;
  19282. serializationObject.isCube = true;
  19283. serializationObject.level = this.level;
  19284. serializationObject.coordinatesMode = this.coordinatesMode;
  19285. return serializationObject;
  19286. };
  19287. return CubeTexture;
  19288. })(BABYLON.BaseTexture);
  19289. BABYLON.CubeTexture = CubeTexture;
  19290. })(BABYLON || (BABYLON = {}));
  19291. var BABYLON;
  19292. (function (BABYLON) {
  19293. var RenderTargetTexture = (function (_super) {
  19294. __extends(RenderTargetTexture, _super);
  19295. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  19296. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  19297. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  19298. if (isCube === void 0) { isCube = false; }
  19299. _super.call(this, null, scene, !generateMipMaps);
  19300. this.isCube = isCube;
  19301. this.renderList = new Array();
  19302. this.renderParticles = true;
  19303. this.renderSprites = false;
  19304. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  19305. this._currentRefreshId = -1;
  19306. this._refreshRate = 1;
  19307. this.name = name;
  19308. this.isRenderTarget = true;
  19309. this._size = size;
  19310. this._generateMipMaps = generateMipMaps;
  19311. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  19312. if (isCube) {
  19313. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  19314. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  19315. this._textureMatrix = BABYLON.Matrix.Identity();
  19316. }
  19317. else {
  19318. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  19319. }
  19320. // Rendering groups
  19321. this._renderingManager = new BABYLON.RenderingManager(scene);
  19322. }
  19323. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  19324. get: function () {
  19325. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  19326. },
  19327. enumerable: true,
  19328. configurable: true
  19329. });
  19330. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  19331. get: function () {
  19332. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  19333. },
  19334. enumerable: true,
  19335. configurable: true
  19336. });
  19337. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  19338. get: function () {
  19339. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  19340. },
  19341. enumerable: true,
  19342. configurable: true
  19343. });
  19344. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  19345. this._currentRefreshId = -1;
  19346. };
  19347. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  19348. get: function () {
  19349. return this._refreshRate;
  19350. },
  19351. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  19352. set: function (value) {
  19353. this._refreshRate = value;
  19354. this.resetRefreshCounter();
  19355. },
  19356. enumerable: true,
  19357. configurable: true
  19358. });
  19359. RenderTargetTexture.prototype._shouldRender = function () {
  19360. if (this._currentRefreshId === -1) {
  19361. this._currentRefreshId = 1;
  19362. return true;
  19363. }
  19364. if (this.refreshRate === this._currentRefreshId) {
  19365. this._currentRefreshId = 1;
  19366. return true;
  19367. }
  19368. this._currentRefreshId++;
  19369. return false;
  19370. };
  19371. RenderTargetTexture.prototype.isReady = function () {
  19372. if (!this.getScene().renderTargetsEnabled) {
  19373. return false;
  19374. }
  19375. return _super.prototype.isReady.call(this);
  19376. };
  19377. RenderTargetTexture.prototype.getRenderSize = function () {
  19378. return this._size;
  19379. };
  19380. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  19381. get: function () {
  19382. return true;
  19383. },
  19384. enumerable: true,
  19385. configurable: true
  19386. });
  19387. RenderTargetTexture.prototype.scale = function (ratio) {
  19388. var newSize = this._size * ratio;
  19389. this.resize(newSize, this._generateMipMaps);
  19390. };
  19391. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  19392. if (this.isCube) {
  19393. return this._textureMatrix;
  19394. }
  19395. return _super.prototype.getReflectionTextureMatrix.call(this);
  19396. };
  19397. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  19398. this.releaseInternalTexture();
  19399. if (this.isCube) {
  19400. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  19401. }
  19402. else {
  19403. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  19404. }
  19405. };
  19406. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  19407. var scene = this.getScene();
  19408. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  19409. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  19410. }
  19411. if (this._waitingRenderList) {
  19412. this.renderList = [];
  19413. for (var index = 0; index < this._waitingRenderList.length; index++) {
  19414. var id = this._waitingRenderList[index];
  19415. this.renderList.push(scene.getMeshByID(id));
  19416. }
  19417. delete this._waitingRenderList;
  19418. }
  19419. if (this.renderList && this.renderList.length === 0) {
  19420. return;
  19421. }
  19422. // Prepare renderingManager
  19423. this._renderingManager.reset();
  19424. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  19425. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  19426. var mesh = currentRenderList[meshIndex];
  19427. if (mesh) {
  19428. if (!mesh.isReady()) {
  19429. // Reset _currentRefreshId
  19430. this.resetRefreshCounter();
  19431. continue;
  19432. }
  19433. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  19434. mesh._activate(scene.getRenderId());
  19435. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19436. var subMesh = mesh.subMeshes[subIndex];
  19437. scene._activeIndices += subMesh.indexCount;
  19438. this._renderingManager.dispatch(subMesh);
  19439. }
  19440. }
  19441. }
  19442. }
  19443. if (this.isCube) {
  19444. for (var face = 0; face < 6; face++) {
  19445. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  19446. scene.incrementRenderId();
  19447. }
  19448. }
  19449. else {
  19450. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  19451. }
  19452. if (this.onAfterUnbind) {
  19453. this.onAfterUnbind();
  19454. }
  19455. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  19456. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  19457. }
  19458. scene.resetCachedMaterial();
  19459. };
  19460. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  19461. var scene = this.getScene();
  19462. var engine = scene.getEngine();
  19463. // Bind
  19464. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  19465. if (this.isCube) {
  19466. engine.bindFramebuffer(this._texture, faceIndex);
  19467. }
  19468. else {
  19469. engine.bindFramebuffer(this._texture);
  19470. }
  19471. }
  19472. if (this.onBeforeRender) {
  19473. this.onBeforeRender(faceIndex);
  19474. }
  19475. // Clear
  19476. if (this.onClear) {
  19477. this.onClear(engine);
  19478. }
  19479. else {
  19480. engine.clear(scene.clearColor, true, true);
  19481. }
  19482. if (!this._doNotChangeAspectRatio) {
  19483. scene.updateTransformMatrix(true);
  19484. }
  19485. // Render
  19486. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  19487. if (useCameraPostProcess) {
  19488. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  19489. }
  19490. if (!this._doNotChangeAspectRatio) {
  19491. scene.updateTransformMatrix(true);
  19492. }
  19493. if (this.onAfterRender) {
  19494. this.onAfterRender(faceIndex);
  19495. }
  19496. // Dump ?
  19497. if (dumpForDebug) {
  19498. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  19499. }
  19500. // Unbind
  19501. if (!this.isCube || faceIndex === 5) {
  19502. if (this.isCube) {
  19503. if (faceIndex === 5) {
  19504. engine.generateMipMapsForCubemap(this._texture);
  19505. }
  19506. }
  19507. engine.unBindFramebuffer(this._texture, this.isCube);
  19508. }
  19509. };
  19510. RenderTargetTexture.prototype.clone = function () {
  19511. var textureSize = this.getSize();
  19512. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19513. // Base texture
  19514. newTexture.hasAlpha = this.hasAlpha;
  19515. newTexture.level = this.level;
  19516. // RenderTarget Texture
  19517. newTexture.coordinatesMode = this.coordinatesMode;
  19518. newTexture.renderList = this.renderList.slice(0);
  19519. return newTexture;
  19520. };
  19521. RenderTargetTexture.prototype.serialize = function () {
  19522. if (!this.name) {
  19523. return null;
  19524. }
  19525. var serializationObject = _super.prototype.serialize.call(this);
  19526. serializationObject.renderTargetSize = this.getRenderSize();
  19527. serializationObject.renderList = [];
  19528. for (var index = 0; index < this.renderList.length; index++) {
  19529. serializationObject.renderList.push(this.renderList[index].id);
  19530. }
  19531. return serializationObject;
  19532. };
  19533. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  19534. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  19535. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  19536. return RenderTargetTexture;
  19537. })(BABYLON.Texture);
  19538. BABYLON.RenderTargetTexture = RenderTargetTexture;
  19539. })(BABYLON || (BABYLON = {}));
  19540. var BABYLON;
  19541. (function (BABYLON) {
  19542. var ProceduralTexture = (function (_super) {
  19543. __extends(ProceduralTexture, _super);
  19544. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  19545. if (generateMipMaps === void 0) { generateMipMaps = true; }
  19546. if (isCube === void 0) { isCube = false; }
  19547. _super.call(this, null, scene, !generateMipMaps);
  19548. this.isCube = isCube;
  19549. this.isEnabled = true;
  19550. this._currentRefreshId = -1;
  19551. this._refreshRate = 1;
  19552. this._vertexDeclaration = [2];
  19553. this._vertexStrideSize = 2 * 4;
  19554. this._uniforms = new Array();
  19555. this._samplers = new Array();
  19556. this._textures = new Array();
  19557. this._floats = new Array();
  19558. this._floatsArrays = {};
  19559. this._colors3 = new Array();
  19560. this._colors4 = new Array();
  19561. this._vectors2 = new Array();
  19562. this._vectors3 = new Array();
  19563. this._matrices = new Array();
  19564. this._fallbackTextureUsed = false;
  19565. scene._proceduralTextures.push(this);
  19566. this.name = name;
  19567. this.isRenderTarget = true;
  19568. this._size = size;
  19569. this._generateMipMaps = generateMipMaps;
  19570. this.setFragment(fragment);
  19571. this._fallbackTexture = fallbackTexture;
  19572. if (isCube) {
  19573. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  19574. this.setFloat("face", 0);
  19575. }
  19576. else {
  19577. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  19578. }
  19579. // VBO
  19580. var vertices = [];
  19581. vertices.push(1, 1);
  19582. vertices.push(-1, 1);
  19583. vertices.push(-1, -1);
  19584. vertices.push(1, -1);
  19585. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  19586. // Indices
  19587. var indices = [];
  19588. indices.push(0);
  19589. indices.push(1);
  19590. indices.push(2);
  19591. indices.push(0);
  19592. indices.push(2);
  19593. indices.push(3);
  19594. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19595. }
  19596. ProceduralTexture.prototype.reset = function () {
  19597. if (this._effect === undefined) {
  19598. return;
  19599. }
  19600. var engine = this.getScene().getEngine();
  19601. engine._releaseEffect(this._effect);
  19602. };
  19603. ProceduralTexture.prototype.isReady = function () {
  19604. var _this = this;
  19605. var engine = this.getScene().getEngine();
  19606. var shaders;
  19607. if (!this._fragment) {
  19608. return false;
  19609. }
  19610. if (this._fallbackTextureUsed) {
  19611. return true;
  19612. }
  19613. if (this._fragment.fragmentElement !== undefined) {
  19614. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  19615. }
  19616. else {
  19617. shaders = { vertex: "procedural", fragment: this._fragment };
  19618. }
  19619. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  19620. _this.releaseInternalTexture();
  19621. if (_this._fallbackTexture) {
  19622. _this._texture = _this._fallbackTexture._texture;
  19623. _this._texture.references++;
  19624. }
  19625. _this._fallbackTextureUsed = true;
  19626. });
  19627. return this._effect.isReady();
  19628. };
  19629. ProceduralTexture.prototype.resetRefreshCounter = function () {
  19630. this._currentRefreshId = -1;
  19631. };
  19632. ProceduralTexture.prototype.setFragment = function (fragment) {
  19633. this._fragment = fragment;
  19634. };
  19635. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  19636. get: function () {
  19637. return this._refreshRate;
  19638. },
  19639. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  19640. set: function (value) {
  19641. this._refreshRate = value;
  19642. this.resetRefreshCounter();
  19643. },
  19644. enumerable: true,
  19645. configurable: true
  19646. });
  19647. ProceduralTexture.prototype._shouldRender = function () {
  19648. if (!this.isEnabled || !this.isReady() || !this._texture) {
  19649. return false;
  19650. }
  19651. if (this._fallbackTextureUsed) {
  19652. return false;
  19653. }
  19654. if (this._currentRefreshId === -1) {
  19655. this._currentRefreshId = 1;
  19656. return true;
  19657. }
  19658. if (this.refreshRate === this._currentRefreshId) {
  19659. this._currentRefreshId = 1;
  19660. return true;
  19661. }
  19662. this._currentRefreshId++;
  19663. return false;
  19664. };
  19665. ProceduralTexture.prototype.getRenderSize = function () {
  19666. return this._size;
  19667. };
  19668. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  19669. if (this._fallbackTextureUsed) {
  19670. return;
  19671. }
  19672. this.releaseInternalTexture();
  19673. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  19674. };
  19675. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  19676. if (this._uniforms.indexOf(uniformName) === -1) {
  19677. this._uniforms.push(uniformName);
  19678. }
  19679. };
  19680. ProceduralTexture.prototype.setTexture = function (name, texture) {
  19681. if (this._samplers.indexOf(name) === -1) {
  19682. this._samplers.push(name);
  19683. }
  19684. this._textures[name] = texture;
  19685. return this;
  19686. };
  19687. ProceduralTexture.prototype.setFloat = function (name, value) {
  19688. this._checkUniform(name);
  19689. this._floats[name] = value;
  19690. return this;
  19691. };
  19692. ProceduralTexture.prototype.setFloats = function (name, value) {
  19693. this._checkUniform(name);
  19694. this._floatsArrays[name] = value;
  19695. return this;
  19696. };
  19697. ProceduralTexture.prototype.setColor3 = function (name, value) {
  19698. this._checkUniform(name);
  19699. this._colors3[name] = value;
  19700. return this;
  19701. };
  19702. ProceduralTexture.prototype.setColor4 = function (name, value) {
  19703. this._checkUniform(name);
  19704. this._colors4[name] = value;
  19705. return this;
  19706. };
  19707. ProceduralTexture.prototype.setVector2 = function (name, value) {
  19708. this._checkUniform(name);
  19709. this._vectors2[name] = value;
  19710. return this;
  19711. };
  19712. ProceduralTexture.prototype.setVector3 = function (name, value) {
  19713. this._checkUniform(name);
  19714. this._vectors3[name] = value;
  19715. return this;
  19716. };
  19717. ProceduralTexture.prototype.setMatrix = function (name, value) {
  19718. this._checkUniform(name);
  19719. this._matrices[name] = value;
  19720. return this;
  19721. };
  19722. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  19723. var scene = this.getScene();
  19724. var engine = scene.getEngine();
  19725. // Render
  19726. engine.enableEffect(this._effect);
  19727. engine.setState(false);
  19728. // Texture
  19729. for (var name in this._textures) {
  19730. this._effect.setTexture(name, this._textures[name]);
  19731. }
  19732. // Float
  19733. for (name in this._floats) {
  19734. this._effect.setFloat(name, this._floats[name]);
  19735. }
  19736. // Floats
  19737. for (name in this._floatsArrays) {
  19738. this._effect.setArray(name, this._floatsArrays[name]);
  19739. }
  19740. // Color3
  19741. for (name in this._colors3) {
  19742. this._effect.setColor3(name, this._colors3[name]);
  19743. }
  19744. // Color4
  19745. for (name in this._colors4) {
  19746. var color = this._colors4[name];
  19747. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19748. }
  19749. // Vector2
  19750. for (name in this._vectors2) {
  19751. this._effect.setVector2(name, this._vectors2[name]);
  19752. }
  19753. // Vector3
  19754. for (name in this._vectors3) {
  19755. this._effect.setVector3(name, this._vectors3[name]);
  19756. }
  19757. // Matrix
  19758. for (name in this._matrices) {
  19759. this._effect.setMatrix(name, this._matrices[name]);
  19760. }
  19761. // VBOs
  19762. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  19763. if (this.isCube) {
  19764. for (var face = 0; face < 6; face++) {
  19765. engine.bindFramebuffer(this._texture, face);
  19766. this._effect.setFloat("face", face);
  19767. // Clear
  19768. engine.clear(scene.clearColor, true, true);
  19769. // Draw order
  19770. engine.draw(true, 0, 6);
  19771. // Mipmaps
  19772. if (face === 5) {
  19773. engine.generateMipMapsForCubemap(this._texture);
  19774. }
  19775. }
  19776. }
  19777. else {
  19778. engine.bindFramebuffer(this._texture);
  19779. // Clear
  19780. engine.clear(scene.clearColor, true, true);
  19781. // Draw order
  19782. engine.draw(true, 0, 6);
  19783. }
  19784. // Unbind
  19785. engine.unBindFramebuffer(this._texture, this.isCube);
  19786. if (this.onGenerated) {
  19787. this.onGenerated();
  19788. }
  19789. };
  19790. ProceduralTexture.prototype.clone = function () {
  19791. var textureSize = this.getSize();
  19792. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  19793. // Base texture
  19794. newTexture.hasAlpha = this.hasAlpha;
  19795. newTexture.level = this.level;
  19796. // RenderTarget Texture
  19797. newTexture.coordinatesMode = this.coordinatesMode;
  19798. return newTexture;
  19799. };
  19800. ProceduralTexture.prototype.dispose = function () {
  19801. var index = this.getScene()._proceduralTextures.indexOf(this);
  19802. if (index >= 0) {
  19803. this.getScene()._proceduralTextures.splice(index, 1);
  19804. }
  19805. _super.prototype.dispose.call(this);
  19806. };
  19807. return ProceduralTexture;
  19808. })(BABYLON.Texture);
  19809. BABYLON.ProceduralTexture = ProceduralTexture;
  19810. })(BABYLON || (BABYLON = {}));
  19811. var BABYLON;
  19812. (function (BABYLON) {
  19813. var MirrorTexture = (function (_super) {
  19814. __extends(MirrorTexture, _super);
  19815. function MirrorTexture(name, size, scene, generateMipMaps) {
  19816. var _this = this;
  19817. _super.call(this, name, size, scene, generateMipMaps, true);
  19818. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  19819. this._transformMatrix = BABYLON.Matrix.Zero();
  19820. this._mirrorMatrix = BABYLON.Matrix.Zero();
  19821. this.onBeforeRender = function () {
  19822. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  19823. _this._savedViewMatrix = scene.getViewMatrix();
  19824. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  19825. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  19826. scene.clipPlane = _this.mirrorPlane;
  19827. scene.getEngine().cullBackFaces = false;
  19828. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  19829. };
  19830. this.onAfterRender = function () {
  19831. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  19832. scene.getEngine().cullBackFaces = true;
  19833. scene._mirroredCameraPosition = null;
  19834. delete scene.clipPlane;
  19835. };
  19836. }
  19837. MirrorTexture.prototype.clone = function () {
  19838. var textureSize = this.getSize();
  19839. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19840. // Base texture
  19841. newTexture.hasAlpha = this.hasAlpha;
  19842. newTexture.level = this.level;
  19843. // Mirror Texture
  19844. newTexture.mirrorPlane = this.mirrorPlane.clone();
  19845. newTexture.renderList = this.renderList.slice(0);
  19846. return newTexture;
  19847. };
  19848. MirrorTexture.prototype.serialize = function () {
  19849. if (!this.name) {
  19850. return null;
  19851. }
  19852. var serializationObject = _super.prototype.serialize.call(this);
  19853. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  19854. return serializationObject;
  19855. };
  19856. return MirrorTexture;
  19857. })(BABYLON.RenderTargetTexture);
  19858. BABYLON.MirrorTexture = MirrorTexture;
  19859. })(BABYLON || (BABYLON = {}));
  19860. var BABYLON;
  19861. (function (BABYLON) {
  19862. /**
  19863. * Creates a refraction texture used by refraction channel of the standard material.
  19864. * @param name the texture name
  19865. * @param size size of the underlying texture
  19866. * @param scene root scene
  19867. */
  19868. var RefractionTexture = (function (_super) {
  19869. __extends(RefractionTexture, _super);
  19870. function RefractionTexture(name, size, scene, generateMipMaps) {
  19871. var _this = this;
  19872. _super.call(this, name, size, scene, generateMipMaps, true);
  19873. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  19874. this.depth = 2.0;
  19875. this.onBeforeRender = function () {
  19876. scene.clipPlane = _this.refractionPlane;
  19877. };
  19878. this.onAfterRender = function () {
  19879. delete scene.clipPlane;
  19880. };
  19881. }
  19882. RefractionTexture.prototype.clone = function () {
  19883. var textureSize = this.getSize();
  19884. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19885. // Base texture
  19886. newTexture.hasAlpha = this.hasAlpha;
  19887. newTexture.level = this.level;
  19888. // Refraction Texture
  19889. newTexture.refractionPlane = this.refractionPlane.clone();
  19890. newTexture.renderList = this.renderList.slice(0);
  19891. newTexture.depth = this.depth;
  19892. return newTexture;
  19893. };
  19894. RefractionTexture.prototype.serialize = function () {
  19895. if (!this.name) {
  19896. return null;
  19897. }
  19898. var serializationObject = _super.prototype.serialize.call(this);
  19899. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  19900. serializationObject.depth = this.depth;
  19901. return serializationObject;
  19902. };
  19903. return RefractionTexture;
  19904. })(BABYLON.RenderTargetTexture);
  19905. BABYLON.RefractionTexture = RefractionTexture;
  19906. })(BABYLON || (BABYLON = {}));
  19907. var BABYLON;
  19908. (function (BABYLON) {
  19909. var DynamicTexture = (function (_super) {
  19910. __extends(DynamicTexture, _super);
  19911. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  19912. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  19913. _super.call(this, null, scene, !generateMipMaps);
  19914. this.name = name;
  19915. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19916. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19917. this._generateMipMaps = generateMipMaps;
  19918. if (options.getContext) {
  19919. this._canvas = options;
  19920. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  19921. }
  19922. else {
  19923. this._canvas = document.createElement("canvas");
  19924. if (options.width) {
  19925. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  19926. }
  19927. else {
  19928. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  19929. }
  19930. }
  19931. var textureSize = this.getSize();
  19932. this._canvas.width = textureSize.width;
  19933. this._canvas.height = textureSize.height;
  19934. this._context = this._canvas.getContext("2d");
  19935. }
  19936. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  19937. get: function () {
  19938. return true;
  19939. },
  19940. enumerable: true,
  19941. configurable: true
  19942. });
  19943. DynamicTexture.prototype.scale = function (ratio) {
  19944. var textureSize = this.getSize();
  19945. textureSize.width *= ratio;
  19946. textureSize.height *= ratio;
  19947. this._canvas.width = textureSize.width;
  19948. this._canvas.height = textureSize.height;
  19949. this.releaseInternalTexture();
  19950. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  19951. };
  19952. DynamicTexture.prototype.getContext = function () {
  19953. return this._context;
  19954. };
  19955. DynamicTexture.prototype.clear = function () {
  19956. var size = this.getSize();
  19957. this._context.fillRect(0, 0, size.width, size.height);
  19958. };
  19959. DynamicTexture.prototype.update = function (invertY) {
  19960. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  19961. };
  19962. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  19963. if (update === void 0) { update = true; }
  19964. var size = this.getSize();
  19965. if (clearColor) {
  19966. this._context.fillStyle = clearColor;
  19967. this._context.fillRect(0, 0, size.width, size.height);
  19968. }
  19969. this._context.font = font;
  19970. if (x === null) {
  19971. var textSize = this._context.measureText(text);
  19972. x = (size.width - textSize.width) / 2;
  19973. }
  19974. this._context.fillStyle = color;
  19975. this._context.fillText(text, x, y);
  19976. if (update) {
  19977. this.update(invertY);
  19978. }
  19979. };
  19980. DynamicTexture.prototype.clone = function () {
  19981. var textureSize = this.getSize();
  19982. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  19983. // Base texture
  19984. newTexture.hasAlpha = this.hasAlpha;
  19985. newTexture.level = this.level;
  19986. // Dynamic Texture
  19987. newTexture.wrapU = this.wrapU;
  19988. newTexture.wrapV = this.wrapV;
  19989. return newTexture;
  19990. };
  19991. return DynamicTexture;
  19992. })(BABYLON.Texture);
  19993. BABYLON.DynamicTexture = DynamicTexture;
  19994. })(BABYLON || (BABYLON = {}));
  19995. var BABYLON;
  19996. (function (BABYLON) {
  19997. var VideoTexture = (function (_super) {
  19998. __extends(VideoTexture, _super);
  19999. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  20000. var _this = this;
  20001. if (generateMipMaps === void 0) { generateMipMaps = false; }
  20002. if (invertY === void 0) { invertY = false; }
  20003. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20004. _super.call(this, null, scene, !generateMipMaps, invertY);
  20005. this._autoLaunch = true;
  20006. this.name = name;
  20007. this.video = document.createElement("video");
  20008. this.video.autoplay = false;
  20009. this.video.loop = true;
  20010. this.video.addEventListener("canplaythrough", function () {
  20011. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  20012. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20013. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20014. }
  20015. else {
  20016. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20017. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20018. generateMipMaps = false;
  20019. }
  20020. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  20021. _this._texture.isReady = true;
  20022. });
  20023. if (urls) {
  20024. urls.forEach(function (url) {
  20025. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  20026. var source = document.createElement("source");
  20027. source.src = url;
  20028. _this.video.appendChild(source);
  20029. });
  20030. }
  20031. this._lastUpdate = BABYLON.Tools.Now;
  20032. }
  20033. VideoTexture.prototype.update = function () {
  20034. if (this._autoLaunch) {
  20035. this._autoLaunch = false;
  20036. this.video.play();
  20037. }
  20038. var now = BABYLON.Tools.Now;
  20039. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  20040. return false;
  20041. }
  20042. this._lastUpdate = now;
  20043. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  20044. return true;
  20045. };
  20046. return VideoTexture;
  20047. })(BABYLON.Texture);
  20048. BABYLON.VideoTexture = VideoTexture;
  20049. })(BABYLON || (BABYLON = {}));
  20050. var BABYLON;
  20051. (function (BABYLON) {
  20052. var CustomProceduralTexture = (function (_super) {
  20053. __extends(CustomProceduralTexture, _super);
  20054. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  20055. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  20056. this._animate = true;
  20057. this._time = 0;
  20058. this._texturePath = texturePath;
  20059. //Try to load json
  20060. this.loadJson(texturePath);
  20061. this.refreshRate = 1;
  20062. }
  20063. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  20064. var _this = this;
  20065. var that = this;
  20066. function noConfigFile() {
  20067. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  20068. try {
  20069. that.setFragment(that._texturePath);
  20070. }
  20071. catch (ex) {
  20072. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  20073. }
  20074. }
  20075. var configFileUrl = jsonUrl + "/config.json";
  20076. var xhr = new XMLHttpRequest();
  20077. xhr.open("GET", configFileUrl, true);
  20078. xhr.addEventListener("load", function () {
  20079. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  20080. try {
  20081. _this._config = JSON.parse(xhr.response);
  20082. _this.updateShaderUniforms();
  20083. _this.updateTextures();
  20084. _this.setFragment(_this._texturePath + "/custom");
  20085. _this._animate = _this._config.animate;
  20086. _this.refreshRate = _this._config.refreshrate;
  20087. }
  20088. catch (ex) {
  20089. noConfigFile();
  20090. }
  20091. }
  20092. else {
  20093. noConfigFile();
  20094. }
  20095. }, false);
  20096. xhr.addEventListener("error", function () {
  20097. noConfigFile();
  20098. }, false);
  20099. try {
  20100. xhr.send();
  20101. }
  20102. catch (ex) {
  20103. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  20104. }
  20105. };
  20106. CustomProceduralTexture.prototype.isReady = function () {
  20107. if (!_super.prototype.isReady.call(this)) {
  20108. return false;
  20109. }
  20110. for (var name in this._textures) {
  20111. var texture = this._textures[name];
  20112. if (!texture.isReady()) {
  20113. return false;
  20114. }
  20115. }
  20116. return true;
  20117. };
  20118. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  20119. if (this._animate) {
  20120. this._time += this.getScene().getAnimationRatio() * 0.03;
  20121. this.updateShaderUniforms();
  20122. }
  20123. _super.prototype.render.call(this, useCameraPostProcess);
  20124. };
  20125. CustomProceduralTexture.prototype.updateTextures = function () {
  20126. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  20127. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  20128. }
  20129. };
  20130. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  20131. if (this._config) {
  20132. for (var j = 0; j < this._config.uniforms.length; j++) {
  20133. var uniform = this._config.uniforms[j];
  20134. switch (uniform.type) {
  20135. case "float":
  20136. this.setFloat(uniform.name, uniform.value);
  20137. break;
  20138. case "color3":
  20139. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  20140. break;
  20141. case "color4":
  20142. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  20143. break;
  20144. case "vector2":
  20145. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  20146. break;
  20147. case "vector3":
  20148. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  20149. break;
  20150. }
  20151. }
  20152. }
  20153. this.setFloat("time", this._time);
  20154. };
  20155. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  20156. get: function () {
  20157. return this._animate;
  20158. },
  20159. set: function (value) {
  20160. this._animate = value;
  20161. },
  20162. enumerable: true,
  20163. configurable: true
  20164. });
  20165. return CustomProceduralTexture;
  20166. })(BABYLON.ProceduralTexture);
  20167. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  20168. })(BABYLON || (BABYLON = {}));
  20169. var BABYLON;
  20170. (function (BABYLON) {
  20171. var EffectFallbacks = (function () {
  20172. function EffectFallbacks() {
  20173. this._defines = {};
  20174. this._currentRank = 32;
  20175. this._maxRank = -1;
  20176. }
  20177. EffectFallbacks.prototype.addFallback = function (rank, define) {
  20178. if (!this._defines[rank]) {
  20179. if (rank < this._currentRank) {
  20180. this._currentRank = rank;
  20181. }
  20182. if (rank > this._maxRank) {
  20183. this._maxRank = rank;
  20184. }
  20185. this._defines[rank] = new Array();
  20186. }
  20187. this._defines[rank].push(define);
  20188. };
  20189. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  20190. this._meshRank = rank;
  20191. this._mesh = mesh;
  20192. if (rank > this._maxRank) {
  20193. this._maxRank = rank;
  20194. }
  20195. };
  20196. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  20197. get: function () {
  20198. return this._currentRank <= this._maxRank;
  20199. },
  20200. enumerable: true,
  20201. configurable: true
  20202. });
  20203. EffectFallbacks.prototype.reduce = function (currentDefines) {
  20204. var currentFallbacks = this._defines[this._currentRank];
  20205. for (var index = 0; index < currentFallbacks.length; index++) {
  20206. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  20207. }
  20208. if (this._mesh && this._currentRank === this._meshRank) {
  20209. this._mesh.computeBonesUsingShaders = false;
  20210. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  20211. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  20212. }
  20213. this._currentRank++;
  20214. return currentDefines;
  20215. };
  20216. return EffectFallbacks;
  20217. })();
  20218. BABYLON.EffectFallbacks = EffectFallbacks;
  20219. var Effect = (function () {
  20220. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  20221. var _this = this;
  20222. this._isReady = false;
  20223. this._compilationError = "";
  20224. this._valueCache = [];
  20225. this._engine = engine;
  20226. this.name = baseName;
  20227. this.defines = defines;
  20228. this._uniformsNames = uniformsNames.concat(samplers);
  20229. this._samplers = samplers;
  20230. this._attributesNames = attributesNames;
  20231. this.onError = onError;
  20232. this.onCompiled = onCompiled;
  20233. var vertexSource;
  20234. var fragmentSource;
  20235. if (baseName.vertexElement) {
  20236. vertexSource = document.getElementById(baseName.vertexElement);
  20237. if (!vertexSource) {
  20238. vertexSource = baseName.vertexElement;
  20239. }
  20240. }
  20241. else {
  20242. vertexSource = baseName.vertex || baseName;
  20243. }
  20244. if (baseName.fragmentElement) {
  20245. fragmentSource = document.getElementById(baseName.fragmentElement);
  20246. if (!fragmentSource) {
  20247. fragmentSource = baseName.fragmentElement;
  20248. }
  20249. }
  20250. else {
  20251. fragmentSource = baseName.fragment || baseName;
  20252. }
  20253. this._loadVertexShader(vertexSource, function (vertexCode) {
  20254. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  20255. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  20256. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  20257. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  20258. });
  20259. });
  20260. });
  20261. });
  20262. }
  20263. // Properties
  20264. Effect.prototype.isReady = function () {
  20265. return this._isReady;
  20266. };
  20267. Effect.prototype.getProgram = function () {
  20268. return this._program;
  20269. };
  20270. Effect.prototype.getAttributesNames = function () {
  20271. return this._attributesNames;
  20272. };
  20273. Effect.prototype.getAttributeLocation = function (index) {
  20274. return this._attributes[index];
  20275. };
  20276. Effect.prototype.getAttributeLocationByName = function (name) {
  20277. var index = this._attributesNames.indexOf(name);
  20278. return this._attributes[index];
  20279. };
  20280. Effect.prototype.getAttributesCount = function () {
  20281. return this._attributes.length;
  20282. };
  20283. Effect.prototype.getUniformIndex = function (uniformName) {
  20284. return this._uniformsNames.indexOf(uniformName);
  20285. };
  20286. Effect.prototype.getUniform = function (uniformName) {
  20287. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  20288. };
  20289. Effect.prototype.getSamplers = function () {
  20290. return this._samplers;
  20291. };
  20292. Effect.prototype.getCompilationError = function () {
  20293. return this._compilationError;
  20294. };
  20295. // Methods
  20296. Effect.prototype._loadVertexShader = function (vertex, callback) {
  20297. // DOM element ?
  20298. if (vertex instanceof HTMLElement) {
  20299. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  20300. callback(vertexCode);
  20301. return;
  20302. }
  20303. // Is in local store ?
  20304. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  20305. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  20306. return;
  20307. }
  20308. var vertexShaderUrl;
  20309. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  20310. vertexShaderUrl = vertex;
  20311. }
  20312. else {
  20313. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  20314. }
  20315. // Vertex shader
  20316. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  20317. };
  20318. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  20319. // DOM element ?
  20320. if (fragment instanceof HTMLElement) {
  20321. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  20322. callback(fragmentCode);
  20323. return;
  20324. }
  20325. // Is in local store ?
  20326. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  20327. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  20328. return;
  20329. }
  20330. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  20331. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  20332. return;
  20333. }
  20334. var fragmentShaderUrl;
  20335. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  20336. fragmentShaderUrl = fragment;
  20337. }
  20338. else {
  20339. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  20340. }
  20341. // Fragment shader
  20342. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  20343. };
  20344. Effect.prototype._dumpShadersName = function () {
  20345. if (this.name.vertexElement) {
  20346. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  20347. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  20348. }
  20349. else if (this.name.vertex) {
  20350. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  20351. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  20352. }
  20353. else {
  20354. BABYLON.Tools.Error("Vertex shader:" + this.name);
  20355. BABYLON.Tools.Error("Fragment shader:" + this.name);
  20356. }
  20357. };
  20358. Effect.prototype._processIncludes = function (sourceCode, callback) {
  20359. var _this = this;
  20360. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  20361. var match = regex.exec(sourceCode);
  20362. var returnValue = new String(sourceCode);
  20363. while (match != null) {
  20364. var includeFile = match[1];
  20365. if (Effect.IncludesShadersStore[includeFile]) {
  20366. // Substitution
  20367. var includeContent = Effect.IncludesShadersStore[includeFile];
  20368. if (match[2]) {
  20369. var splits = match[3].split(",");
  20370. for (var index = 0; index < splits.length; index += 2) {
  20371. var source = new RegExp(splits[index], "g");
  20372. var dest = splits[index + 1];
  20373. includeContent = includeContent.replace(source, dest);
  20374. }
  20375. }
  20376. if (match[4]) {
  20377. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  20378. }
  20379. // Replace
  20380. returnValue = returnValue.replace(match[0], includeContent);
  20381. }
  20382. else {
  20383. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  20384. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  20385. Effect.IncludesShadersStore[includeFile] = fileContent;
  20386. _this._processIncludes(returnValue, callback);
  20387. });
  20388. return;
  20389. }
  20390. match = regex.exec(sourceCode);
  20391. }
  20392. callback(returnValue);
  20393. };
  20394. Effect.prototype._processPrecision = function (source) {
  20395. if (source.indexOf("precision highp float") === -1) {
  20396. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  20397. source = "precision mediump float;\n" + source;
  20398. }
  20399. else {
  20400. source = "precision highp float;\n" + source;
  20401. }
  20402. }
  20403. else {
  20404. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  20405. source = source.replace("precision highp float", "precision mediump float");
  20406. }
  20407. }
  20408. return source;
  20409. };
  20410. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  20411. try {
  20412. var engine = this._engine;
  20413. // Precision
  20414. vertexSourceCode = this._processPrecision(vertexSourceCode);
  20415. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  20416. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  20417. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  20418. this._attributes = engine.getAttributes(this._program, attributesNames);
  20419. for (var index = 0; index < this._samplers.length; index++) {
  20420. var sampler = this.getUniform(this._samplers[index]);
  20421. if (sampler == null) {
  20422. this._samplers.splice(index, 1);
  20423. index--;
  20424. }
  20425. }
  20426. engine.bindSamplers(this);
  20427. this._isReady = true;
  20428. if (this.onCompiled) {
  20429. this.onCompiled(this);
  20430. }
  20431. }
  20432. catch (e) {
  20433. // Is it a problem with precision?
  20434. if (e.message.indexOf("highp") !== -1) {
  20435. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  20436. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  20437. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  20438. return;
  20439. }
  20440. // Let's go through fallbacks then
  20441. if (fallbacks && fallbacks.isMoreFallbacks) {
  20442. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  20443. this._dumpShadersName();
  20444. defines = fallbacks.reduce(defines);
  20445. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  20446. }
  20447. else {
  20448. BABYLON.Tools.Error("Unable to compile effect: ");
  20449. this._dumpShadersName();
  20450. BABYLON.Tools.Error("Defines: " + defines);
  20451. BABYLON.Tools.Error("Error: " + e.message);
  20452. this._compilationError = e.message;
  20453. if (this.onError) {
  20454. this.onError(this, this._compilationError);
  20455. }
  20456. }
  20457. }
  20458. };
  20459. Object.defineProperty(Effect.prototype, "isSupported", {
  20460. get: function () {
  20461. return this._compilationError === "";
  20462. },
  20463. enumerable: true,
  20464. configurable: true
  20465. });
  20466. Effect.prototype._bindTexture = function (channel, texture) {
  20467. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  20468. };
  20469. Effect.prototype.setTexture = function (channel, texture) {
  20470. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  20471. };
  20472. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  20473. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  20474. };
  20475. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  20476. if (!this._valueCache[uniformName]) {
  20477. this._valueCache[uniformName] = new BABYLON.Matrix();
  20478. }
  20479. for (var index = 0; index < 16; index++) {
  20480. this._valueCache[uniformName].m[index] = matrix.m[index];
  20481. }
  20482. };
  20483. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  20484. if (!this._valueCache[uniformName]) {
  20485. this._valueCache[uniformName] = [x, y];
  20486. return;
  20487. }
  20488. this._valueCache[uniformName][0] = x;
  20489. this._valueCache[uniformName][1] = y;
  20490. };
  20491. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  20492. if (!this._valueCache[uniformName]) {
  20493. this._valueCache[uniformName] = [x, y, z];
  20494. return;
  20495. }
  20496. this._valueCache[uniformName][0] = x;
  20497. this._valueCache[uniformName][1] = y;
  20498. this._valueCache[uniformName][2] = z;
  20499. };
  20500. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  20501. if (!this._valueCache[uniformName]) {
  20502. this._valueCache[uniformName] = [x, y, z, w];
  20503. return;
  20504. }
  20505. this._valueCache[uniformName][0] = x;
  20506. this._valueCache[uniformName][1] = y;
  20507. this._valueCache[uniformName][2] = z;
  20508. this._valueCache[uniformName][3] = w;
  20509. };
  20510. Effect.prototype.setArray = function (uniformName, array) {
  20511. this._engine.setArray(this.getUniform(uniformName), array);
  20512. return this;
  20513. };
  20514. Effect.prototype.setArray2 = function (uniformName, array) {
  20515. this._engine.setArray2(this.getUniform(uniformName), array);
  20516. return this;
  20517. };
  20518. Effect.prototype.setArray3 = function (uniformName, array) {
  20519. this._engine.setArray3(this.getUniform(uniformName), array);
  20520. return this;
  20521. };
  20522. Effect.prototype.setArray4 = function (uniformName, array) {
  20523. this._engine.setArray4(this.getUniform(uniformName), array);
  20524. return this;
  20525. };
  20526. Effect.prototype.setMatrices = function (uniformName, matrices) {
  20527. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  20528. return this;
  20529. };
  20530. Effect.prototype.setMatrix = function (uniformName, matrix) {
  20531. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  20532. // return this;
  20533. // this._cacheMatrix(uniformName, matrix);
  20534. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  20535. return this;
  20536. };
  20537. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  20538. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  20539. return this;
  20540. };
  20541. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  20542. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  20543. return this;
  20544. };
  20545. Effect.prototype.setFloat = function (uniformName, value) {
  20546. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  20547. return this;
  20548. this._valueCache[uniformName] = value;
  20549. this._engine.setFloat(this.getUniform(uniformName), value);
  20550. return this;
  20551. };
  20552. Effect.prototype.setBool = function (uniformName, bool) {
  20553. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  20554. return this;
  20555. this._valueCache[uniformName] = bool;
  20556. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  20557. return this;
  20558. };
  20559. Effect.prototype.setVector2 = function (uniformName, vector2) {
  20560. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  20561. return this;
  20562. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  20563. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  20564. return this;
  20565. };
  20566. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  20567. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  20568. return this;
  20569. this._cacheFloat2(uniformName, x, y);
  20570. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  20571. return this;
  20572. };
  20573. Effect.prototype.setVector3 = function (uniformName, vector3) {
  20574. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  20575. return this;
  20576. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  20577. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  20578. return this;
  20579. };
  20580. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  20581. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  20582. return this;
  20583. this._cacheFloat3(uniformName, x, y, z);
  20584. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  20585. return this;
  20586. };
  20587. Effect.prototype.setVector4 = function (uniformName, vector4) {
  20588. 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)
  20589. return this;
  20590. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  20591. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  20592. return this;
  20593. };
  20594. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  20595. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  20596. return this;
  20597. this._cacheFloat4(uniformName, x, y, z, w);
  20598. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  20599. return this;
  20600. };
  20601. Effect.prototype.setColor3 = function (uniformName, color3) {
  20602. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  20603. return this;
  20604. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  20605. this._engine.setColor3(this.getUniform(uniformName), color3);
  20606. return this;
  20607. };
  20608. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  20609. 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)
  20610. return this;
  20611. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  20612. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  20613. return this;
  20614. };
  20615. // Statics
  20616. Effect.ShadersStore = {};
  20617. Effect.IncludesShadersStore = {};
  20618. return Effect;
  20619. })();
  20620. BABYLON.Effect = Effect;
  20621. })(BABYLON || (BABYLON = {}));
  20622. var BABYLON;
  20623. (function (BABYLON) {
  20624. var maxSimultaneousLights = 4;
  20625. var MaterialHelper = (function () {
  20626. function MaterialHelper() {
  20627. }
  20628. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  20629. var lightIndex = 0;
  20630. var needNormals = false;
  20631. for (var index = 0; index < scene.lights.length; index++) {
  20632. var light = scene.lights[index];
  20633. if (!light.isEnabled()) {
  20634. continue;
  20635. }
  20636. // Excluded check
  20637. if (light._excludedMeshesIds.length > 0) {
  20638. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  20639. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  20640. if (excludedMesh) {
  20641. light.excludedMeshes.push(excludedMesh);
  20642. }
  20643. }
  20644. light._excludedMeshesIds = [];
  20645. }
  20646. // Included check
  20647. if (light._includedOnlyMeshesIds.length > 0) {
  20648. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  20649. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  20650. if (includedOnlyMesh) {
  20651. light.includedOnlyMeshes.push(includedOnlyMesh);
  20652. }
  20653. }
  20654. light._includedOnlyMeshesIds = [];
  20655. }
  20656. if (!light.canAffectMesh(mesh)) {
  20657. continue;
  20658. }
  20659. needNormals = true;
  20660. defines["LIGHT" + lightIndex] = true;
  20661. var type;
  20662. if (light instanceof BABYLON.SpotLight) {
  20663. type = "SPOTLIGHT" + lightIndex;
  20664. }
  20665. else if (light instanceof BABYLON.HemisphericLight) {
  20666. type = "HEMILIGHT" + lightIndex;
  20667. }
  20668. else if (light instanceof BABYLON.PointLight) {
  20669. type = "POINTLIGHT" + lightIndex;
  20670. }
  20671. else {
  20672. type = "DIRLIGHT" + lightIndex;
  20673. }
  20674. defines[type] = true;
  20675. // Specular
  20676. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  20677. defines["SPECULARTERM"] = true;
  20678. }
  20679. // Shadows
  20680. if (scene.shadowsEnabled) {
  20681. var shadowGenerator = light.getShadowGenerator();
  20682. if (mesh && mesh.receiveShadows && shadowGenerator) {
  20683. defines["SHADOW" + lightIndex] = true;
  20684. defines["SHADOWS"] = true;
  20685. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  20686. defines["SHADOWVSM" + lightIndex] = true;
  20687. }
  20688. if (shadowGenerator.usePoissonSampling) {
  20689. defines["SHADOWPCF" + lightIndex] = true;
  20690. }
  20691. }
  20692. }
  20693. lightIndex++;
  20694. if (lightIndex === maxSimultaneousLights)
  20695. break;
  20696. }
  20697. return needNormals;
  20698. };
  20699. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  20700. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  20701. if (!defines["LIGHT" + lightIndex]) {
  20702. continue;
  20703. }
  20704. if (lightIndex > 0) {
  20705. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  20706. }
  20707. if (defines["SHADOW" + lightIndex]) {
  20708. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  20709. }
  20710. if (defines["SHADOWPCF" + lightIndex]) {
  20711. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  20712. }
  20713. if (defines["SHADOWVSM" + lightIndex]) {
  20714. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  20715. }
  20716. }
  20717. };
  20718. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  20719. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  20720. fallbacks.addCPUSkinningFallback(0, mesh);
  20721. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20722. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20723. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  20724. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  20725. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  20726. }
  20727. }
  20728. };
  20729. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  20730. if (defines["INSTANCES"]) {
  20731. attribs.push("world0");
  20732. attribs.push("world1");
  20733. attribs.push("world2");
  20734. attribs.push("world3");
  20735. }
  20736. };
  20737. // Bindings
  20738. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  20739. var shadowGenerator = light.getShadowGenerator();
  20740. if (mesh.receiveShadows && shadowGenerator) {
  20741. if (!light.needCube()) {
  20742. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  20743. }
  20744. else {
  20745. if (!depthValuesAlreadySet) {
  20746. depthValuesAlreadySet = true;
  20747. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  20748. }
  20749. }
  20750. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  20751. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  20752. }
  20753. return depthValuesAlreadySet;
  20754. };
  20755. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  20756. if (light instanceof BABYLON.PointLight) {
  20757. // Point Light
  20758. light.transferToEffect(effect, "vLightData" + lightIndex);
  20759. }
  20760. else if (light instanceof BABYLON.DirectionalLight) {
  20761. // Directional Light
  20762. light.transferToEffect(effect, "vLightData" + lightIndex);
  20763. }
  20764. else if (light instanceof BABYLON.SpotLight) {
  20765. // Spot Light
  20766. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  20767. }
  20768. else if (light instanceof BABYLON.HemisphericLight) {
  20769. // Hemispheric Light
  20770. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  20771. }
  20772. };
  20773. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  20774. var lightIndex = 0;
  20775. var depthValuesAlreadySet = false;
  20776. for (var index = 0; index < scene.lights.length; index++) {
  20777. var light = scene.lights[index];
  20778. if (!light.isEnabled()) {
  20779. continue;
  20780. }
  20781. if (!light.canAffectMesh(mesh)) {
  20782. continue;
  20783. }
  20784. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  20785. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  20786. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  20787. if (defines["SPECULARTERM"]) {
  20788. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  20789. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  20790. }
  20791. // Shadows
  20792. if (scene.shadowsEnabled) {
  20793. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  20794. }
  20795. lightIndex++;
  20796. if (lightIndex === maxSimultaneousLights)
  20797. break;
  20798. }
  20799. };
  20800. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  20801. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  20802. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  20803. effect.setColor3("vFogColor", scene.fogColor);
  20804. }
  20805. };
  20806. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  20807. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  20808. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  20809. }
  20810. };
  20811. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  20812. if (defines["LOGARITHMICDEPTH"]) {
  20813. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  20814. }
  20815. };
  20816. MaterialHelper.BindClipPlane = function (effect, scene) {
  20817. if (scene.clipPlane) {
  20818. var clipPlane = scene.clipPlane;
  20819. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20820. }
  20821. };
  20822. return MaterialHelper;
  20823. })();
  20824. BABYLON.MaterialHelper = MaterialHelper;
  20825. })(BABYLON || (BABYLON = {}));
  20826. var BABYLON;
  20827. (function (BABYLON) {
  20828. var FresnelParameters = (function () {
  20829. function FresnelParameters() {
  20830. this.isEnabled = true;
  20831. this.leftColor = BABYLON.Color3.White();
  20832. this.rightColor = BABYLON.Color3.Black();
  20833. this.bias = 0;
  20834. this.power = 1;
  20835. }
  20836. FresnelParameters.prototype.clone = function () {
  20837. var newFresnelParameters = new FresnelParameters();
  20838. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  20839. return new FresnelParameters;
  20840. };
  20841. FresnelParameters.prototype.serialize = function () {
  20842. var serializationObject = {};
  20843. serializationObject.isEnabled = this.isEnabled;
  20844. serializationObject.leftColor = this.leftColor;
  20845. serializationObject.rightColor = this.rightColor;
  20846. serializationObject.bias = this.bias;
  20847. serializationObject.power = this.power;
  20848. return serializationObject;
  20849. };
  20850. FresnelParameters.Parse = function (parsedFresnelParameters) {
  20851. var fresnelParameters = new FresnelParameters();
  20852. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  20853. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  20854. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  20855. fresnelParameters.bias = parsedFresnelParameters.bias;
  20856. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  20857. return fresnelParameters;
  20858. };
  20859. return FresnelParameters;
  20860. })();
  20861. BABYLON.FresnelParameters = FresnelParameters;
  20862. })(BABYLON || (BABYLON = {}));
  20863. var BABYLON;
  20864. (function (BABYLON) {
  20865. var MaterialDefines = (function () {
  20866. function MaterialDefines() {
  20867. }
  20868. MaterialDefines.prototype.isEqual = function (other) {
  20869. for (var index = 0; index < this._keys.length; index++) {
  20870. var prop = this._keys[index];
  20871. if (this[prop] !== other[prop]) {
  20872. return false;
  20873. }
  20874. }
  20875. return true;
  20876. };
  20877. MaterialDefines.prototype.cloneTo = function (other) {
  20878. for (var index = 0; index < this._keys.length; index++) {
  20879. var prop = this._keys[index];
  20880. other[prop] = this[prop];
  20881. }
  20882. };
  20883. MaterialDefines.prototype.reset = function () {
  20884. for (var index = 0; index < this._keys.length; index++) {
  20885. var prop = this._keys[index];
  20886. if (typeof (this[prop]) === "number") {
  20887. this[prop] = 0;
  20888. }
  20889. else {
  20890. this[prop] = false;
  20891. }
  20892. }
  20893. };
  20894. MaterialDefines.prototype.toString = function () {
  20895. var result = "";
  20896. for (var index = 0; index < this._keys.length; index++) {
  20897. var prop = this._keys[index];
  20898. if (typeof (this[prop]) === "number") {
  20899. result += "#define " + prop + " " + this[prop] + "\n";
  20900. }
  20901. else if (this[prop]) {
  20902. result += "#define " + prop + "\n";
  20903. }
  20904. }
  20905. return result;
  20906. };
  20907. return MaterialDefines;
  20908. })();
  20909. BABYLON.MaterialDefines = MaterialDefines;
  20910. var Material = (function () {
  20911. function Material(name, scene, doNotAdd) {
  20912. this.name = name;
  20913. this.checkReadyOnEveryCall = false;
  20914. this.checkReadyOnlyOnce = false;
  20915. this.state = "";
  20916. this.alpha = 1.0;
  20917. this.backFaceCulling = true;
  20918. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  20919. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  20920. this.disableDepthWrite = false;
  20921. this.fogEnabled = true;
  20922. this.pointSize = 1.0;
  20923. this.zOffset = 0;
  20924. this._wasPreviouslyReady = false;
  20925. this._fillMode = Material.TriangleFillMode;
  20926. this.id = name;
  20927. this._scene = scene;
  20928. if (!doNotAdd) {
  20929. scene.materials.push(this);
  20930. }
  20931. }
  20932. Object.defineProperty(Material, "TriangleFillMode", {
  20933. get: function () {
  20934. return Material._TriangleFillMode;
  20935. },
  20936. enumerable: true,
  20937. configurable: true
  20938. });
  20939. Object.defineProperty(Material, "WireFrameFillMode", {
  20940. get: function () {
  20941. return Material._WireFrameFillMode;
  20942. },
  20943. enumerable: true,
  20944. configurable: true
  20945. });
  20946. Object.defineProperty(Material, "PointFillMode", {
  20947. get: function () {
  20948. return Material._PointFillMode;
  20949. },
  20950. enumerable: true,
  20951. configurable: true
  20952. });
  20953. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  20954. get: function () {
  20955. return Material._ClockWiseSideOrientation;
  20956. },
  20957. enumerable: true,
  20958. configurable: true
  20959. });
  20960. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  20961. get: function () {
  20962. return Material._CounterClockWiseSideOrientation;
  20963. },
  20964. enumerable: true,
  20965. configurable: true
  20966. });
  20967. Object.defineProperty(Material.prototype, "wireframe", {
  20968. get: function () {
  20969. return this._fillMode === Material.WireFrameFillMode;
  20970. },
  20971. set: function (value) {
  20972. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  20973. },
  20974. enumerable: true,
  20975. configurable: true
  20976. });
  20977. Object.defineProperty(Material.prototype, "pointsCloud", {
  20978. get: function () {
  20979. return this._fillMode === Material.PointFillMode;
  20980. },
  20981. set: function (value) {
  20982. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  20983. },
  20984. enumerable: true,
  20985. configurable: true
  20986. });
  20987. Object.defineProperty(Material.prototype, "fillMode", {
  20988. get: function () {
  20989. return this._fillMode;
  20990. },
  20991. set: function (value) {
  20992. this._fillMode = value;
  20993. },
  20994. enumerable: true,
  20995. configurable: true
  20996. });
  20997. /**
  20998. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20999. * subclasses should override adding information pertainent to themselves
  21000. */
  21001. Material.prototype.toString = function (fullDetails) {
  21002. var ret = "Name: " + this.name;
  21003. if (fullDetails) {
  21004. }
  21005. return ret;
  21006. };
  21007. Object.defineProperty(Material.prototype, "isFrozen", {
  21008. get: function () {
  21009. return this.checkReadyOnlyOnce;
  21010. },
  21011. enumerable: true,
  21012. configurable: true
  21013. });
  21014. Material.prototype.freeze = function () {
  21015. this.checkReadyOnlyOnce = true;
  21016. };
  21017. Material.prototype.unfreeze = function () {
  21018. this.checkReadyOnlyOnce = false;
  21019. };
  21020. Material.prototype.isReady = function (mesh, useInstances) {
  21021. return true;
  21022. };
  21023. Material.prototype.getEffect = function () {
  21024. return this._effect;
  21025. };
  21026. Material.prototype.getScene = function () {
  21027. return this._scene;
  21028. };
  21029. Material.prototype.needAlphaBlending = function () {
  21030. return (this.alpha < 1.0);
  21031. };
  21032. Material.prototype.needAlphaTesting = function () {
  21033. return false;
  21034. };
  21035. Material.prototype.getAlphaTestTexture = function () {
  21036. return null;
  21037. };
  21038. Material.prototype.trackCreation = function (onCompiled, onError) {
  21039. };
  21040. Material.prototype.markDirty = function () {
  21041. this._wasPreviouslyReady = false;
  21042. };
  21043. Material.prototype._preBind = function () {
  21044. var engine = this._scene.getEngine();
  21045. engine.enableEffect(this._effect);
  21046. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  21047. };
  21048. Material.prototype.bind = function (world, mesh) {
  21049. this._scene._cachedMaterial = this;
  21050. if (this.onBind) {
  21051. this.onBind(this, mesh);
  21052. }
  21053. if (this.disableDepthWrite) {
  21054. var engine = this._scene.getEngine();
  21055. this._cachedDepthWriteState = engine.getDepthWrite();
  21056. engine.setDepthWrite(false);
  21057. }
  21058. };
  21059. Material.prototype.bindOnlyWorldMatrix = function (world) {
  21060. };
  21061. Material.prototype.unbind = function () {
  21062. if (this.disableDepthWrite) {
  21063. var engine = this._scene.getEngine();
  21064. engine.setDepthWrite(this._cachedDepthWriteState);
  21065. }
  21066. };
  21067. Material.prototype.clone = function (name) {
  21068. return null;
  21069. };
  21070. Material.prototype.getBindedMeshes = function () {
  21071. var result = new Array();
  21072. for (var index = 0; index < this._scene.meshes.length; index++) {
  21073. var mesh = this._scene.meshes[index];
  21074. if (mesh.material === this) {
  21075. result.push(mesh);
  21076. }
  21077. }
  21078. return result;
  21079. };
  21080. Material.prototype.dispose = function (forceDisposeEffect) {
  21081. // Animations
  21082. this.getScene().stopAnimation(this);
  21083. // Remove from scene
  21084. var index = this._scene.materials.indexOf(this);
  21085. if (index >= 0) {
  21086. this._scene.materials.splice(index, 1);
  21087. }
  21088. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  21089. if (forceDisposeEffect && this._effect) {
  21090. this._scene.getEngine()._releaseEffect(this._effect);
  21091. this._effect = null;
  21092. }
  21093. // Remove from meshes
  21094. for (index = 0; index < this._scene.meshes.length; index++) {
  21095. var mesh = this._scene.meshes[index];
  21096. if (mesh.material === this) {
  21097. mesh.material = null;
  21098. }
  21099. }
  21100. // Callback
  21101. if (this.onDispose) {
  21102. this.onDispose();
  21103. }
  21104. };
  21105. Material.prototype.serialize = function () {
  21106. return BABYLON.SerializationHelper.Serialize(this);
  21107. };
  21108. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  21109. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  21110. multiMaterial.id = parsedMultiMaterial.id;
  21111. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  21112. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  21113. var subMatId = parsedMultiMaterial.materials[matIndex];
  21114. if (subMatId) {
  21115. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  21116. }
  21117. else {
  21118. multiMaterial.subMaterials.push(null);
  21119. }
  21120. }
  21121. return multiMaterial;
  21122. };
  21123. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  21124. if (!parsedMaterial.customType) {
  21125. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  21126. }
  21127. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  21128. return materialType.Parse(parsedMaterial, scene, rootUrl);
  21129. ;
  21130. };
  21131. Material._TriangleFillMode = 0;
  21132. Material._WireFrameFillMode = 1;
  21133. Material._PointFillMode = 2;
  21134. Material._ClockWiseSideOrientation = 0;
  21135. Material._CounterClockWiseSideOrientation = 1;
  21136. __decorate([
  21137. BABYLON.serialize()
  21138. ], Material.prototype, "id", void 0);
  21139. __decorate([
  21140. BABYLON.serialize()
  21141. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  21142. __decorate([
  21143. BABYLON.serialize()
  21144. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  21145. __decorate([
  21146. BABYLON.serialize()
  21147. ], Material.prototype, "state", void 0);
  21148. __decorate([
  21149. BABYLON.serialize()
  21150. ], Material.prototype, "alpha", void 0);
  21151. __decorate([
  21152. BABYLON.serialize()
  21153. ], Material.prototype, "backFaceCulling", void 0);
  21154. __decorate([
  21155. BABYLON.serialize()
  21156. ], Material.prototype, "sideOrientation", void 0);
  21157. __decorate([
  21158. BABYLON.serialize()
  21159. ], Material.prototype, "alphaMode", void 0);
  21160. __decorate([
  21161. BABYLON.serialize()
  21162. ], Material.prototype, "disableDepthWrite", void 0);
  21163. __decorate([
  21164. BABYLON.serialize()
  21165. ], Material.prototype, "fogEnabled", void 0);
  21166. __decorate([
  21167. BABYLON.serialize()
  21168. ], Material.prototype, "pointSize", void 0);
  21169. __decorate([
  21170. BABYLON.serialize()
  21171. ], Material.prototype, "zOffset", void 0);
  21172. __decorate([
  21173. BABYLON.serialize()
  21174. ], Material.prototype, "wireframe", null);
  21175. __decorate([
  21176. BABYLON.serialize()
  21177. ], Material.prototype, "pointsCloud", null);
  21178. __decorate([
  21179. BABYLON.serialize()
  21180. ], Material.prototype, "fillMode", null);
  21181. return Material;
  21182. })();
  21183. BABYLON.Material = Material;
  21184. })(BABYLON || (BABYLON = {}));
  21185. var BABYLON;
  21186. (function (BABYLON) {
  21187. var StandardMaterialDefines = (function (_super) {
  21188. __extends(StandardMaterialDefines, _super);
  21189. function StandardMaterialDefines() {
  21190. _super.call(this);
  21191. this.DIFFUSE = false;
  21192. this.AMBIENT = false;
  21193. this.OPACITY = false;
  21194. this.OPACITYRGB = false;
  21195. this.REFLECTION = false;
  21196. this.EMISSIVE = false;
  21197. this.SPECULAR = false;
  21198. this.BUMP = false;
  21199. this.PARALLAX = false;
  21200. this.PARALLAXOCCLUSION = false;
  21201. this.SPECULAROVERALPHA = false;
  21202. this.CLIPPLANE = false;
  21203. this.ALPHATEST = false;
  21204. this.ALPHAFROMDIFFUSE = false;
  21205. this.POINTSIZE = false;
  21206. this.FOG = false;
  21207. this.LIGHT0 = false;
  21208. this.LIGHT1 = false;
  21209. this.LIGHT2 = false;
  21210. this.LIGHT3 = false;
  21211. this.SPOTLIGHT0 = false;
  21212. this.SPOTLIGHT1 = false;
  21213. this.SPOTLIGHT2 = false;
  21214. this.SPOTLIGHT3 = false;
  21215. this.HEMILIGHT0 = false;
  21216. this.HEMILIGHT1 = false;
  21217. this.HEMILIGHT2 = false;
  21218. this.HEMILIGHT3 = false;
  21219. this.POINTLIGHT0 = false;
  21220. this.POINTLIGHT1 = false;
  21221. this.POINTLIGHT2 = false;
  21222. this.POINTLIGHT3 = false;
  21223. this.DIRLIGHT0 = false;
  21224. this.DIRLIGHT1 = false;
  21225. this.DIRLIGHT2 = false;
  21226. this.DIRLIGHT3 = false;
  21227. this.SPECULARTERM = false;
  21228. this.SHADOW0 = false;
  21229. this.SHADOW1 = false;
  21230. this.SHADOW2 = false;
  21231. this.SHADOW3 = false;
  21232. this.SHADOWS = false;
  21233. this.SHADOWVSM0 = false;
  21234. this.SHADOWVSM1 = false;
  21235. this.SHADOWVSM2 = false;
  21236. this.SHADOWVSM3 = false;
  21237. this.SHADOWPCF0 = false;
  21238. this.SHADOWPCF1 = false;
  21239. this.SHADOWPCF2 = false;
  21240. this.SHADOWPCF3 = false;
  21241. this.DIFFUSEFRESNEL = false;
  21242. this.OPACITYFRESNEL = false;
  21243. this.REFLECTIONFRESNEL = false;
  21244. this.REFRACTIONFRESNEL = false;
  21245. this.EMISSIVEFRESNEL = false;
  21246. this.FRESNEL = false;
  21247. this.NORMAL = false;
  21248. this.UV1 = false;
  21249. this.UV2 = false;
  21250. this.VERTEXCOLOR = false;
  21251. this.VERTEXALPHA = false;
  21252. this.NUM_BONE_INFLUENCERS = 0;
  21253. this.BonesPerMesh = 0;
  21254. this.INSTANCES = false;
  21255. this.GLOSSINESS = false;
  21256. this.ROUGHNESS = false;
  21257. this.EMISSIVEASILLUMINATION = false;
  21258. this.LINKEMISSIVEWITHDIFFUSE = false;
  21259. this.REFLECTIONFRESNELFROMSPECULAR = false;
  21260. this.LIGHTMAP = false;
  21261. this.USELIGHTMAPASSHADOWMAP = false;
  21262. this.REFLECTIONMAP_3D = false;
  21263. this.REFLECTIONMAP_SPHERICAL = false;
  21264. this.REFLECTIONMAP_PLANAR = false;
  21265. this.REFLECTIONMAP_CUBIC = false;
  21266. this.REFLECTIONMAP_PROJECTION = false;
  21267. this.REFLECTIONMAP_SKYBOX = false;
  21268. this.REFLECTIONMAP_EXPLICIT = false;
  21269. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  21270. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  21271. this.INVERTCUBICMAP = false;
  21272. this.LOGARITHMICDEPTH = false;
  21273. this.REFRACTION = false;
  21274. this.REFRACTIONMAP_3D = false;
  21275. this.REFLECTIONOVERALPHA = false;
  21276. this._keys = Object.keys(this);
  21277. }
  21278. return StandardMaterialDefines;
  21279. })(BABYLON.MaterialDefines);
  21280. var StandardMaterial = (function (_super) {
  21281. __extends(StandardMaterial, _super);
  21282. function StandardMaterial(name, scene) {
  21283. var _this = this;
  21284. _super.call(this, name, scene);
  21285. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21286. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  21287. this.specularColor = new BABYLON.Color3(1, 1, 1);
  21288. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  21289. this.specularPower = 64;
  21290. this.useAlphaFromDiffuseTexture = false;
  21291. this.useEmissiveAsIllumination = false;
  21292. this.linkEmissiveWithDiffuse = false;
  21293. this.useReflectionFresnelFromSpecular = false;
  21294. this.useSpecularOverAlpha = false;
  21295. this.useReflectionOverAlpha = false;
  21296. this.disableLighting = false;
  21297. this.useParallax = false;
  21298. this.useParallaxOcclusion = false;
  21299. this.parallaxScaleBias = 0.05;
  21300. this.roughness = 0;
  21301. this.indexOfRefraction = 0.98;
  21302. this.invertRefractionY = true;
  21303. this.useLightmapAsShadowmap = false;
  21304. this.useGlossinessFromSpecularMapAlpha = false;
  21305. this._renderTargets = new BABYLON.SmartArray(16);
  21306. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  21307. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  21308. this._defines = new StandardMaterialDefines();
  21309. this._cachedDefines = new StandardMaterialDefines();
  21310. this._cachedDefines.BonesPerMesh = -1;
  21311. this.getRenderTargetTextures = function () {
  21312. _this._renderTargets.reset();
  21313. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  21314. _this._renderTargets.push(_this.reflectionTexture);
  21315. }
  21316. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  21317. _this._renderTargets.push(_this.refractionTexture);
  21318. }
  21319. return _this._renderTargets;
  21320. };
  21321. }
  21322. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  21323. get: function () {
  21324. return this._useLogarithmicDepth;
  21325. },
  21326. set: function (value) {
  21327. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  21328. },
  21329. enumerable: true,
  21330. configurable: true
  21331. });
  21332. StandardMaterial.prototype.needAlphaBlending = function () {
  21333. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  21334. };
  21335. StandardMaterial.prototype.needAlphaTesting = function () {
  21336. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  21337. };
  21338. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  21339. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  21340. };
  21341. StandardMaterial.prototype.getAlphaTestTexture = function () {
  21342. return this.diffuseTexture;
  21343. };
  21344. // Methods
  21345. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  21346. if (!mesh) {
  21347. return true;
  21348. }
  21349. if (this._defines.INSTANCES !== useInstances) {
  21350. return false;
  21351. }
  21352. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  21353. return true;
  21354. }
  21355. return false;
  21356. };
  21357. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  21358. if (this.isFrozen) {
  21359. if (this._wasPreviouslyReady) {
  21360. return true;
  21361. }
  21362. }
  21363. var scene = this.getScene();
  21364. if (!this.checkReadyOnEveryCall) {
  21365. if (this._renderId === scene.getRenderId()) {
  21366. if (this._checkCache(scene, mesh, useInstances)) {
  21367. return true;
  21368. }
  21369. }
  21370. }
  21371. var engine = scene.getEngine();
  21372. var needNormals = false;
  21373. var needUVs = false;
  21374. this._defines.reset();
  21375. // Textures
  21376. if (scene.texturesEnabled) {
  21377. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  21378. if (!this.diffuseTexture.isReady()) {
  21379. return false;
  21380. }
  21381. else {
  21382. needUVs = true;
  21383. this._defines.DIFFUSE = true;
  21384. }
  21385. }
  21386. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  21387. if (!this.ambientTexture.isReady()) {
  21388. return false;
  21389. }
  21390. else {
  21391. needUVs = true;
  21392. this._defines.AMBIENT = true;
  21393. }
  21394. }
  21395. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  21396. if (!this.opacityTexture.isReady()) {
  21397. return false;
  21398. }
  21399. else {
  21400. needUVs = true;
  21401. this._defines.OPACITY = true;
  21402. if (this.opacityTexture.getAlphaFromRGB) {
  21403. this._defines.OPACITYRGB = true;
  21404. }
  21405. }
  21406. }
  21407. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  21408. if (!this.reflectionTexture.isReady()) {
  21409. return false;
  21410. }
  21411. else {
  21412. needNormals = true;
  21413. this._defines.REFLECTION = true;
  21414. if (this.roughness > 0) {
  21415. this._defines.ROUGHNESS = true;
  21416. }
  21417. if (this.useReflectionOverAlpha) {
  21418. this._defines.REFLECTIONOVERALPHA = true;
  21419. }
  21420. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  21421. this._defines.INVERTCUBICMAP = true;
  21422. }
  21423. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  21424. switch (this.reflectionTexture.coordinatesMode) {
  21425. case BABYLON.Texture.CUBIC_MODE:
  21426. case BABYLON.Texture.INVCUBIC_MODE:
  21427. this._defines.REFLECTIONMAP_CUBIC = true;
  21428. break;
  21429. case BABYLON.Texture.EXPLICIT_MODE:
  21430. this._defines.REFLECTIONMAP_EXPLICIT = true;
  21431. break;
  21432. case BABYLON.Texture.PLANAR_MODE:
  21433. this._defines.REFLECTIONMAP_PLANAR = true;
  21434. break;
  21435. case BABYLON.Texture.PROJECTION_MODE:
  21436. this._defines.REFLECTIONMAP_PROJECTION = true;
  21437. break;
  21438. case BABYLON.Texture.SKYBOX_MODE:
  21439. this._defines.REFLECTIONMAP_SKYBOX = true;
  21440. break;
  21441. case BABYLON.Texture.SPHERICAL_MODE:
  21442. this._defines.REFLECTIONMAP_SPHERICAL = true;
  21443. break;
  21444. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  21445. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  21446. break;
  21447. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  21448. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  21449. break;
  21450. }
  21451. }
  21452. }
  21453. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  21454. if (!this.emissiveTexture.isReady()) {
  21455. return false;
  21456. }
  21457. else {
  21458. needUVs = true;
  21459. this._defines.EMISSIVE = true;
  21460. }
  21461. }
  21462. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  21463. if (!this.lightmapTexture.isReady()) {
  21464. return false;
  21465. }
  21466. else {
  21467. needUVs = true;
  21468. this._defines.LIGHTMAP = true;
  21469. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  21470. }
  21471. }
  21472. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  21473. if (!this.specularTexture.isReady()) {
  21474. return false;
  21475. }
  21476. else {
  21477. needUVs = true;
  21478. this._defines.SPECULAR = true;
  21479. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  21480. }
  21481. }
  21482. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  21483. if (!this.bumpTexture.isReady()) {
  21484. return false;
  21485. }
  21486. else {
  21487. needUVs = true;
  21488. this._defines.BUMP = true;
  21489. if (this.useParallax) {
  21490. this._defines.PARALLAX = true;
  21491. if (this.useParallaxOcclusion) {
  21492. this._defines.PARALLAXOCCLUSION = true;
  21493. }
  21494. }
  21495. }
  21496. }
  21497. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  21498. if (!this.refractionTexture.isReady()) {
  21499. return false;
  21500. }
  21501. else {
  21502. needUVs = true;
  21503. this._defines.REFRACTION = true;
  21504. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  21505. }
  21506. }
  21507. }
  21508. // Effect
  21509. if (scene.clipPlane) {
  21510. this._defines.CLIPPLANE = true;
  21511. }
  21512. if (engine.getAlphaTesting()) {
  21513. this._defines.ALPHATEST = true;
  21514. }
  21515. if (this._shouldUseAlphaFromDiffuseTexture()) {
  21516. this._defines.ALPHAFROMDIFFUSE = true;
  21517. }
  21518. if (this.useEmissiveAsIllumination) {
  21519. this._defines.EMISSIVEASILLUMINATION = true;
  21520. }
  21521. if (this.linkEmissiveWithDiffuse) {
  21522. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  21523. }
  21524. if (this.useLogarithmicDepth) {
  21525. this._defines.LOGARITHMICDEPTH = true;
  21526. }
  21527. // Point size
  21528. if (this.pointsCloud || scene.forcePointsCloud) {
  21529. this._defines.POINTSIZE = true;
  21530. }
  21531. // Fog
  21532. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21533. this._defines.FOG = true;
  21534. }
  21535. if (scene.lightsEnabled && !this.disableLighting) {
  21536. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  21537. }
  21538. if (StandardMaterial.FresnelEnabled) {
  21539. // Fresnel
  21540. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  21541. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  21542. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  21543. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  21544. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  21545. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  21546. this._defines.DIFFUSEFRESNEL = true;
  21547. }
  21548. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  21549. this._defines.OPACITYFRESNEL = true;
  21550. }
  21551. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  21552. this._defines.REFLECTIONFRESNEL = true;
  21553. if (this.useReflectionFresnelFromSpecular) {
  21554. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  21555. }
  21556. }
  21557. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  21558. this._defines.REFRACTIONFRESNEL = true;
  21559. }
  21560. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  21561. this._defines.EMISSIVEFRESNEL = true;
  21562. }
  21563. needNormals = true;
  21564. this._defines.FRESNEL = true;
  21565. }
  21566. }
  21567. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  21568. this._defines.SPECULAROVERALPHA = true;
  21569. }
  21570. // Attribs
  21571. if (mesh) {
  21572. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21573. this._defines.NORMAL = true;
  21574. }
  21575. if (needUVs) {
  21576. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21577. this._defines.UV1 = true;
  21578. }
  21579. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21580. this._defines.UV2 = true;
  21581. }
  21582. }
  21583. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21584. this._defines.VERTEXCOLOR = true;
  21585. if (mesh.hasVertexAlpha) {
  21586. this._defines.VERTEXALPHA = true;
  21587. }
  21588. }
  21589. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  21590. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  21591. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  21592. }
  21593. // Instances
  21594. if (useInstances) {
  21595. this._defines.INSTANCES = true;
  21596. }
  21597. }
  21598. // Get correct effect
  21599. if (!this._defines.isEqual(this._cachedDefines)) {
  21600. this._defines.cloneTo(this._cachedDefines);
  21601. scene.resetCachedMaterial();
  21602. // Fallbacks
  21603. var fallbacks = new BABYLON.EffectFallbacks();
  21604. if (this._defines.REFLECTION) {
  21605. fallbacks.addFallback(0, "REFLECTION");
  21606. }
  21607. if (this._defines.SPECULAR) {
  21608. fallbacks.addFallback(0, "SPECULAR");
  21609. }
  21610. if (this._defines.BUMP) {
  21611. fallbacks.addFallback(0, "BUMP");
  21612. }
  21613. if (this._defines.PARALLAX) {
  21614. fallbacks.addFallback(1, "PARALLAX");
  21615. }
  21616. if (this._defines.PARALLAXOCCLUSION) {
  21617. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  21618. }
  21619. if (this._defines.SPECULAROVERALPHA) {
  21620. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  21621. }
  21622. if (this._defines.FOG) {
  21623. fallbacks.addFallback(1, "FOG");
  21624. }
  21625. if (this._defines.POINTSIZE) {
  21626. fallbacks.addFallback(0, "POINTSIZE");
  21627. }
  21628. if (this._defines.LOGARITHMICDEPTH) {
  21629. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  21630. }
  21631. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  21632. if (this._defines.SPECULARTERM) {
  21633. fallbacks.addFallback(0, "SPECULARTERM");
  21634. }
  21635. if (this._defines.DIFFUSEFRESNEL) {
  21636. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  21637. }
  21638. if (this._defines.OPACITYFRESNEL) {
  21639. fallbacks.addFallback(2, "OPACITYFRESNEL");
  21640. }
  21641. if (this._defines.REFLECTIONFRESNEL) {
  21642. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  21643. }
  21644. if (this._defines.EMISSIVEFRESNEL) {
  21645. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  21646. }
  21647. if (this._defines.FRESNEL) {
  21648. fallbacks.addFallback(4, "FRESNEL");
  21649. }
  21650. //Attributes
  21651. var attribs = [BABYLON.VertexBuffer.PositionKind];
  21652. if (this._defines.NORMAL) {
  21653. attribs.push(BABYLON.VertexBuffer.NormalKind);
  21654. }
  21655. if (this._defines.UV1) {
  21656. attribs.push(BABYLON.VertexBuffer.UVKind);
  21657. }
  21658. if (this._defines.UV2) {
  21659. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  21660. }
  21661. if (this._defines.VERTEXCOLOR) {
  21662. attribs.push(BABYLON.VertexBuffer.ColorKind);
  21663. }
  21664. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  21665. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  21666. // Legacy browser patch
  21667. var shaderName = "default";
  21668. if (!scene.getEngine().getCaps().standardDerivatives) {
  21669. shaderName = "legacydefault";
  21670. }
  21671. var join = this._defines.toString();
  21672. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  21673. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  21674. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  21675. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  21676. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  21677. "vFogInfos", "vFogColor", "pointSize",
  21678. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  21679. "mBones",
  21680. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  21681. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  21682. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  21683. "logarithmicDepthConstant"
  21684. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  21685. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  21686. ], join, fallbacks, this.onCompiled, this.onError);
  21687. }
  21688. if (!this._effect.isReady()) {
  21689. return false;
  21690. }
  21691. this._renderId = scene.getRenderId();
  21692. this._wasPreviouslyReady = true;
  21693. if (mesh) {
  21694. if (!mesh._materialDefines) {
  21695. mesh._materialDefines = new StandardMaterialDefines();
  21696. }
  21697. this._defines.cloneTo(mesh._materialDefines);
  21698. }
  21699. return true;
  21700. };
  21701. StandardMaterial.prototype.unbind = function () {
  21702. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  21703. this._effect.setTexture("reflection2DSampler", null);
  21704. }
  21705. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  21706. this._effect.setTexture("refraction2DSampler", null);
  21707. }
  21708. _super.prototype.unbind.call(this);
  21709. };
  21710. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21711. this._effect.setMatrix("world", world);
  21712. };
  21713. StandardMaterial.prototype.bind = function (world, mesh) {
  21714. var scene = this.getScene();
  21715. // Matrices
  21716. this.bindOnlyWorldMatrix(world);
  21717. // Bones
  21718. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  21719. if (scene.getCachedMaterial() !== this) {
  21720. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  21721. if (StandardMaterial.FresnelEnabled) {
  21722. // Fresnel
  21723. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  21724. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  21725. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  21726. }
  21727. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  21728. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  21729. }
  21730. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  21731. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  21732. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  21733. }
  21734. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  21735. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  21736. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  21737. }
  21738. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  21739. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  21740. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  21741. }
  21742. }
  21743. // Textures
  21744. if (scene.texturesEnabled) {
  21745. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  21746. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  21747. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  21748. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  21749. }
  21750. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  21751. this._effect.setTexture("ambientSampler", this.ambientTexture);
  21752. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  21753. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  21754. }
  21755. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  21756. this._effect.setTexture("opacitySampler", this.opacityTexture);
  21757. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  21758. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  21759. }
  21760. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  21761. if (this.reflectionTexture.isCube) {
  21762. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  21763. }
  21764. else {
  21765. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  21766. }
  21767. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  21768. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  21769. }
  21770. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  21771. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  21772. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  21773. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  21774. }
  21775. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  21776. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  21777. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  21778. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  21779. }
  21780. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  21781. this._effect.setTexture("specularSampler", this.specularTexture);
  21782. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  21783. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  21784. }
  21785. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  21786. this._effect.setTexture("bumpSampler", this.bumpTexture);
  21787. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  21788. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  21789. }
  21790. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  21791. var depth = 1.0;
  21792. if (this.refractionTexture.isCube) {
  21793. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  21794. }
  21795. else {
  21796. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  21797. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  21798. if (this.refractionTexture.depth) {
  21799. depth = this.refractionTexture.depth;
  21800. }
  21801. }
  21802. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  21803. }
  21804. }
  21805. // Clip plane
  21806. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  21807. // Point size
  21808. if (this.pointsCloud) {
  21809. this._effect.setFloat("pointSize", this.pointSize);
  21810. }
  21811. // Colors
  21812. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  21813. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  21814. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  21815. if (this._defines.SPECULARTERM) {
  21816. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  21817. }
  21818. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  21819. }
  21820. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  21821. // Diffuse
  21822. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  21823. // Lights
  21824. if (scene.lightsEnabled && !this.disableLighting) {
  21825. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  21826. }
  21827. // View
  21828. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  21829. this._effect.setMatrix("view", scene.getViewMatrix());
  21830. }
  21831. // Fog
  21832. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  21833. // Log. depth
  21834. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  21835. }
  21836. _super.prototype.bind.call(this, world, mesh);
  21837. };
  21838. StandardMaterial.prototype.getAnimatables = function () {
  21839. var results = [];
  21840. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  21841. results.push(this.diffuseTexture);
  21842. }
  21843. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  21844. results.push(this.ambientTexture);
  21845. }
  21846. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  21847. results.push(this.opacityTexture);
  21848. }
  21849. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  21850. results.push(this.reflectionTexture);
  21851. }
  21852. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  21853. results.push(this.emissiveTexture);
  21854. }
  21855. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  21856. results.push(this.specularTexture);
  21857. }
  21858. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  21859. results.push(this.bumpTexture);
  21860. }
  21861. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  21862. results.push(this.lightmapTexture);
  21863. }
  21864. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  21865. results.push(this.refractionTexture);
  21866. }
  21867. return results;
  21868. };
  21869. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  21870. if (this.diffuseTexture) {
  21871. this.diffuseTexture.dispose();
  21872. }
  21873. if (this.ambientTexture) {
  21874. this.ambientTexture.dispose();
  21875. }
  21876. if (this.opacityTexture) {
  21877. this.opacityTexture.dispose();
  21878. }
  21879. if (this.reflectionTexture) {
  21880. this.reflectionTexture.dispose();
  21881. }
  21882. if (this.emissiveTexture) {
  21883. this.emissiveTexture.dispose();
  21884. }
  21885. if (this.specularTexture) {
  21886. this.specularTexture.dispose();
  21887. }
  21888. if (this.bumpTexture) {
  21889. this.bumpTexture.dispose();
  21890. }
  21891. if (this.lightmapTexture) {
  21892. this.lightmapTexture.dispose();
  21893. }
  21894. if (this.refractionTexture) {
  21895. this.refractionTexture.dispose();
  21896. }
  21897. _super.prototype.dispose.call(this, forceDisposeEffect);
  21898. };
  21899. StandardMaterial.prototype.clone = function (name) {
  21900. var _this = this;
  21901. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  21902. };
  21903. StandardMaterial.prototype.serialize = function () {
  21904. return BABYLON.SerializationHelper.Serialize(this);
  21905. };
  21906. // Statics
  21907. StandardMaterial.Parse = function (source, scene, rootUrl) {
  21908. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  21909. };
  21910. // Flags used to enable or disable a type of texture for all Standard Materials
  21911. StandardMaterial.DiffuseTextureEnabled = true;
  21912. StandardMaterial.AmbientTextureEnabled = true;
  21913. StandardMaterial.OpacityTextureEnabled = true;
  21914. StandardMaterial.ReflectionTextureEnabled = true;
  21915. StandardMaterial.EmissiveTextureEnabled = true;
  21916. StandardMaterial.SpecularTextureEnabled = true;
  21917. StandardMaterial.BumpTextureEnabled = true;
  21918. StandardMaterial.FresnelEnabled = true;
  21919. StandardMaterial.LightmapTextureEnabled = true;
  21920. StandardMaterial.RefractionTextureEnabled = true;
  21921. __decorate([
  21922. BABYLON.serializeAsTexture()
  21923. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  21924. __decorate([
  21925. BABYLON.serializeAsTexture()
  21926. ], StandardMaterial.prototype, "ambientTexture", void 0);
  21927. __decorate([
  21928. BABYLON.serializeAsTexture()
  21929. ], StandardMaterial.prototype, "opacityTexture", void 0);
  21930. __decorate([
  21931. BABYLON.serializeAsTexture()
  21932. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  21933. __decorate([
  21934. BABYLON.serializeAsTexture()
  21935. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  21936. __decorate([
  21937. BABYLON.serializeAsTexture()
  21938. ], StandardMaterial.prototype, "specularTexture", void 0);
  21939. __decorate([
  21940. BABYLON.serializeAsTexture()
  21941. ], StandardMaterial.prototype, "bumpTexture", void 0);
  21942. __decorate([
  21943. BABYLON.serializeAsTexture()
  21944. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  21945. __decorate([
  21946. BABYLON.serializeAsTexture()
  21947. ], StandardMaterial.prototype, "refractionTexture", void 0);
  21948. __decorate([
  21949. BABYLON.serializeAsColor3("ambient")
  21950. ], StandardMaterial.prototype, "ambientColor", void 0);
  21951. __decorate([
  21952. BABYLON.serializeAsColor3("diffuse")
  21953. ], StandardMaterial.prototype, "diffuseColor", void 0);
  21954. __decorate([
  21955. BABYLON.serializeAsColor3("specular")
  21956. ], StandardMaterial.prototype, "specularColor", void 0);
  21957. __decorate([
  21958. BABYLON.serializeAsColor3("emissive")
  21959. ], StandardMaterial.prototype, "emissiveColor", void 0);
  21960. __decorate([
  21961. BABYLON.serialize()
  21962. ], StandardMaterial.prototype, "specularPower", void 0);
  21963. __decorate([
  21964. BABYLON.serialize()
  21965. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  21966. __decorate([
  21967. BABYLON.serialize()
  21968. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  21969. __decorate([
  21970. BABYLON.serialize()
  21971. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  21972. __decorate([
  21973. BABYLON.serialize()
  21974. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  21975. __decorate([
  21976. BABYLON.serialize()
  21977. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  21978. __decorate([
  21979. BABYLON.serialize()
  21980. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  21981. __decorate([
  21982. BABYLON.serialize()
  21983. ], StandardMaterial.prototype, "disableLighting", void 0);
  21984. __decorate([
  21985. BABYLON.serialize()
  21986. ], StandardMaterial.prototype, "useParallax", void 0);
  21987. __decorate([
  21988. BABYLON.serialize()
  21989. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  21990. __decorate([
  21991. BABYLON.serialize()
  21992. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  21993. __decorate([
  21994. BABYLON.serialize()
  21995. ], StandardMaterial.prototype, "roughness", void 0);
  21996. __decorate([
  21997. BABYLON.serialize()
  21998. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  21999. __decorate([
  22000. BABYLON.serialize()
  22001. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  22002. __decorate([
  22003. BABYLON.serialize()
  22004. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  22005. __decorate([
  22006. BABYLON.serializeAsFresnelParameters()
  22007. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  22008. __decorate([
  22009. BABYLON.serializeAsFresnelParameters()
  22010. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  22011. __decorate([
  22012. BABYLON.serializeAsFresnelParameters()
  22013. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  22014. __decorate([
  22015. BABYLON.serializeAsFresnelParameters()
  22016. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  22017. __decorate([
  22018. BABYLON.serializeAsFresnelParameters()
  22019. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  22020. __decorate([
  22021. BABYLON.serialize()
  22022. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  22023. __decorate([
  22024. BABYLON.serialize()
  22025. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  22026. return StandardMaterial;
  22027. })(BABYLON.Material);
  22028. BABYLON.StandardMaterial = StandardMaterial;
  22029. })(BABYLON || (BABYLON = {}));
  22030. var BABYLON;
  22031. (function (BABYLON) {
  22032. var MultiMaterial = (function (_super) {
  22033. __extends(MultiMaterial, _super);
  22034. function MultiMaterial(name, scene) {
  22035. _super.call(this, name, scene, true);
  22036. this.subMaterials = new Array();
  22037. scene.multiMaterials.push(this);
  22038. }
  22039. // Properties
  22040. MultiMaterial.prototype.getSubMaterial = function (index) {
  22041. if (index < 0 || index >= this.subMaterials.length) {
  22042. return this.getScene().defaultMaterial;
  22043. }
  22044. return this.subMaterials[index];
  22045. };
  22046. // Methods
  22047. MultiMaterial.prototype.isReady = function (mesh) {
  22048. for (var index = 0; index < this.subMaterials.length; index++) {
  22049. var subMaterial = this.subMaterials[index];
  22050. if (subMaterial) {
  22051. if (!this.subMaterials[index].isReady(mesh)) {
  22052. return false;
  22053. }
  22054. }
  22055. }
  22056. return true;
  22057. };
  22058. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  22059. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  22060. for (var index = 0; index < this.subMaterials.length; index++) {
  22061. var subMaterial = null;
  22062. if (cloneChildren) {
  22063. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  22064. }
  22065. else {
  22066. subMaterial = this.subMaterials[index];
  22067. }
  22068. newMultiMaterial.subMaterials.push(subMaterial);
  22069. }
  22070. return newMultiMaterial;
  22071. };
  22072. MultiMaterial.prototype.serialize = function () {
  22073. var serializationObject = {};
  22074. serializationObject.name = this.name;
  22075. serializationObject.id = this.id;
  22076. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22077. serializationObject.materials = [];
  22078. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  22079. var subMat = this.subMaterials[matIndex];
  22080. if (subMat) {
  22081. serializationObject.materials.push(subMat.id);
  22082. }
  22083. else {
  22084. serializationObject.materials.push(null);
  22085. }
  22086. }
  22087. return serializationObject;
  22088. };
  22089. return MultiMaterial;
  22090. })(BABYLON.Material);
  22091. BABYLON.MultiMaterial = MultiMaterial;
  22092. })(BABYLON || (BABYLON = {}));
  22093. var BABYLON;
  22094. (function (BABYLON) {
  22095. var SceneLoader = (function () {
  22096. function SceneLoader() {
  22097. }
  22098. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  22099. get: function () {
  22100. return 0;
  22101. },
  22102. enumerable: true,
  22103. configurable: true
  22104. });
  22105. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  22106. get: function () {
  22107. return 1;
  22108. },
  22109. enumerable: true,
  22110. configurable: true
  22111. });
  22112. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  22113. get: function () {
  22114. return 2;
  22115. },
  22116. enumerable: true,
  22117. configurable: true
  22118. });
  22119. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  22120. get: function () {
  22121. return 3;
  22122. },
  22123. enumerable: true,
  22124. configurable: true
  22125. });
  22126. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  22127. get: function () {
  22128. return SceneLoader._ForceFullSceneLoadingForIncremental;
  22129. },
  22130. set: function (value) {
  22131. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  22132. },
  22133. enumerable: true,
  22134. configurable: true
  22135. });
  22136. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  22137. get: function () {
  22138. return SceneLoader._ShowLoadingScreen;
  22139. },
  22140. set: function (value) {
  22141. SceneLoader._ShowLoadingScreen = value;
  22142. },
  22143. enumerable: true,
  22144. configurable: true
  22145. });
  22146. Object.defineProperty(SceneLoader, "loggingLevel", {
  22147. get: function () {
  22148. return SceneLoader._loggingLevel;
  22149. },
  22150. set: function (value) {
  22151. SceneLoader._loggingLevel = value;
  22152. },
  22153. enumerable: true,
  22154. configurable: true
  22155. });
  22156. SceneLoader._getPluginForFilename = function (sceneFilename) {
  22157. var dotPosition = sceneFilename.lastIndexOf(".");
  22158. var queryStringPosition = sceneFilename.indexOf("?");
  22159. if (queryStringPosition === -1) {
  22160. queryStringPosition = sceneFilename.length;
  22161. }
  22162. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  22163. for (var index = 0; index < this._registeredPlugins.length; index++) {
  22164. var plugin = this._registeredPlugins[index];
  22165. if (plugin.extensions.indexOf(extension) !== -1) {
  22166. return plugin;
  22167. }
  22168. }
  22169. return this._registeredPlugins[this._registeredPlugins.length - 1];
  22170. };
  22171. // Public functions
  22172. SceneLoader.GetPluginForExtension = function (extension) {
  22173. for (var index = 0; index < this._registeredPlugins.length; index++) {
  22174. var plugin = this._registeredPlugins[index];
  22175. if (plugin.extensions.indexOf(extension) !== -1) {
  22176. return plugin;
  22177. }
  22178. }
  22179. return null;
  22180. };
  22181. SceneLoader.RegisterPlugin = function (plugin) {
  22182. plugin.extensions = plugin.extensions.toLowerCase();
  22183. SceneLoader._registeredPlugins.push(plugin);
  22184. };
  22185. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  22186. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  22187. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  22188. return;
  22189. }
  22190. var loadingToken = {};
  22191. scene._addPendingData(loadingToken);
  22192. var manifestChecked = function (success) {
  22193. scene.database = database;
  22194. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  22195. var importMeshFromData = function (data) {
  22196. var meshes = [];
  22197. var particleSystems = [];
  22198. var skeletons = [];
  22199. try {
  22200. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  22201. if (onerror) {
  22202. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  22203. }
  22204. scene._removePendingData(loadingToken);
  22205. return;
  22206. }
  22207. }
  22208. catch (e) {
  22209. if (onerror) {
  22210. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  22211. }
  22212. scene._removePendingData(loadingToken);
  22213. return;
  22214. }
  22215. if (onsuccess) {
  22216. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  22217. onsuccess(meshes, particleSystems, skeletons);
  22218. scene._removePendingData(loadingToken);
  22219. }
  22220. };
  22221. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  22222. // Direct load
  22223. importMeshFromData(sceneFilename.substr(5));
  22224. return;
  22225. }
  22226. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  22227. importMeshFromData(data);
  22228. }, progressCallBack, database);
  22229. };
  22230. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  22231. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  22232. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  22233. }
  22234. else {
  22235. // If the scene is a data stream or offline support is not enabled, it's a direct load
  22236. manifestChecked(true);
  22237. }
  22238. };
  22239. /**
  22240. * Load a scene
  22241. * @param rootUrl a string that defines the root url for scene and resources
  22242. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  22243. * @param engine is the instance of BABYLON.Engine to use to create the scene
  22244. */
  22245. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  22246. if (!SceneLoader._warned) {
  22247. BABYLON.Tools.Warn("SceneLoader.Load deprecated since 2.4. Use SceneLoader.Append.");
  22248. SceneLoader._warned = true;
  22249. }
  22250. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  22251. };
  22252. /**
  22253. * Append a scene
  22254. * @param rootUrl a string that defines the root url for scene and resources
  22255. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  22256. * @param scene is the instance of BABYLON.Scene to append to
  22257. */
  22258. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  22259. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  22260. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  22261. return;
  22262. }
  22263. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  22264. var database;
  22265. var loadingToken = {};
  22266. scene._addPendingData(loadingToken);
  22267. if (SceneLoader.ShowLoadingScreen) {
  22268. scene.getEngine().displayLoadingUI();
  22269. }
  22270. var loadSceneFromData = function (data) {
  22271. scene.database = database;
  22272. if (!plugin.load(scene, data, rootUrl)) {
  22273. if (onerror) {
  22274. onerror(scene);
  22275. }
  22276. scene._removePendingData(loadingToken);
  22277. scene.getEngine().hideLoadingUI();
  22278. return;
  22279. }
  22280. if (onsuccess) {
  22281. onsuccess(scene);
  22282. }
  22283. scene._removePendingData(loadingToken);
  22284. if (SceneLoader.ShowLoadingScreen) {
  22285. scene.executeWhenReady(function () {
  22286. scene.getEngine().hideLoadingUI();
  22287. });
  22288. }
  22289. };
  22290. var manifestChecked = function (success) {
  22291. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  22292. };
  22293. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  22294. // Direct load
  22295. loadSceneFromData(sceneFilename.substr(5));
  22296. return;
  22297. }
  22298. if (rootUrl.indexOf("file:") === -1) {
  22299. if (scene.getEngine().enableOfflineSupport) {
  22300. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  22301. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  22302. }
  22303. else {
  22304. manifestChecked(true);
  22305. }
  22306. }
  22307. else {
  22308. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  22309. }
  22310. };
  22311. // Flags
  22312. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  22313. SceneLoader._ShowLoadingScreen = true;
  22314. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  22315. // Members
  22316. SceneLoader._registeredPlugins = new Array();
  22317. return SceneLoader;
  22318. })();
  22319. BABYLON.SceneLoader = SceneLoader;
  22320. ;
  22321. })(BABYLON || (BABYLON = {}));
  22322. var BABYLON;
  22323. (function (BABYLON) {
  22324. var Internals;
  22325. (function (Internals) {
  22326. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  22327. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  22328. var parsedMaterial = parsedData.materials[index];
  22329. if (parsedMaterial.id === id) {
  22330. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  22331. }
  22332. }
  22333. return null;
  22334. };
  22335. var isDescendantOf = function (mesh, names, hierarchyIds) {
  22336. names = (names instanceof Array) ? names : [names];
  22337. for (var i in names) {
  22338. if (mesh.name === names[i]) {
  22339. hierarchyIds.push(mesh.id);
  22340. return true;
  22341. }
  22342. }
  22343. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  22344. hierarchyIds.push(mesh.id);
  22345. return true;
  22346. }
  22347. return false;
  22348. };
  22349. var logOperation = function (operation, producer) {
  22350. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  22351. };
  22352. BABYLON.SceneLoader.RegisterPlugin({
  22353. extensions: ".babylon",
  22354. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  22355. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  22356. // when SceneLoader.debugLogging = true (default), or exception encountered.
  22357. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  22358. // and avoid problems with multiple concurrent .babylon loads.
  22359. var log = "importMesh has failed JSON parse";
  22360. try {
  22361. var parsedData = JSON.parse(data);
  22362. log = "";
  22363. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  22364. var loadedSkeletonsIds = [];
  22365. var loadedMaterialsIds = [];
  22366. var hierarchyIds = [];
  22367. var index;
  22368. var cache;
  22369. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  22370. var parsedMesh = parsedData.meshes[index];
  22371. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  22372. if (meshesNames instanceof Array) {
  22373. // Remove found mesh name from list.
  22374. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  22375. }
  22376. //Geometry?
  22377. if (parsedMesh.geometryId) {
  22378. //does the file contain geometries?
  22379. if (parsedData.geometries) {
  22380. //find the correct geometry and add it to the scene
  22381. var found = false;
  22382. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  22383. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  22384. return;
  22385. }
  22386. else {
  22387. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  22388. if (parsedGeometryData.id === parsedMesh.geometryId) {
  22389. switch (geometryType) {
  22390. case "boxes":
  22391. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  22392. break;
  22393. case "spheres":
  22394. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  22395. break;
  22396. case "cylinders":
  22397. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  22398. break;
  22399. case "toruses":
  22400. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  22401. break;
  22402. case "grounds":
  22403. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  22404. break;
  22405. case "planes":
  22406. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  22407. break;
  22408. case "torusKnots":
  22409. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  22410. break;
  22411. case "vertexData":
  22412. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  22413. break;
  22414. }
  22415. found = true;
  22416. }
  22417. });
  22418. }
  22419. });
  22420. if (!found) {
  22421. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  22422. }
  22423. }
  22424. }
  22425. // Material ?
  22426. if (parsedMesh.materialId) {
  22427. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  22428. if (!materialFound && parsedData.multiMaterials) {
  22429. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  22430. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  22431. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  22432. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  22433. var subMatId = parsedMultiMaterial.materials[matIndex];
  22434. loadedMaterialsIds.push(subMatId);
  22435. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  22436. log += "\n\tMaterial " + mat.toString(fullDetails);
  22437. }
  22438. loadedMaterialsIds.push(parsedMultiMaterial.id);
  22439. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  22440. materialFound = true;
  22441. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  22442. break;
  22443. }
  22444. }
  22445. }
  22446. if (!materialFound) {
  22447. loadedMaterialsIds.push(parsedMesh.materialId);
  22448. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  22449. if (!mat) {
  22450. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  22451. }
  22452. else {
  22453. log += "\n\tMaterial " + mat.toString(fullDetails);
  22454. }
  22455. }
  22456. }
  22457. // Skeleton ?
  22458. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  22459. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  22460. if (!skeletonAlreadyLoaded) {
  22461. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  22462. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  22463. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  22464. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  22465. skeletons.push(skeleton);
  22466. loadedSkeletonsIds.push(parsedSkeleton.id);
  22467. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  22468. }
  22469. }
  22470. }
  22471. }
  22472. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  22473. meshes.push(mesh);
  22474. log += "\n\tMesh " + mesh.toString(fullDetails);
  22475. }
  22476. }
  22477. // Connecting parents
  22478. var currentMesh;
  22479. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22480. currentMesh = scene.meshes[index];
  22481. if (currentMesh._waitingParentId) {
  22482. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  22483. currentMesh._waitingParentId = undefined;
  22484. }
  22485. }
  22486. // freeze and compute world matrix application
  22487. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22488. currentMesh = scene.meshes[index];
  22489. if (currentMesh._waitingFreezeWorldMatrix) {
  22490. currentMesh.freezeWorldMatrix();
  22491. currentMesh._waitingFreezeWorldMatrix = undefined;
  22492. }
  22493. else {
  22494. currentMesh.computeWorldMatrix(true);
  22495. }
  22496. }
  22497. // Particles
  22498. if (parsedData.particleSystems) {
  22499. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  22500. var parsedParticleSystem = parsedData.particleSystems[index];
  22501. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  22502. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  22503. }
  22504. }
  22505. }
  22506. return true;
  22507. }
  22508. catch (err) {
  22509. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  22510. log = null;
  22511. throw err;
  22512. }
  22513. finally {
  22514. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  22515. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  22516. }
  22517. }
  22518. },
  22519. load: function (scene, data, rootUrl) {
  22520. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  22521. // when SceneLoader.debugLogging = true (default), or exception encountered.
  22522. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  22523. // and avoid problems with multiple concurrent .babylon loads.
  22524. var log = "importScene has failed JSON parse";
  22525. try {
  22526. var parsedData = JSON.parse(data);
  22527. log = "";
  22528. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  22529. // Scene
  22530. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  22531. scene.autoClear = parsedData.autoClear;
  22532. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  22533. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  22534. if (parsedData.gravity) {
  22535. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  22536. }
  22537. // Fog
  22538. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  22539. scene.fogMode = parsedData.fogMode;
  22540. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  22541. scene.fogStart = parsedData.fogStart;
  22542. scene.fogEnd = parsedData.fogEnd;
  22543. scene.fogDensity = parsedData.fogDensity;
  22544. log += "\tFog mode for scene: ";
  22545. switch (scene.fogMode) {
  22546. // getters not compiling, so using hardcoded
  22547. case 1:
  22548. log += "exp\n";
  22549. break;
  22550. case 2:
  22551. log += "exp2\n";
  22552. break;
  22553. case 3:
  22554. log += "linear\n";
  22555. break;
  22556. }
  22557. }
  22558. //Physics
  22559. if (parsedData.physicsEnabled) {
  22560. var physicsPlugin;
  22561. if (parsedData.physicsEngine === "cannon") {
  22562. physicsPlugin = new BABYLON.CannonJSPlugin();
  22563. }
  22564. else if (parsedData.physicsEngine === "oimo") {
  22565. physicsPlugin = new BABYLON.OimoJSPlugin();
  22566. }
  22567. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  22568. //else - default engine, which is currently oimo
  22569. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  22570. scene.enablePhysics(physicsGravity, physicsPlugin);
  22571. }
  22572. //collisions, if defined. otherwise, default is true
  22573. if (parsedData.collisionsEnabled != undefined) {
  22574. scene.collisionsEnabled = parsedData.collisionsEnabled;
  22575. }
  22576. scene.workerCollisions = !!parsedData.workerCollisions;
  22577. var index;
  22578. var cache;
  22579. // Lights
  22580. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  22581. var parsedLight = parsedData.lights[index];
  22582. var light = BABYLON.Light.Parse(parsedLight, scene);
  22583. log += (index === 0 ? "\n\tLights:" : "");
  22584. log += "\n\t\t" + light.toString(fullDetails);
  22585. }
  22586. // Animations
  22587. if (parsedData.animations) {
  22588. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  22589. var parsedAnimation = parsedData.animations[index];
  22590. var animation = BABYLON.Animation.Parse(parsedAnimation);
  22591. scene.animations.push(animation);
  22592. log += (index === 0 ? "\n\tAnimations:" : "");
  22593. log += "\n\t\t" + animation.toString(fullDetails);
  22594. }
  22595. }
  22596. // Materials
  22597. if (parsedData.materials) {
  22598. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  22599. var parsedMaterial = parsedData.materials[index];
  22600. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  22601. log += (index === 0 ? "\n\tMaterials:" : "");
  22602. log += "\n\t\t" + mat.toString(fullDetails);
  22603. }
  22604. }
  22605. if (parsedData.multiMaterials) {
  22606. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  22607. var parsedMultiMaterial = parsedData.multiMaterials[index];
  22608. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  22609. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  22610. log += "\n\t\t" + mmat.toString(fullDetails);
  22611. }
  22612. }
  22613. // Skeletons
  22614. if (parsedData.skeletons) {
  22615. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  22616. var parsedSkeleton = parsedData.skeletons[index];
  22617. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  22618. log += (index === 0 ? "\n\tSkeletons:" : "");
  22619. log += "\n\t\t" + skeleton.toString(fullDetails);
  22620. }
  22621. }
  22622. // Geometries
  22623. var geometries = parsedData.geometries;
  22624. if (geometries) {
  22625. // Boxes
  22626. var boxes = geometries.boxes;
  22627. if (boxes) {
  22628. for (index = 0, cache = boxes.length; index < cache; index++) {
  22629. var parsedBox = boxes[index];
  22630. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  22631. }
  22632. }
  22633. // Spheres
  22634. var spheres = geometries.spheres;
  22635. if (spheres) {
  22636. for (index = 0, cache = spheres.length; index < cache; index++) {
  22637. var parsedSphere = spheres[index];
  22638. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  22639. }
  22640. }
  22641. // Cylinders
  22642. var cylinders = geometries.cylinders;
  22643. if (cylinders) {
  22644. for (index = 0, cache = cylinders.length; index < cache; index++) {
  22645. var parsedCylinder = cylinders[index];
  22646. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  22647. }
  22648. }
  22649. // Toruses
  22650. var toruses = geometries.toruses;
  22651. if (toruses) {
  22652. for (index = 0, cache = toruses.length; index < cache; index++) {
  22653. var parsedTorus = toruses[index];
  22654. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  22655. }
  22656. }
  22657. // Grounds
  22658. var grounds = geometries.grounds;
  22659. if (grounds) {
  22660. for (index = 0, cache = grounds.length; index < cache; index++) {
  22661. var parsedGround = grounds[index];
  22662. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  22663. }
  22664. }
  22665. // Planes
  22666. var planes = geometries.planes;
  22667. if (planes) {
  22668. for (index = 0, cache = planes.length; index < cache; index++) {
  22669. var parsedPlane = planes[index];
  22670. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  22671. }
  22672. }
  22673. // TorusKnots
  22674. var torusKnots = geometries.torusKnots;
  22675. if (torusKnots) {
  22676. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  22677. var parsedTorusKnot = torusKnots[index];
  22678. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  22679. }
  22680. }
  22681. // VertexData
  22682. var vertexData = geometries.vertexData;
  22683. if (vertexData) {
  22684. for (index = 0, cache = vertexData.length; index < cache; index++) {
  22685. var parsedVertexData = vertexData[index];
  22686. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  22687. }
  22688. }
  22689. }
  22690. // Meshes
  22691. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  22692. var parsedMesh = parsedData.meshes[index];
  22693. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  22694. log += (index === 0 ? "\n\tMeshes:" : "");
  22695. log += "\n\t\t" + mesh.toString(fullDetails);
  22696. }
  22697. // Cameras
  22698. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  22699. var parsedCamera = parsedData.cameras[index];
  22700. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  22701. log += (index === 0 ? "\n\tCameras:" : "");
  22702. log += "\n\t\t" + camera.toString(fullDetails);
  22703. }
  22704. if (parsedData.activeCameraID) {
  22705. scene.setActiveCameraByID(parsedData.activeCameraID);
  22706. }
  22707. // Browsing all the graph to connect the dots
  22708. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  22709. var camera = scene.cameras[index];
  22710. if (camera._waitingParentId) {
  22711. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  22712. camera._waitingParentId = undefined;
  22713. }
  22714. }
  22715. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  22716. var light = scene.lights[index];
  22717. if (light._waitingParentId) {
  22718. light.parent = scene.getLastEntryByID(light._waitingParentId);
  22719. light._waitingParentId = undefined;
  22720. }
  22721. }
  22722. // Sounds
  22723. var loadedSounds = [];
  22724. var loadedSound;
  22725. if (BABYLON.AudioEngine && parsedData.sounds) {
  22726. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  22727. var parsedSound = parsedData.sounds[index];
  22728. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  22729. if (!parsedSound.url)
  22730. parsedSound.url = parsedSound.name;
  22731. if (!loadedSounds[parsedSound.url]) {
  22732. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  22733. loadedSounds[parsedSound.url] = loadedSound;
  22734. }
  22735. else {
  22736. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  22737. }
  22738. }
  22739. else {
  22740. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  22741. }
  22742. }
  22743. log += (index === 0 ? "\n\tSounds:" : "");
  22744. log += "\n\t\t" + mat.toString(fullDetails);
  22745. }
  22746. loadedSounds = [];
  22747. // Connect parents & children and parse actions
  22748. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22749. var mesh = scene.meshes[index];
  22750. if (mesh._waitingParentId) {
  22751. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  22752. mesh._waitingParentId = undefined;
  22753. }
  22754. if (mesh._waitingActions) {
  22755. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  22756. mesh._waitingActions = undefined;
  22757. }
  22758. }
  22759. // freeze world matrix application
  22760. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  22761. var currentMesh = scene.meshes[index];
  22762. if (currentMesh._waitingFreezeWorldMatrix) {
  22763. currentMesh.freezeWorldMatrix();
  22764. currentMesh._waitingFreezeWorldMatrix = undefined;
  22765. }
  22766. else {
  22767. currentMesh.computeWorldMatrix(true);
  22768. }
  22769. }
  22770. // Particles Systems
  22771. if (parsedData.particleSystems) {
  22772. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  22773. var parsedParticleSystem = parsedData.particleSystems[index];
  22774. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  22775. }
  22776. }
  22777. // Lens flares
  22778. if (parsedData.lensFlareSystems) {
  22779. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  22780. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  22781. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  22782. }
  22783. }
  22784. // Shadows
  22785. if (parsedData.shadowGenerators) {
  22786. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  22787. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  22788. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  22789. }
  22790. }
  22791. // Actions (scene)
  22792. if (parsedData.actions) {
  22793. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  22794. }
  22795. // Finish
  22796. return true;
  22797. }
  22798. catch (err) {
  22799. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  22800. log = null;
  22801. throw err;
  22802. }
  22803. finally {
  22804. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  22805. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  22806. }
  22807. }
  22808. }
  22809. });
  22810. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22811. })(BABYLON || (BABYLON = {}));
  22812. var BABYLON;
  22813. (function (BABYLON) {
  22814. var SpriteManager = (function () {
  22815. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  22816. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22817. this.name = name;
  22818. this.cellSize = cellSize;
  22819. this.sprites = new Array();
  22820. this.renderingGroupId = 0;
  22821. this.layerMask = 0x0FFFFFFF;
  22822. this.fogEnabled = true;
  22823. this.isPickable = false;
  22824. this._vertexDeclaration = [4, 4, 4, 4];
  22825. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  22826. this._capacity = capacity;
  22827. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  22828. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22829. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22830. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  22831. this._scene = scene;
  22832. this._scene.spriteManagers.push(this);
  22833. // VBO
  22834. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  22835. var indices = [];
  22836. var index = 0;
  22837. for (var count = 0; count < capacity; count++) {
  22838. indices.push(index);
  22839. indices.push(index + 1);
  22840. indices.push(index + 2);
  22841. indices.push(index);
  22842. indices.push(index + 2);
  22843. indices.push(index + 3);
  22844. index += 4;
  22845. }
  22846. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22847. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  22848. // Effects
  22849. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  22850. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  22851. }
  22852. Object.defineProperty(SpriteManager.prototype, "texture", {
  22853. get: function () {
  22854. return this._spriteTexture;
  22855. },
  22856. set: function (value) {
  22857. this._spriteTexture = value;
  22858. },
  22859. enumerable: true,
  22860. configurable: true
  22861. });
  22862. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  22863. var arrayOffset = index * 16;
  22864. if (offsetX === 0)
  22865. offsetX = this._epsilon;
  22866. else if (offsetX === 1)
  22867. offsetX = 1 - this._epsilon;
  22868. if (offsetY === 0)
  22869. offsetY = this._epsilon;
  22870. else if (offsetY === 1)
  22871. offsetY = 1 - this._epsilon;
  22872. this._vertices[arrayOffset] = sprite.position.x;
  22873. this._vertices[arrayOffset + 1] = sprite.position.y;
  22874. this._vertices[arrayOffset + 2] = sprite.position.z;
  22875. this._vertices[arrayOffset + 3] = sprite.angle;
  22876. this._vertices[arrayOffset + 4] = sprite.width;
  22877. this._vertices[arrayOffset + 5] = sprite.height;
  22878. this._vertices[arrayOffset + 6] = offsetX;
  22879. this._vertices[arrayOffset + 7] = offsetY;
  22880. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  22881. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  22882. var offset = (sprite.cellIndex / rowSize) >> 0;
  22883. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  22884. this._vertices[arrayOffset + 11] = offset;
  22885. // Color
  22886. this._vertices[arrayOffset + 12] = sprite.color.r;
  22887. this._vertices[arrayOffset + 13] = sprite.color.g;
  22888. this._vertices[arrayOffset + 14] = sprite.color.b;
  22889. this._vertices[arrayOffset + 15] = sprite.color.a;
  22890. };
  22891. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  22892. var count = Math.min(this._capacity, this.sprites.length);
  22893. var min = BABYLON.Vector3.Zero();
  22894. var max = BABYLON.Vector3.Zero();
  22895. var distance = Number.MAX_VALUE;
  22896. var currentSprite;
  22897. var cameraSpacePosition = BABYLON.Vector3.Zero();
  22898. var cameraView = camera.getViewMatrix();
  22899. for (var index = 0; index < count; index++) {
  22900. var sprite = this.sprites[index];
  22901. if (!sprite) {
  22902. continue;
  22903. }
  22904. if (predicate) {
  22905. if (!predicate(sprite)) {
  22906. continue;
  22907. }
  22908. }
  22909. else if (!sprite.isPickable) {
  22910. continue;
  22911. }
  22912. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  22913. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  22914. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  22915. if (ray.intersectsBoxMinMax(min, max)) {
  22916. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  22917. if (distance > currentDistance) {
  22918. distance = currentDistance;
  22919. currentSprite = sprite;
  22920. if (fastCheck) {
  22921. break;
  22922. }
  22923. }
  22924. }
  22925. }
  22926. if (currentSprite) {
  22927. var result = new BABYLON.PickingInfo();
  22928. result.hit = true;
  22929. result.pickedSprite = currentSprite;
  22930. result.distance = distance;
  22931. return result;
  22932. }
  22933. return null;
  22934. };
  22935. SpriteManager.prototype.render = function () {
  22936. // Check
  22937. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  22938. return;
  22939. var engine = this._scene.getEngine();
  22940. var baseSize = this._spriteTexture.getBaseSize();
  22941. // Sprites
  22942. var deltaTime = engine.getDeltaTime();
  22943. var max = Math.min(this._capacity, this.sprites.length);
  22944. var rowSize = baseSize.width / this.cellSize;
  22945. var offset = 0;
  22946. for (var index = 0; index < max; index++) {
  22947. var sprite = this.sprites[index];
  22948. if (!sprite) {
  22949. continue;
  22950. }
  22951. sprite._animate(deltaTime);
  22952. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  22953. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  22954. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  22955. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  22956. }
  22957. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22958. // Render
  22959. var effect = this._effectBase;
  22960. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22961. effect = this._effectFog;
  22962. }
  22963. engine.enableEffect(effect);
  22964. var viewMatrix = this._scene.getViewMatrix();
  22965. effect.setTexture("diffuseSampler", this._spriteTexture);
  22966. effect.setMatrix("view", viewMatrix);
  22967. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22968. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  22969. // Fog
  22970. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22971. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  22972. effect.setColor3("vFogColor", this._scene.fogColor);
  22973. }
  22974. // VBOs
  22975. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22976. // Draw order
  22977. engine.setDepthFunctionToLessOrEqual();
  22978. effect.setBool("alphaTest", true);
  22979. engine.setColorWrite(false);
  22980. engine.draw(true, 0, max * 6);
  22981. engine.setColorWrite(true);
  22982. effect.setBool("alphaTest", false);
  22983. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22984. engine.draw(true, 0, max * 6);
  22985. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22986. };
  22987. SpriteManager.prototype.dispose = function () {
  22988. if (this._vertexBuffer) {
  22989. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22990. this._vertexBuffer = null;
  22991. }
  22992. if (this._indexBuffer) {
  22993. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22994. this._indexBuffer = null;
  22995. }
  22996. if (this._spriteTexture) {
  22997. this._spriteTexture.dispose();
  22998. this._spriteTexture = null;
  22999. }
  23000. // Remove from scene
  23001. var index = this._scene.spriteManagers.indexOf(this);
  23002. this._scene.spriteManagers.splice(index, 1);
  23003. // Callback
  23004. if (this.onDispose) {
  23005. this.onDispose();
  23006. }
  23007. };
  23008. return SpriteManager;
  23009. })();
  23010. BABYLON.SpriteManager = SpriteManager;
  23011. })(BABYLON || (BABYLON = {}));
  23012. var BABYLON;
  23013. (function (BABYLON) {
  23014. var Sprite = (function () {
  23015. function Sprite(name, manager) {
  23016. this.name = name;
  23017. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23018. this.width = 1.0;
  23019. this.height = 1.0;
  23020. this.angle = 0;
  23021. this.cellIndex = 0;
  23022. this.invertU = 0;
  23023. this.invertV = 0;
  23024. this.animations = new Array();
  23025. this.isPickable = false;
  23026. this._animationStarted = false;
  23027. this._loopAnimation = false;
  23028. this._fromIndex = 0;
  23029. this._toIndex = 0;
  23030. this._delay = 0;
  23031. this._direction = 1;
  23032. this._frameCount = 0;
  23033. this._time = 0;
  23034. this._manager = manager;
  23035. this._manager.sprites.push(this);
  23036. this.position = BABYLON.Vector3.Zero();
  23037. }
  23038. Object.defineProperty(Sprite.prototype, "size", {
  23039. get: function () {
  23040. return this.width;
  23041. },
  23042. set: function (value) {
  23043. this.width = value;
  23044. this.height = value;
  23045. },
  23046. enumerable: true,
  23047. configurable: true
  23048. });
  23049. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  23050. this._fromIndex = from;
  23051. this._toIndex = to;
  23052. this._loopAnimation = loop;
  23053. this._delay = delay;
  23054. this._animationStarted = true;
  23055. this._direction = from < to ? 1 : -1;
  23056. this.cellIndex = from;
  23057. this._time = 0;
  23058. };
  23059. Sprite.prototype.stopAnimation = function () {
  23060. this._animationStarted = false;
  23061. };
  23062. Sprite.prototype._animate = function (deltaTime) {
  23063. if (!this._animationStarted)
  23064. return;
  23065. this._time += deltaTime;
  23066. if (this._time > this._delay) {
  23067. this._time = this._time % this._delay;
  23068. this.cellIndex += this._direction;
  23069. if (this.cellIndex == this._toIndex) {
  23070. if (this._loopAnimation) {
  23071. this.cellIndex = this._fromIndex;
  23072. }
  23073. else {
  23074. this._animationStarted = false;
  23075. if (this.disposeWhenFinishedAnimating) {
  23076. this.dispose();
  23077. }
  23078. }
  23079. }
  23080. }
  23081. };
  23082. Sprite.prototype.dispose = function () {
  23083. for (var i = 0; i < this._manager.sprites.length; i++) {
  23084. if (this._manager.sprites[i] == this) {
  23085. this._manager.sprites.splice(i, 1);
  23086. }
  23087. }
  23088. };
  23089. return Sprite;
  23090. })();
  23091. BABYLON.Sprite = Sprite;
  23092. })(BABYLON || (BABYLON = {}));
  23093. var BABYLON;
  23094. (function (BABYLON) {
  23095. var Layer = (function () {
  23096. function Layer(name, imgUrl, scene, isBackground, color) {
  23097. this.name = name;
  23098. this.scale = new BABYLON.Vector2(1, 1);
  23099. this.offset = new BABYLON.Vector2(0, 0);
  23100. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  23101. this._vertexDeclaration = [2];
  23102. this._vertexStrideSize = 2 * 4;
  23103. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  23104. this.isBackground = isBackground === undefined ? true : isBackground;
  23105. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  23106. this._scene = scene;
  23107. this._scene.layers.push(this);
  23108. // VBO
  23109. var vertices = [];
  23110. vertices.push(1, 1);
  23111. vertices.push(-1, 1);
  23112. vertices.push(-1, -1);
  23113. vertices.push(1, -1);
  23114. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23115. // Indices
  23116. var indices = [];
  23117. indices.push(0);
  23118. indices.push(1);
  23119. indices.push(2);
  23120. indices.push(0);
  23121. indices.push(2);
  23122. indices.push(3);
  23123. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23124. // Effects
  23125. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  23126. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  23127. }
  23128. Layer.prototype.render = function () {
  23129. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  23130. // Check
  23131. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  23132. return;
  23133. var engine = this._scene.getEngine();
  23134. if (this.onBeforeRender) {
  23135. this.onBeforeRender();
  23136. }
  23137. // Render
  23138. engine.enableEffect(currentEffect);
  23139. engine.setState(false);
  23140. // Texture
  23141. currentEffect.setTexture("textureSampler", this.texture);
  23142. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  23143. // Color
  23144. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  23145. // Scale / offset
  23146. currentEffect.setVector2("offset", this.offset);
  23147. currentEffect.setVector2("scale", this.scale);
  23148. // VBOs
  23149. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  23150. // Draw order
  23151. if (!this._alphaTestEffect) {
  23152. engine.setAlphaMode(this.alphaBlendingMode);
  23153. engine.draw(true, 0, 6);
  23154. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23155. }
  23156. else {
  23157. engine.draw(true, 0, 6);
  23158. }
  23159. if (this.onAfterRender) {
  23160. this.onAfterRender();
  23161. }
  23162. };
  23163. Layer.prototype.dispose = function () {
  23164. if (this._vertexBuffer) {
  23165. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23166. this._vertexBuffer = null;
  23167. }
  23168. if (this._indexBuffer) {
  23169. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23170. this._indexBuffer = null;
  23171. }
  23172. if (this.texture) {
  23173. this.texture.dispose();
  23174. this.texture = null;
  23175. }
  23176. // Remove from scene
  23177. var index = this._scene.layers.indexOf(this);
  23178. this._scene.layers.splice(index, 1);
  23179. // Callback
  23180. if (this.onDispose) {
  23181. this.onDispose();
  23182. }
  23183. };
  23184. return Layer;
  23185. })();
  23186. BABYLON.Layer = Layer;
  23187. })(BABYLON || (BABYLON = {}));
  23188. var BABYLON;
  23189. (function (BABYLON) {
  23190. var Particle = (function () {
  23191. function Particle() {
  23192. this.position = BABYLON.Vector3.Zero();
  23193. this.direction = BABYLON.Vector3.Zero();
  23194. this.color = new BABYLON.Color4(0, 0, 0, 0);
  23195. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  23196. this.lifeTime = 1.0;
  23197. this.age = 0;
  23198. this.size = 0;
  23199. this.angle = 0;
  23200. this.angularSpeed = 0;
  23201. }
  23202. Particle.prototype.copyTo = function (other) {
  23203. other.position.copyFrom(this.position);
  23204. other.direction.copyFrom(this.direction);
  23205. other.color.copyFrom(this.color);
  23206. other.colorStep.copyFrom(this.colorStep);
  23207. other.lifeTime = this.lifeTime;
  23208. other.age = this.age;
  23209. other.size = this.size;
  23210. other.angle = this.angle;
  23211. other.angularSpeed = this.angularSpeed;
  23212. };
  23213. return Particle;
  23214. })();
  23215. BABYLON.Particle = Particle;
  23216. })(BABYLON || (BABYLON = {}));
  23217. var BABYLON;
  23218. (function (BABYLON) {
  23219. var randomNumber = function (min, max) {
  23220. if (min === max) {
  23221. return (min);
  23222. }
  23223. var random = Math.random();
  23224. return ((random * (max - min)) + min);
  23225. };
  23226. var ParticleSystem = (function () {
  23227. function ParticleSystem(name, capacity, scene, customEffect) {
  23228. var _this = this;
  23229. this.name = name;
  23230. // Members
  23231. this.animations = [];
  23232. this.renderingGroupId = 0;
  23233. this.emitter = null;
  23234. this.emitRate = 10;
  23235. this.manualEmitCount = -1;
  23236. this.updateSpeed = 0.01;
  23237. this.targetStopDuration = 0;
  23238. this.disposeOnStop = false;
  23239. this.minEmitPower = 1;
  23240. this.maxEmitPower = 1;
  23241. this.minLifeTime = 1;
  23242. this.maxLifeTime = 1;
  23243. this.minSize = 1;
  23244. this.maxSize = 1;
  23245. this.minAngularSpeed = 0;
  23246. this.maxAngularSpeed = 0;
  23247. this.layerMask = 0x0FFFFFFF;
  23248. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  23249. this.forceDepthWrite = false;
  23250. this.gravity = BABYLON.Vector3.Zero();
  23251. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  23252. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  23253. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  23254. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  23255. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23256. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23257. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  23258. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23259. this.particles = new Array();
  23260. this._vertexDeclaration = [3, 4, 4];
  23261. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  23262. this._stockParticles = new Array();
  23263. this._newPartsExcess = 0;
  23264. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  23265. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  23266. this._scaledDirection = BABYLON.Vector3.Zero();
  23267. this._scaledGravity = BABYLON.Vector3.Zero();
  23268. this._currentRenderId = -1;
  23269. this._started = false;
  23270. this._stopped = false;
  23271. this._actualFrame = 0;
  23272. this.id = name;
  23273. this._capacity = capacity;
  23274. this._scene = scene;
  23275. this._customEffect = customEffect;
  23276. scene.particleSystems.push(this);
  23277. // VBO
  23278. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  23279. var indices = [];
  23280. var index = 0;
  23281. for (var count = 0; count < capacity; count++) {
  23282. indices.push(index);
  23283. indices.push(index + 1);
  23284. indices.push(index + 2);
  23285. indices.push(index);
  23286. indices.push(index + 2);
  23287. indices.push(index + 3);
  23288. index += 4;
  23289. }
  23290. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23291. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  23292. // Default behaviors
  23293. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  23294. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  23295. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  23296. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  23297. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  23298. };
  23299. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  23300. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  23301. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  23302. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  23303. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  23304. };
  23305. this.updateFunction = function (particles) {
  23306. for (var index = 0; index < particles.length; index++) {
  23307. var particle = particles[index];
  23308. particle.age += _this._scaledUpdateSpeed;
  23309. if (particle.age >= particle.lifeTime) {
  23310. _this.recycleParticle(particle);
  23311. index--;
  23312. continue;
  23313. }
  23314. else {
  23315. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  23316. particle.color.addInPlace(_this._scaledColorStep);
  23317. if (particle.color.a < 0)
  23318. particle.color.a = 0;
  23319. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  23320. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  23321. particle.position.addInPlace(_this._scaledDirection);
  23322. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  23323. particle.direction.addInPlace(_this._scaledGravity);
  23324. }
  23325. }
  23326. };
  23327. }
  23328. ParticleSystem.prototype.recycleParticle = function (particle) {
  23329. var lastParticle = this.particles.pop();
  23330. if (lastParticle !== particle) {
  23331. lastParticle.copyTo(particle);
  23332. this._stockParticles.push(lastParticle);
  23333. }
  23334. };
  23335. ParticleSystem.prototype.getCapacity = function () {
  23336. return this._capacity;
  23337. };
  23338. ParticleSystem.prototype.isAlive = function () {
  23339. return this._alive;
  23340. };
  23341. ParticleSystem.prototype.isStarted = function () {
  23342. return this._started;
  23343. };
  23344. ParticleSystem.prototype.start = function () {
  23345. this._started = true;
  23346. this._stopped = false;
  23347. this._actualFrame = 0;
  23348. };
  23349. ParticleSystem.prototype.stop = function () {
  23350. this._stopped = true;
  23351. };
  23352. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  23353. var offset = index * 11;
  23354. this._vertices[offset] = particle.position.x;
  23355. this._vertices[offset + 1] = particle.position.y;
  23356. this._vertices[offset + 2] = particle.position.z;
  23357. this._vertices[offset + 3] = particle.color.r;
  23358. this._vertices[offset + 4] = particle.color.g;
  23359. this._vertices[offset + 5] = particle.color.b;
  23360. this._vertices[offset + 6] = particle.color.a;
  23361. this._vertices[offset + 7] = particle.angle;
  23362. this._vertices[offset + 8] = particle.size;
  23363. this._vertices[offset + 9] = offsetX;
  23364. this._vertices[offset + 10] = offsetY;
  23365. };
  23366. ParticleSystem.prototype._update = function (newParticles) {
  23367. // Update current
  23368. this._alive = this.particles.length > 0;
  23369. this.updateFunction(this.particles);
  23370. // Add new ones
  23371. var worldMatrix;
  23372. if (this.emitter.position) {
  23373. worldMatrix = this.emitter.getWorldMatrix();
  23374. }
  23375. else {
  23376. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  23377. }
  23378. var particle;
  23379. for (var index = 0; index < newParticles; index++) {
  23380. if (this.particles.length === this._capacity) {
  23381. break;
  23382. }
  23383. if (this._stockParticles.length !== 0) {
  23384. particle = this._stockParticles.pop();
  23385. particle.age = 0;
  23386. }
  23387. else {
  23388. particle = new BABYLON.Particle();
  23389. }
  23390. this.particles.push(particle);
  23391. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  23392. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  23393. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  23394. particle.size = randomNumber(this.minSize, this.maxSize);
  23395. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  23396. this.startPositionFunction(worldMatrix, particle.position, particle);
  23397. var step = randomNumber(0, 1.0);
  23398. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  23399. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  23400. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  23401. }
  23402. };
  23403. ParticleSystem.prototype._getEffect = function () {
  23404. if (this._customEffect) {
  23405. return this._customEffect;
  23406. }
  23407. ;
  23408. var defines = [];
  23409. if (this._scene.clipPlane) {
  23410. defines.push("#define CLIPPLANE");
  23411. }
  23412. // Effect
  23413. var join = defines.join("\n");
  23414. if (this._cachedDefines !== join) {
  23415. this._cachedDefines = join;
  23416. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  23417. }
  23418. return this._effect;
  23419. };
  23420. ParticleSystem.prototype.animate = function () {
  23421. if (!this._started)
  23422. return;
  23423. var effect = this._getEffect();
  23424. // Check
  23425. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  23426. return;
  23427. if (this._currentRenderId === this._scene.getRenderId()) {
  23428. return;
  23429. }
  23430. this._currentRenderId = this._scene.getRenderId();
  23431. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  23432. // determine the number of particles we need to create
  23433. var newParticles;
  23434. if (this.manualEmitCount > -1) {
  23435. newParticles = this.manualEmitCount;
  23436. this._newPartsExcess = 0;
  23437. this.manualEmitCount = 0;
  23438. }
  23439. else {
  23440. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  23441. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  23442. }
  23443. if (this._newPartsExcess > 1.0) {
  23444. newParticles += this._newPartsExcess >> 0;
  23445. this._newPartsExcess -= this._newPartsExcess >> 0;
  23446. }
  23447. this._alive = false;
  23448. if (!this._stopped) {
  23449. this._actualFrame += this._scaledUpdateSpeed;
  23450. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  23451. this.stop();
  23452. }
  23453. else {
  23454. newParticles = 0;
  23455. }
  23456. this._update(newParticles);
  23457. // Stopped?
  23458. if (this._stopped) {
  23459. if (!this._alive) {
  23460. this._started = false;
  23461. if (this.disposeOnStop) {
  23462. this._scene._toBeDisposed.push(this);
  23463. }
  23464. }
  23465. }
  23466. // Update VBO
  23467. var offset = 0;
  23468. for (var index = 0; index < this.particles.length; index++) {
  23469. var particle = this.particles[index];
  23470. this._appendParticleVertex(offset++, particle, 0, 0);
  23471. this._appendParticleVertex(offset++, particle, 1, 0);
  23472. this._appendParticleVertex(offset++, particle, 1, 1);
  23473. this._appendParticleVertex(offset++, particle, 0, 1);
  23474. }
  23475. var engine = this._scene.getEngine();
  23476. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  23477. };
  23478. ParticleSystem.prototype.render = function () {
  23479. var effect = this._getEffect();
  23480. // Check
  23481. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  23482. return 0;
  23483. var engine = this._scene.getEngine();
  23484. // Render
  23485. engine.enableEffect(effect);
  23486. engine.setState(false);
  23487. var viewMatrix = this._scene.getViewMatrix();
  23488. effect.setTexture("diffuseSampler", this.particleTexture);
  23489. effect.setMatrix("view", viewMatrix);
  23490. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  23491. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  23492. if (this._scene.clipPlane) {
  23493. var clipPlane = this._scene.clipPlane;
  23494. var invView = viewMatrix.clone();
  23495. invView.invert();
  23496. effect.setMatrix("invView", invView);
  23497. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23498. }
  23499. // VBOs
  23500. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23501. // Draw order
  23502. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  23503. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23504. }
  23505. else {
  23506. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23507. }
  23508. if (this.forceDepthWrite) {
  23509. engine.setDepthWrite(true);
  23510. }
  23511. engine.draw(true, 0, this.particles.length * 6);
  23512. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23513. return this.particles.length;
  23514. };
  23515. ParticleSystem.prototype.dispose = function () {
  23516. if (this._vertexBuffer) {
  23517. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23518. this._vertexBuffer = null;
  23519. }
  23520. if (this._indexBuffer) {
  23521. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23522. this._indexBuffer = null;
  23523. }
  23524. if (this.particleTexture) {
  23525. this.particleTexture.dispose();
  23526. this.particleTexture = null;
  23527. }
  23528. // Remove from scene
  23529. var index = this._scene.particleSystems.indexOf(this);
  23530. this._scene.particleSystems.splice(index, 1);
  23531. // Callback
  23532. if (this.onDispose) {
  23533. this.onDispose();
  23534. }
  23535. };
  23536. // Clone
  23537. ParticleSystem.prototype.clone = function (name, newEmitter) {
  23538. var result = new ParticleSystem(name, this._capacity, this._scene);
  23539. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  23540. if (newEmitter === undefined) {
  23541. newEmitter = this.emitter;
  23542. }
  23543. result.emitter = newEmitter;
  23544. if (this.particleTexture) {
  23545. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  23546. }
  23547. result.start();
  23548. return result;
  23549. };
  23550. ParticleSystem.prototype.serialize = function () {
  23551. var serializationObject = {};
  23552. serializationObject.name = this.name;
  23553. serializationObject.id = this.id;
  23554. // Emitter
  23555. if (this.emitter.position) {
  23556. serializationObject.emitterId = this.emitter.id;
  23557. }
  23558. else {
  23559. serializationObject.emitter = this.emitter.asArray();
  23560. }
  23561. serializationObject.capacity = this.getCapacity();
  23562. if (this.particleTexture) {
  23563. serializationObject.textureName = this.particleTexture.name;
  23564. }
  23565. // Animations
  23566. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23567. // Particle system
  23568. serializationObject.minAngularSpeed = this.minAngularSpeed;
  23569. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  23570. serializationObject.minSize = this.minSize;
  23571. serializationObject.maxSize = this.maxSize;
  23572. serializationObject.minEmitPower = this.minEmitPower;
  23573. serializationObject.maxEmitPower = this.maxEmitPower;
  23574. serializationObject.minLifeTime = this.minLifeTime;
  23575. serializationObject.maxLifeTime = this.maxLifeTime;
  23576. serializationObject.emitRate = this.emitRate;
  23577. serializationObject.minEmitBox = this.minEmitBox.asArray();
  23578. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  23579. serializationObject.gravity = this.gravity.asArray();
  23580. serializationObject.direction1 = this.direction1.asArray();
  23581. serializationObject.direction2 = this.direction2.asArray();
  23582. serializationObject.color1 = this.color1.asArray();
  23583. serializationObject.color2 = this.color2.asArray();
  23584. serializationObject.colorDead = this.colorDead.asArray();
  23585. serializationObject.updateSpeed = this.updateSpeed;
  23586. serializationObject.targetStopDuration = this.targetStopDuration;
  23587. serializationObject.textureMask = this.textureMask.asArray();
  23588. serializationObject.blendMode = this.blendMode;
  23589. return serializationObject;
  23590. };
  23591. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  23592. var name = parsedParticleSystem.name;
  23593. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  23594. if (parsedParticleSystem.id) {
  23595. particleSystem.id = parsedParticleSystem.id;
  23596. }
  23597. // Texture
  23598. if (parsedParticleSystem.textureName) {
  23599. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  23600. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  23601. }
  23602. // Emitter
  23603. if (parsedParticleSystem.emitterId) {
  23604. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  23605. }
  23606. else {
  23607. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  23608. }
  23609. // Animations
  23610. if (parsedParticleSystem.animations) {
  23611. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  23612. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  23613. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23614. }
  23615. }
  23616. if (parsedParticleSystem.autoAnimate) {
  23617. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  23618. }
  23619. // Particle system
  23620. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  23621. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  23622. particleSystem.minSize = parsedParticleSystem.minSize;
  23623. particleSystem.maxSize = parsedParticleSystem.maxSize;
  23624. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  23625. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  23626. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  23627. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  23628. particleSystem.emitRate = parsedParticleSystem.emitRate;
  23629. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  23630. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  23631. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  23632. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  23633. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  23634. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  23635. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  23636. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  23637. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  23638. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  23639. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  23640. particleSystem.blendMode = parsedParticleSystem.blendMode;
  23641. particleSystem.start();
  23642. return particleSystem;
  23643. };
  23644. // Statics
  23645. ParticleSystem.BLENDMODE_ONEONE = 0;
  23646. ParticleSystem.BLENDMODE_STANDARD = 1;
  23647. return ParticleSystem;
  23648. })();
  23649. BABYLON.ParticleSystem = ParticleSystem;
  23650. })(BABYLON || (BABYLON = {}));
  23651. var BABYLON;
  23652. (function (BABYLON) {
  23653. var AnimationRange = (function () {
  23654. function AnimationRange(name, from, to) {
  23655. this.name = name;
  23656. this.from = from;
  23657. this.to = to;
  23658. }
  23659. AnimationRange.prototype.clone = function () {
  23660. return new AnimationRange(this.name, this.from, this.to);
  23661. };
  23662. return AnimationRange;
  23663. })();
  23664. BABYLON.AnimationRange = AnimationRange;
  23665. /**
  23666. * Composed of a frame, and an action function
  23667. */
  23668. var AnimationEvent = (function () {
  23669. function AnimationEvent(frame, action, onlyOnce) {
  23670. this.frame = frame;
  23671. this.action = action;
  23672. this.onlyOnce = onlyOnce;
  23673. this.isDone = false;
  23674. }
  23675. return AnimationEvent;
  23676. })();
  23677. BABYLON.AnimationEvent = AnimationEvent;
  23678. var PathCursor = (function () {
  23679. function PathCursor(path) {
  23680. this.path = path;
  23681. this._onchange = new Array();
  23682. this.value = 0;
  23683. this.animations = new Array();
  23684. }
  23685. PathCursor.prototype.getPoint = function () {
  23686. var point = this.path.getPointAtLengthPosition(this.value);
  23687. return new BABYLON.Vector3(point.x, 0, point.y);
  23688. };
  23689. PathCursor.prototype.moveAhead = function (step) {
  23690. if (step === void 0) { step = 0.002; }
  23691. this.move(step);
  23692. return this;
  23693. };
  23694. PathCursor.prototype.moveBack = function (step) {
  23695. if (step === void 0) { step = 0.002; }
  23696. this.move(-step);
  23697. return this;
  23698. };
  23699. PathCursor.prototype.move = function (step) {
  23700. if (Math.abs(step) > 1) {
  23701. throw "step size should be less than 1.";
  23702. }
  23703. this.value += step;
  23704. this.ensureLimits();
  23705. this.raiseOnChange();
  23706. return this;
  23707. };
  23708. PathCursor.prototype.ensureLimits = function () {
  23709. while (this.value > 1) {
  23710. this.value -= 1;
  23711. }
  23712. while (this.value < 0) {
  23713. this.value += 1;
  23714. }
  23715. return this;
  23716. };
  23717. // used by animation engine
  23718. PathCursor.prototype.markAsDirty = function (propertyName) {
  23719. this.ensureLimits();
  23720. this.raiseOnChange();
  23721. return this;
  23722. };
  23723. PathCursor.prototype.raiseOnChange = function () {
  23724. var _this = this;
  23725. this._onchange.forEach(function (f) { return f(_this); });
  23726. return this;
  23727. };
  23728. PathCursor.prototype.onchange = function (f) {
  23729. this._onchange.push(f);
  23730. return this;
  23731. };
  23732. return PathCursor;
  23733. })();
  23734. BABYLON.PathCursor = PathCursor;
  23735. var Animation = (function () {
  23736. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  23737. this.name = name;
  23738. this.targetProperty = targetProperty;
  23739. this.framePerSecond = framePerSecond;
  23740. this.dataType = dataType;
  23741. this.loopMode = loopMode;
  23742. this.enableBlending = enableBlending;
  23743. this._offsetsCache = {};
  23744. this._highLimitsCache = {};
  23745. this._stopped = false;
  23746. this._blendingFactor = 0;
  23747. // The set of event that will be linked to this animation
  23748. this._events = new Array();
  23749. this.allowMatricesInterpolation = false;
  23750. this.blendingSpeed = 0.01;
  23751. this._ranges = {};
  23752. this.targetPropertyPath = targetProperty.split(".");
  23753. this.dataType = dataType;
  23754. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  23755. }
  23756. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  23757. var dataType = undefined;
  23758. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  23759. dataType = Animation.ANIMATIONTYPE_FLOAT;
  23760. }
  23761. else if (from instanceof BABYLON.Quaternion) {
  23762. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  23763. }
  23764. else if (from instanceof BABYLON.Vector3) {
  23765. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  23766. }
  23767. else if (from instanceof BABYLON.Vector2) {
  23768. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  23769. }
  23770. else if (from instanceof BABYLON.Color3) {
  23771. dataType = Animation.ANIMATIONTYPE_COLOR3;
  23772. }
  23773. if (dataType == undefined) {
  23774. return null;
  23775. }
  23776. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  23777. var keys = [];
  23778. keys.push({ frame: 0, value: from });
  23779. keys.push({ frame: totalFrame, value: to });
  23780. animation.setKeys(keys);
  23781. if (easingFunction !== undefined) {
  23782. animation.setEasingFunction(easingFunction);
  23783. }
  23784. return animation;
  23785. };
  23786. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  23787. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  23788. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  23789. };
  23790. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  23791. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  23792. node.animations.push(animation);
  23793. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  23794. };
  23795. // Methods
  23796. /**
  23797. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23798. */
  23799. Animation.prototype.toString = function (fullDetails) {
  23800. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  23801. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  23802. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  23803. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  23804. if (fullDetails) {
  23805. ret += ", Ranges: {";
  23806. var first = true;
  23807. for (var name in this._ranges) {
  23808. if (!first) {
  23809. ret + ", ";
  23810. first = false;
  23811. }
  23812. ret += name;
  23813. }
  23814. ret += "}";
  23815. }
  23816. return ret;
  23817. };
  23818. /**
  23819. * Add an event to this animation.
  23820. */
  23821. Animation.prototype.addEvent = function (event) {
  23822. this._events.push(event);
  23823. };
  23824. /**
  23825. * Remove all events found at the given frame
  23826. * @param frame
  23827. */
  23828. Animation.prototype.removeEvents = function (frame) {
  23829. for (var index = 0; index < this._events.length; index++) {
  23830. if (this._events[index].frame === frame) {
  23831. this._events.splice(index, 1);
  23832. index--;
  23833. }
  23834. }
  23835. };
  23836. Animation.prototype.createRange = function (name, from, to) {
  23837. // check name not already in use; could happen for bones after serialized
  23838. if (!this._ranges[name]) {
  23839. this._ranges[name] = new AnimationRange(name, from, to);
  23840. }
  23841. };
  23842. Animation.prototype.deleteRange = function (name, deleteFrames) {
  23843. if (deleteFrames === void 0) { deleteFrames = true; }
  23844. if (this._ranges[name]) {
  23845. if (deleteFrames) {
  23846. var from = this._ranges[name].from;
  23847. var to = this._ranges[name].to;
  23848. // this loop MUST go high to low for multiple splices to work
  23849. for (var key = this._keys.length - 1; key >= 0; key--) {
  23850. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  23851. this._keys.splice(key, 1);
  23852. }
  23853. }
  23854. }
  23855. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23856. }
  23857. };
  23858. Animation.prototype.getRange = function (name) {
  23859. return this._ranges[name];
  23860. };
  23861. Animation.prototype.reset = function () {
  23862. this._offsetsCache = {};
  23863. this._highLimitsCache = {};
  23864. this.currentFrame = 0;
  23865. this._blendingFactor = 0;
  23866. this._originalBlendValue = null;
  23867. };
  23868. Animation.prototype.isStopped = function () {
  23869. return this._stopped;
  23870. };
  23871. Animation.prototype.getKeys = function () {
  23872. return this._keys;
  23873. };
  23874. Animation.prototype.getHighestFrame = function () {
  23875. var ret = 0;
  23876. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  23877. if (ret < this._keys[key].frame) {
  23878. ret = this._keys[key].frame;
  23879. }
  23880. }
  23881. return ret;
  23882. };
  23883. Animation.prototype.getEasingFunction = function () {
  23884. return this._easingFunction;
  23885. };
  23886. Animation.prototype.setEasingFunction = function (easingFunction) {
  23887. this._easingFunction = easingFunction;
  23888. };
  23889. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  23890. return startValue + (endValue - startValue) * gradient;
  23891. };
  23892. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  23893. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  23894. };
  23895. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  23896. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  23897. };
  23898. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  23899. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  23900. };
  23901. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  23902. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  23903. };
  23904. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  23905. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  23906. };
  23907. Animation.prototype.clone = function () {
  23908. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  23909. if (this._keys) {
  23910. clone.setKeys(this._keys);
  23911. }
  23912. if (this._ranges) {
  23913. clone._ranges = {};
  23914. for (var name in this._ranges) {
  23915. clone._ranges[name] = this._ranges[name].clone();
  23916. }
  23917. }
  23918. return clone;
  23919. };
  23920. Animation.prototype.setKeys = function (values) {
  23921. this._keys = values.slice(0);
  23922. this._offsetsCache = {};
  23923. this._highLimitsCache = {};
  23924. };
  23925. Animation.prototype._getKeyValue = function (value) {
  23926. if (typeof value === "function") {
  23927. return value();
  23928. }
  23929. return value;
  23930. };
  23931. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  23932. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  23933. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  23934. }
  23935. this.currentFrame = currentFrame;
  23936. // Try to get a hash to find the right key
  23937. 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));
  23938. if (this._keys[startKey].frame >= currentFrame) {
  23939. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  23940. startKey--;
  23941. }
  23942. }
  23943. for (var key = startKey; key < this._keys.length; key++) {
  23944. if (this._keys[key + 1].frame >= currentFrame) {
  23945. var startValue = this._getKeyValue(this._keys[key].value);
  23946. var endValue = this._getKeyValue(this._keys[key + 1].value);
  23947. // gradient : percent of currentFrame between the frame inf and the frame sup
  23948. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  23949. // check for easingFunction and correction of gradient
  23950. if (this._easingFunction != null) {
  23951. gradient = this._easingFunction.ease(gradient);
  23952. }
  23953. switch (this.dataType) {
  23954. // Float
  23955. case Animation.ANIMATIONTYPE_FLOAT:
  23956. switch (loopMode) {
  23957. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23958. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23959. return this.floatInterpolateFunction(startValue, endValue, gradient);
  23960. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23961. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  23962. }
  23963. break;
  23964. // Quaternion
  23965. case Animation.ANIMATIONTYPE_QUATERNION:
  23966. var quaternion = null;
  23967. switch (loopMode) {
  23968. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23969. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23970. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  23971. break;
  23972. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23973. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  23974. break;
  23975. }
  23976. return quaternion;
  23977. // Vector3
  23978. case Animation.ANIMATIONTYPE_VECTOR3:
  23979. switch (loopMode) {
  23980. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23981. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23982. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  23983. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23984. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  23985. }
  23986. // Vector2
  23987. case Animation.ANIMATIONTYPE_VECTOR2:
  23988. switch (loopMode) {
  23989. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23990. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  23991. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  23992. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  23993. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  23994. }
  23995. // Color3
  23996. case Animation.ANIMATIONTYPE_COLOR3:
  23997. switch (loopMode) {
  23998. case Animation.ANIMATIONLOOPMODE_CYCLE:
  23999. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24000. return this.color3InterpolateFunction(startValue, endValue, gradient);
  24001. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24002. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  24003. }
  24004. // Matrix
  24005. case Animation.ANIMATIONTYPE_MATRIX:
  24006. switch (loopMode) {
  24007. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24008. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24009. if (this.allowMatricesInterpolation) {
  24010. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  24011. }
  24012. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24013. return startValue;
  24014. }
  24015. default:
  24016. break;
  24017. }
  24018. break;
  24019. }
  24020. }
  24021. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  24022. };
  24023. Animation.prototype.setValue = function (currentValue, blend) {
  24024. if (blend === void 0) { blend = false; }
  24025. // Set value
  24026. var path;
  24027. var destination;
  24028. if (this.targetPropertyPath.length > 1) {
  24029. var property = this._target[this.targetPropertyPath[0]];
  24030. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  24031. property = property[this.targetPropertyPath[index]];
  24032. }
  24033. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  24034. destination = property;
  24035. }
  24036. else {
  24037. path = this.targetPropertyPath[0];
  24038. destination = this._target;
  24039. }
  24040. // Blending
  24041. if (this.enableBlending && this._blendingFactor <= 1.0) {
  24042. if (!this._originalBlendValue) {
  24043. this._originalBlendValue = destination[path];
  24044. }
  24045. if (this._originalBlendValue.prototype) {
  24046. if (this._originalBlendValue.prototype.Lerp) {
  24047. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  24048. }
  24049. else {
  24050. destination[path] = currentValue;
  24051. }
  24052. }
  24053. else {
  24054. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  24055. }
  24056. this._blendingFactor += this.blendingSpeed;
  24057. }
  24058. else {
  24059. destination[path] = currentValue;
  24060. }
  24061. if (this._target.markAsDirty) {
  24062. this._target.markAsDirty(this.targetProperty);
  24063. }
  24064. };
  24065. Animation.prototype.goToFrame = function (frame) {
  24066. if (frame < this._keys[0].frame) {
  24067. frame = this._keys[0].frame;
  24068. }
  24069. else if (frame > this._keys[this._keys.length - 1].frame) {
  24070. frame = this._keys[this._keys.length - 1].frame;
  24071. }
  24072. var currentValue = this._interpolate(frame, 0, this.loopMode);
  24073. this.setValue(currentValue);
  24074. };
  24075. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  24076. if (blend === void 0) { blend = false; }
  24077. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  24078. this._stopped = true;
  24079. return false;
  24080. }
  24081. var returnValue = true;
  24082. // Adding a start key at frame 0 if missing
  24083. if (this._keys[0].frame !== 0) {
  24084. var newKey = { frame: 0, value: this._keys[0].value };
  24085. this._keys.splice(0, 0, newKey);
  24086. }
  24087. // Check limits
  24088. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  24089. from = this._keys[0].frame;
  24090. }
  24091. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  24092. to = this._keys[this._keys.length - 1].frame;
  24093. }
  24094. // Compute ratio
  24095. var range = to - from;
  24096. var offsetValue;
  24097. // ratio represents the frame delta between from and to
  24098. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  24099. var highLimitValue = 0;
  24100. if (ratio > range && !loop) {
  24101. returnValue = false;
  24102. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  24103. }
  24104. else {
  24105. // Get max value if required
  24106. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  24107. var keyOffset = to.toString() + from.toString();
  24108. if (!this._offsetsCache[keyOffset]) {
  24109. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  24110. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  24111. switch (this.dataType) {
  24112. // Float
  24113. case Animation.ANIMATIONTYPE_FLOAT:
  24114. this._offsetsCache[keyOffset] = toValue - fromValue;
  24115. break;
  24116. // Quaternion
  24117. case Animation.ANIMATIONTYPE_QUATERNION:
  24118. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24119. break;
  24120. // Vector3
  24121. case Animation.ANIMATIONTYPE_VECTOR3:
  24122. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24123. // Vector2
  24124. case Animation.ANIMATIONTYPE_VECTOR2:
  24125. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24126. // Color3
  24127. case Animation.ANIMATIONTYPE_COLOR3:
  24128. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24129. default:
  24130. break;
  24131. }
  24132. this._highLimitsCache[keyOffset] = toValue;
  24133. }
  24134. highLimitValue = this._highLimitsCache[keyOffset];
  24135. offsetValue = this._offsetsCache[keyOffset];
  24136. }
  24137. }
  24138. if (offsetValue === undefined) {
  24139. switch (this.dataType) {
  24140. // Float
  24141. case Animation.ANIMATIONTYPE_FLOAT:
  24142. offsetValue = 0;
  24143. break;
  24144. // Quaternion
  24145. case Animation.ANIMATIONTYPE_QUATERNION:
  24146. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  24147. break;
  24148. // Vector3
  24149. case Animation.ANIMATIONTYPE_VECTOR3:
  24150. offsetValue = BABYLON.Vector3.Zero();
  24151. break;
  24152. // Vector2
  24153. case Animation.ANIMATIONTYPE_VECTOR2:
  24154. offsetValue = BABYLON.Vector2.Zero();
  24155. break;
  24156. // Color3
  24157. case Animation.ANIMATIONTYPE_COLOR3:
  24158. offsetValue = BABYLON.Color3.Black();
  24159. }
  24160. }
  24161. // Compute value
  24162. var repeatCount = (ratio / range) >> 0;
  24163. var currentFrame = returnValue ? from + ratio % range : to;
  24164. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  24165. // Set value
  24166. this.setValue(currentValue);
  24167. // Check events
  24168. for (var index = 0; index < this._events.length; index++) {
  24169. if (currentFrame >= this._events[index].frame) {
  24170. var event = this._events[index];
  24171. if (!event.isDone) {
  24172. // If event should be done only once, remove it.
  24173. if (event.onlyOnce) {
  24174. this._events.splice(index, 1);
  24175. index--;
  24176. }
  24177. event.isDone = true;
  24178. event.action();
  24179. } // Don't do anything if the event has already be done.
  24180. }
  24181. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  24182. // reset event, the animation is looping
  24183. this._events[index].isDone = false;
  24184. }
  24185. }
  24186. if (!returnValue) {
  24187. this._stopped = true;
  24188. }
  24189. return returnValue;
  24190. };
  24191. Animation.prototype.serialize = function () {
  24192. var serializationObject = {};
  24193. serializationObject.name = this.name;
  24194. serializationObject.property = this.targetProperty;
  24195. serializationObject.framePerSecond = this.framePerSecond;
  24196. serializationObject.dataType = this.dataType;
  24197. serializationObject.loopBehavior = this.loopMode;
  24198. var dataType = this.dataType;
  24199. serializationObject.keys = [];
  24200. var keys = this.getKeys();
  24201. for (var index = 0; index < keys.length; index++) {
  24202. var animationKey = keys[index];
  24203. var key = {};
  24204. key.frame = animationKey.frame;
  24205. switch (dataType) {
  24206. case Animation.ANIMATIONTYPE_FLOAT:
  24207. key.values = [animationKey.value];
  24208. break;
  24209. case Animation.ANIMATIONTYPE_QUATERNION:
  24210. case Animation.ANIMATIONTYPE_MATRIX:
  24211. case Animation.ANIMATIONTYPE_VECTOR3:
  24212. case Animation.ANIMATIONTYPE_COLOR3:
  24213. key.values = animationKey.value.asArray();
  24214. break;
  24215. }
  24216. serializationObject.keys.push(key);
  24217. }
  24218. serializationObject.ranges = [];
  24219. for (var name in this._ranges) {
  24220. var range = {};
  24221. range.name = name;
  24222. range.from = this._ranges[name].from;
  24223. range.to = this._ranges[name].to;
  24224. serializationObject.ranges.push(range);
  24225. }
  24226. return serializationObject;
  24227. };
  24228. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  24229. get: function () {
  24230. return Animation._ANIMATIONTYPE_FLOAT;
  24231. },
  24232. enumerable: true,
  24233. configurable: true
  24234. });
  24235. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  24236. get: function () {
  24237. return Animation._ANIMATIONTYPE_VECTOR3;
  24238. },
  24239. enumerable: true,
  24240. configurable: true
  24241. });
  24242. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  24243. get: function () {
  24244. return Animation._ANIMATIONTYPE_VECTOR2;
  24245. },
  24246. enumerable: true,
  24247. configurable: true
  24248. });
  24249. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  24250. get: function () {
  24251. return Animation._ANIMATIONTYPE_QUATERNION;
  24252. },
  24253. enumerable: true,
  24254. configurable: true
  24255. });
  24256. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  24257. get: function () {
  24258. return Animation._ANIMATIONTYPE_MATRIX;
  24259. },
  24260. enumerable: true,
  24261. configurable: true
  24262. });
  24263. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  24264. get: function () {
  24265. return Animation._ANIMATIONTYPE_COLOR3;
  24266. },
  24267. enumerable: true,
  24268. configurable: true
  24269. });
  24270. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  24271. get: function () {
  24272. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  24273. },
  24274. enumerable: true,
  24275. configurable: true
  24276. });
  24277. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  24278. get: function () {
  24279. return Animation._ANIMATIONLOOPMODE_CYCLE;
  24280. },
  24281. enumerable: true,
  24282. configurable: true
  24283. });
  24284. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  24285. get: function () {
  24286. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  24287. },
  24288. enumerable: true,
  24289. configurable: true
  24290. });
  24291. Animation.Parse = function (parsedAnimation) {
  24292. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  24293. var dataType = parsedAnimation.dataType;
  24294. var keys = [];
  24295. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  24296. var key = parsedAnimation.keys[index];
  24297. var data;
  24298. switch (dataType) {
  24299. case Animation.ANIMATIONTYPE_FLOAT:
  24300. data = key.values[0];
  24301. break;
  24302. case Animation.ANIMATIONTYPE_QUATERNION:
  24303. data = BABYLON.Quaternion.FromArray(key.values);
  24304. break;
  24305. case Animation.ANIMATIONTYPE_MATRIX:
  24306. data = BABYLON.Matrix.FromArray(key.values);
  24307. break;
  24308. case Animation.ANIMATIONTYPE_COLOR3:
  24309. data = BABYLON.Color3.FromArray(key.values);
  24310. break;
  24311. case Animation.ANIMATIONTYPE_VECTOR3:
  24312. default:
  24313. data = BABYLON.Vector3.FromArray(key.values);
  24314. break;
  24315. }
  24316. keys.push({
  24317. frame: key.frame,
  24318. value: data
  24319. });
  24320. }
  24321. animation.setKeys(keys);
  24322. if (parsedAnimation.ranges) {
  24323. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  24324. data = parsedAnimation.ranges[index];
  24325. animation.createRange(data.name, data.from, data.to);
  24326. }
  24327. }
  24328. return animation;
  24329. };
  24330. Animation.AppendSerializedAnimations = function (source, destination) {
  24331. if (source.animations) {
  24332. destination.animations = [];
  24333. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24334. var animation = source.animations[animationIndex];
  24335. destination.animations.push(animation.serialize());
  24336. }
  24337. }
  24338. };
  24339. // Statics
  24340. Animation._ANIMATIONTYPE_FLOAT = 0;
  24341. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  24342. Animation._ANIMATIONTYPE_QUATERNION = 2;
  24343. Animation._ANIMATIONTYPE_MATRIX = 3;
  24344. Animation._ANIMATIONTYPE_COLOR3 = 4;
  24345. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  24346. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  24347. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  24348. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  24349. return Animation;
  24350. })();
  24351. BABYLON.Animation = Animation;
  24352. })(BABYLON || (BABYLON = {}));
  24353. var BABYLON;
  24354. (function (BABYLON) {
  24355. var Animatable = (function () {
  24356. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  24357. if (fromFrame === void 0) { fromFrame = 0; }
  24358. if (toFrame === void 0) { toFrame = 100; }
  24359. if (loopAnimation === void 0) { loopAnimation = false; }
  24360. if (speedRatio === void 0) { speedRatio = 1.0; }
  24361. this.target = target;
  24362. this.fromFrame = fromFrame;
  24363. this.toFrame = toFrame;
  24364. this.loopAnimation = loopAnimation;
  24365. this.speedRatio = speedRatio;
  24366. this.onAnimationEnd = onAnimationEnd;
  24367. this._animations = new Array();
  24368. this._paused = false;
  24369. this.animationStarted = false;
  24370. if (animations) {
  24371. this.appendAnimations(target, animations);
  24372. }
  24373. this._scene = scene;
  24374. scene._activeAnimatables.push(this);
  24375. }
  24376. // Methods
  24377. Animatable.prototype.getAnimations = function () {
  24378. return this._animations;
  24379. };
  24380. Animatable.prototype.appendAnimations = function (target, animations) {
  24381. for (var index = 0; index < animations.length; index++) {
  24382. var animation = animations[index];
  24383. animation._target = target;
  24384. this._animations.push(animation);
  24385. }
  24386. };
  24387. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  24388. var animations = this._animations;
  24389. for (var index = 0; index < animations.length; index++) {
  24390. if (animations[index].targetProperty === property) {
  24391. return animations[index];
  24392. }
  24393. }
  24394. return null;
  24395. };
  24396. Animatable.prototype.reset = function () {
  24397. var animations = this._animations;
  24398. for (var index = 0; index < animations.length; index++) {
  24399. animations[index].reset();
  24400. }
  24401. this._localDelayOffset = null;
  24402. this._pausedDelay = null;
  24403. };
  24404. Animatable.prototype.enableBlending = function (blendingSpeed) {
  24405. var animations = this._animations;
  24406. for (var index = 0; index < animations.length; index++) {
  24407. animations[index].enableBlending = true;
  24408. animations[index].blendingSpeed = blendingSpeed;
  24409. }
  24410. };
  24411. Animatable.prototype.disableBlending = function () {
  24412. var animations = this._animations;
  24413. for (var index = 0; index < animations.length; index++) {
  24414. animations[index].enableBlending = false;
  24415. }
  24416. };
  24417. Animatable.prototype.goToFrame = function (frame) {
  24418. var animations = this._animations;
  24419. for (var index = 0; index < animations.length; index++) {
  24420. animations[index].goToFrame(frame);
  24421. }
  24422. };
  24423. Animatable.prototype.pause = function () {
  24424. if (this._paused) {
  24425. return;
  24426. }
  24427. this._paused = true;
  24428. };
  24429. Animatable.prototype.restart = function () {
  24430. this._paused = false;
  24431. };
  24432. Animatable.prototype.stop = function () {
  24433. var index = this._scene._activeAnimatables.indexOf(this);
  24434. if (index > -1) {
  24435. this._scene._activeAnimatables.splice(index, 1);
  24436. var animations = this._animations;
  24437. for (var index = 0; index < animations.length; index++) {
  24438. animations[index].reset();
  24439. }
  24440. if (this.onAnimationEnd) {
  24441. this.onAnimationEnd();
  24442. }
  24443. }
  24444. };
  24445. Animatable.prototype._animate = function (delay) {
  24446. if (this._paused) {
  24447. this.animationStarted = false;
  24448. if (!this._pausedDelay) {
  24449. this._pausedDelay = delay;
  24450. }
  24451. return true;
  24452. }
  24453. if (!this._localDelayOffset) {
  24454. this._localDelayOffset = delay;
  24455. }
  24456. else if (this._pausedDelay) {
  24457. this._localDelayOffset += delay - this._pausedDelay;
  24458. this._pausedDelay = null;
  24459. }
  24460. // Animating
  24461. var running = false;
  24462. var animations = this._animations;
  24463. var index;
  24464. for (index = 0; index < animations.length; index++) {
  24465. var animation = animations[index];
  24466. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  24467. running = running || isRunning;
  24468. }
  24469. this.animationStarted = running;
  24470. if (!running) {
  24471. // Remove from active animatables
  24472. index = this._scene._activeAnimatables.indexOf(this);
  24473. this._scene._activeAnimatables.splice(index, 1);
  24474. }
  24475. if (!running && this.onAnimationEnd) {
  24476. this.onAnimationEnd();
  24477. this.onAnimationEnd = null;
  24478. }
  24479. return running;
  24480. };
  24481. return Animatable;
  24482. })();
  24483. BABYLON.Animatable = Animatable;
  24484. })(BABYLON || (BABYLON = {}));
  24485. var BABYLON;
  24486. (function (BABYLON) {
  24487. var EasingFunction = (function () {
  24488. function EasingFunction() {
  24489. // Properties
  24490. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  24491. }
  24492. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  24493. get: function () {
  24494. return EasingFunction._EASINGMODE_EASEIN;
  24495. },
  24496. enumerable: true,
  24497. configurable: true
  24498. });
  24499. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  24500. get: function () {
  24501. return EasingFunction._EASINGMODE_EASEOUT;
  24502. },
  24503. enumerable: true,
  24504. configurable: true
  24505. });
  24506. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  24507. get: function () {
  24508. return EasingFunction._EASINGMODE_EASEINOUT;
  24509. },
  24510. enumerable: true,
  24511. configurable: true
  24512. });
  24513. EasingFunction.prototype.setEasingMode = function (easingMode) {
  24514. var n = Math.min(Math.max(easingMode, 0), 2);
  24515. this._easingMode = n;
  24516. };
  24517. EasingFunction.prototype.getEasingMode = function () {
  24518. return this._easingMode;
  24519. };
  24520. EasingFunction.prototype.easeInCore = function (gradient) {
  24521. throw new Error('You must implement this method');
  24522. };
  24523. EasingFunction.prototype.ease = function (gradient) {
  24524. switch (this._easingMode) {
  24525. case EasingFunction.EASINGMODE_EASEIN:
  24526. return this.easeInCore(gradient);
  24527. case EasingFunction.EASINGMODE_EASEOUT:
  24528. return (1 - this.easeInCore(1 - gradient));
  24529. }
  24530. if (gradient >= 0.5) {
  24531. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  24532. }
  24533. return (this.easeInCore(gradient * 2) * 0.5);
  24534. };
  24535. //Statics
  24536. EasingFunction._EASINGMODE_EASEIN = 0;
  24537. EasingFunction._EASINGMODE_EASEOUT = 1;
  24538. EasingFunction._EASINGMODE_EASEINOUT = 2;
  24539. return EasingFunction;
  24540. })();
  24541. BABYLON.EasingFunction = EasingFunction;
  24542. var CircleEase = (function (_super) {
  24543. __extends(CircleEase, _super);
  24544. function CircleEase() {
  24545. _super.apply(this, arguments);
  24546. }
  24547. CircleEase.prototype.easeInCore = function (gradient) {
  24548. gradient = Math.max(0, Math.min(1, gradient));
  24549. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  24550. };
  24551. return CircleEase;
  24552. })(EasingFunction);
  24553. BABYLON.CircleEase = CircleEase;
  24554. var BackEase = (function (_super) {
  24555. __extends(BackEase, _super);
  24556. function BackEase(amplitude) {
  24557. if (amplitude === void 0) { amplitude = 1; }
  24558. _super.call(this);
  24559. this.amplitude = amplitude;
  24560. }
  24561. BackEase.prototype.easeInCore = function (gradient) {
  24562. var num = Math.max(0, this.amplitude);
  24563. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  24564. };
  24565. return BackEase;
  24566. })(EasingFunction);
  24567. BABYLON.BackEase = BackEase;
  24568. var BounceEase = (function (_super) {
  24569. __extends(BounceEase, _super);
  24570. function BounceEase(bounces, bounciness) {
  24571. if (bounces === void 0) { bounces = 3; }
  24572. if (bounciness === void 0) { bounciness = 2; }
  24573. _super.call(this);
  24574. this.bounces = bounces;
  24575. this.bounciness = bounciness;
  24576. }
  24577. BounceEase.prototype.easeInCore = function (gradient) {
  24578. var y = Math.max(0.0, this.bounces);
  24579. var bounciness = this.bounciness;
  24580. if (bounciness <= 1.0) {
  24581. bounciness = 1.001;
  24582. }
  24583. var num9 = Math.pow(bounciness, y);
  24584. var num5 = 1.0 - bounciness;
  24585. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  24586. var num15 = gradient * num4;
  24587. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  24588. var num3 = Math.floor(num65);
  24589. var num13 = num3 + 1.0;
  24590. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  24591. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  24592. var num7 = (num8 + num12) * 0.5;
  24593. var num6 = gradient - num7;
  24594. var num2 = num7 - num8;
  24595. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  24596. };
  24597. return BounceEase;
  24598. })(EasingFunction);
  24599. BABYLON.BounceEase = BounceEase;
  24600. var CubicEase = (function (_super) {
  24601. __extends(CubicEase, _super);
  24602. function CubicEase() {
  24603. _super.apply(this, arguments);
  24604. }
  24605. CubicEase.prototype.easeInCore = function (gradient) {
  24606. return (gradient * gradient * gradient);
  24607. };
  24608. return CubicEase;
  24609. })(EasingFunction);
  24610. BABYLON.CubicEase = CubicEase;
  24611. var ElasticEase = (function (_super) {
  24612. __extends(ElasticEase, _super);
  24613. function ElasticEase(oscillations, springiness) {
  24614. if (oscillations === void 0) { oscillations = 3; }
  24615. if (springiness === void 0) { springiness = 3; }
  24616. _super.call(this);
  24617. this.oscillations = oscillations;
  24618. this.springiness = springiness;
  24619. }
  24620. ElasticEase.prototype.easeInCore = function (gradient) {
  24621. var num2;
  24622. var num3 = Math.max(0.0, this.oscillations);
  24623. var num = Math.max(0.0, this.springiness);
  24624. if (num == 0) {
  24625. num2 = gradient;
  24626. }
  24627. else {
  24628. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  24629. }
  24630. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  24631. };
  24632. return ElasticEase;
  24633. })(EasingFunction);
  24634. BABYLON.ElasticEase = ElasticEase;
  24635. var ExponentialEase = (function (_super) {
  24636. __extends(ExponentialEase, _super);
  24637. function ExponentialEase(exponent) {
  24638. if (exponent === void 0) { exponent = 2; }
  24639. _super.call(this);
  24640. this.exponent = exponent;
  24641. }
  24642. ExponentialEase.prototype.easeInCore = function (gradient) {
  24643. if (this.exponent <= 0) {
  24644. return gradient;
  24645. }
  24646. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  24647. };
  24648. return ExponentialEase;
  24649. })(EasingFunction);
  24650. BABYLON.ExponentialEase = ExponentialEase;
  24651. var PowerEase = (function (_super) {
  24652. __extends(PowerEase, _super);
  24653. function PowerEase(power) {
  24654. if (power === void 0) { power = 2; }
  24655. _super.call(this);
  24656. this.power = power;
  24657. }
  24658. PowerEase.prototype.easeInCore = function (gradient) {
  24659. var y = Math.max(0.0, this.power);
  24660. return Math.pow(gradient, y);
  24661. };
  24662. return PowerEase;
  24663. })(EasingFunction);
  24664. BABYLON.PowerEase = PowerEase;
  24665. var QuadraticEase = (function (_super) {
  24666. __extends(QuadraticEase, _super);
  24667. function QuadraticEase() {
  24668. _super.apply(this, arguments);
  24669. }
  24670. QuadraticEase.prototype.easeInCore = function (gradient) {
  24671. return (gradient * gradient);
  24672. };
  24673. return QuadraticEase;
  24674. })(EasingFunction);
  24675. BABYLON.QuadraticEase = QuadraticEase;
  24676. var QuarticEase = (function (_super) {
  24677. __extends(QuarticEase, _super);
  24678. function QuarticEase() {
  24679. _super.apply(this, arguments);
  24680. }
  24681. QuarticEase.prototype.easeInCore = function (gradient) {
  24682. return (gradient * gradient * gradient * gradient);
  24683. };
  24684. return QuarticEase;
  24685. })(EasingFunction);
  24686. BABYLON.QuarticEase = QuarticEase;
  24687. var QuinticEase = (function (_super) {
  24688. __extends(QuinticEase, _super);
  24689. function QuinticEase() {
  24690. _super.apply(this, arguments);
  24691. }
  24692. QuinticEase.prototype.easeInCore = function (gradient) {
  24693. return (gradient * gradient * gradient * gradient * gradient);
  24694. };
  24695. return QuinticEase;
  24696. })(EasingFunction);
  24697. BABYLON.QuinticEase = QuinticEase;
  24698. var SineEase = (function (_super) {
  24699. __extends(SineEase, _super);
  24700. function SineEase() {
  24701. _super.apply(this, arguments);
  24702. }
  24703. SineEase.prototype.easeInCore = function (gradient) {
  24704. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  24705. };
  24706. return SineEase;
  24707. })(EasingFunction);
  24708. BABYLON.SineEase = SineEase;
  24709. var BezierCurveEase = (function (_super) {
  24710. __extends(BezierCurveEase, _super);
  24711. function BezierCurveEase(x1, y1, x2, y2) {
  24712. if (x1 === void 0) { x1 = 0; }
  24713. if (y1 === void 0) { y1 = 0; }
  24714. if (x2 === void 0) { x2 = 1; }
  24715. if (y2 === void 0) { y2 = 1; }
  24716. _super.call(this);
  24717. this.x1 = x1;
  24718. this.y1 = y1;
  24719. this.x2 = x2;
  24720. this.y2 = y2;
  24721. }
  24722. BezierCurveEase.prototype.easeInCore = function (gradient) {
  24723. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  24724. };
  24725. return BezierCurveEase;
  24726. })(EasingFunction);
  24727. BABYLON.BezierCurveEase = BezierCurveEase;
  24728. })(BABYLON || (BABYLON = {}));
  24729. var BABYLON;
  24730. (function (BABYLON) {
  24731. var Bone = (function (_super) {
  24732. __extends(Bone, _super);
  24733. function Bone(name, skeleton, parentBone, matrix, restPose) {
  24734. _super.call(this, name, skeleton.getScene());
  24735. this.name = name;
  24736. this.children = new Array();
  24737. this.animations = new Array();
  24738. this._worldTransform = new BABYLON.Matrix();
  24739. this._absoluteTransform = new BABYLON.Matrix();
  24740. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  24741. this._skeleton = skeleton;
  24742. this._matrix = matrix;
  24743. this._baseMatrix = matrix;
  24744. this._restPose = restPose ? restPose : matrix.clone();
  24745. skeleton.bones.push(this);
  24746. if (parentBone) {
  24747. this._parent = parentBone;
  24748. parentBone.children.push(this);
  24749. }
  24750. else {
  24751. this._parent = null;
  24752. }
  24753. this._updateDifferenceMatrix();
  24754. }
  24755. // Members
  24756. Bone.prototype.getParent = function () {
  24757. return this._parent;
  24758. };
  24759. Bone.prototype.getLocalMatrix = function () {
  24760. return this._matrix;
  24761. };
  24762. Bone.prototype.getBaseMatrix = function () {
  24763. return this._baseMatrix;
  24764. };
  24765. Bone.prototype.getRestPose = function () {
  24766. return this._restPose;
  24767. };
  24768. Bone.prototype.returnToRest = function () {
  24769. this.updateMatrix(this._restPose.clone());
  24770. };
  24771. Bone.prototype.getWorldMatrix = function () {
  24772. return this._worldTransform;
  24773. };
  24774. Bone.prototype.getInvertedAbsoluteTransform = function () {
  24775. return this._invertedAbsoluteTransform;
  24776. };
  24777. Bone.prototype.getAbsoluteTransform = function () {
  24778. return this._absoluteTransform;
  24779. };
  24780. // Methods
  24781. Bone.prototype.updateMatrix = function (matrix) {
  24782. this._baseMatrix = matrix.clone();
  24783. this._matrix = matrix.clone();
  24784. this._skeleton._markAsDirty();
  24785. this._updateDifferenceMatrix();
  24786. };
  24787. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  24788. if (!rootMatrix) {
  24789. rootMatrix = this._baseMatrix;
  24790. }
  24791. if (this._parent) {
  24792. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  24793. }
  24794. else {
  24795. this._absoluteTransform.copyFrom(rootMatrix);
  24796. }
  24797. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  24798. for (var index = 0; index < this.children.length; index++) {
  24799. this.children[index]._updateDifferenceMatrix();
  24800. }
  24801. };
  24802. Bone.prototype.markAsDirty = function () {
  24803. this._currentRenderId++;
  24804. this._skeleton._markAsDirty();
  24805. };
  24806. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  24807. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  24808. // all animation may be coming from a library skeleton, so may need to create animation
  24809. if (this.animations.length === 0) {
  24810. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  24811. this.animations[0].setKeys([]);
  24812. }
  24813. // get animation info / verify there is such a range from the source bone
  24814. var sourceRange = source.animations[0].getRange(rangeName);
  24815. if (!sourceRange) {
  24816. return false;
  24817. }
  24818. var from = sourceRange.from;
  24819. var to = sourceRange.to;
  24820. var sourceKeys = source.animations[0].getKeys();
  24821. // rescaling prep
  24822. var sourceBoneLength = source.length;
  24823. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  24824. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  24825. var destKeys = this.animations[0].getKeys();
  24826. // loop vars declaration / initialization
  24827. var orig;
  24828. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  24829. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  24830. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  24831. var mat;
  24832. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  24833. orig = sourceKeys[key];
  24834. if (orig.frame >= from && orig.frame <= to) {
  24835. if (scalingReqd) {
  24836. orig.value.decompose(origScale, origRotation, origTranslation);
  24837. origTranslation.scaleInPlace(ratio);
  24838. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  24839. }
  24840. else {
  24841. mat = orig.value;
  24842. }
  24843. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  24844. }
  24845. }
  24846. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  24847. return true;
  24848. };
  24849. return Bone;
  24850. })(BABYLON.Node);
  24851. BABYLON.Bone = Bone;
  24852. })(BABYLON || (BABYLON = {}));
  24853. var BABYLON;
  24854. (function (BABYLON) {
  24855. var Skeleton = (function () {
  24856. function Skeleton(name, id, scene) {
  24857. this.name = name;
  24858. this.id = id;
  24859. this.bones = new Array();
  24860. this.needInitialSkinMatrix = false;
  24861. this._isDirty = true;
  24862. this._meshesWithPoseMatrix = new Array();
  24863. this._identity = BABYLON.Matrix.Identity();
  24864. this._ranges = {};
  24865. this.bones = [];
  24866. this._scene = scene;
  24867. scene.skeletons.push(this);
  24868. //make sure it will recalculate the matrix next time prepare is called.
  24869. this._isDirty = true;
  24870. }
  24871. // Members
  24872. Skeleton.prototype.getTransformMatrices = function (mesh) {
  24873. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  24874. return mesh._bonesTransformMatrices;
  24875. }
  24876. return this._transformMatrices;
  24877. };
  24878. Skeleton.prototype.getScene = function () {
  24879. return this._scene;
  24880. };
  24881. // Methods
  24882. /**
  24883. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24884. */
  24885. Skeleton.prototype.toString = function (fullDetails) {
  24886. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  24887. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  24888. if (fullDetails) {
  24889. ret += ", Ranges: {";
  24890. var first = true;
  24891. for (var name in this._ranges) {
  24892. if (!first) {
  24893. ret + ", ";
  24894. first = false;
  24895. }
  24896. ret += name;
  24897. }
  24898. ret += "}";
  24899. }
  24900. return ret;
  24901. };
  24902. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  24903. // check name not already in use
  24904. if (!this._ranges[name]) {
  24905. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  24906. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  24907. if (this.bones[i].animations[0]) {
  24908. this.bones[i].animations[0].createRange(name, from, to);
  24909. }
  24910. }
  24911. }
  24912. };
  24913. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  24914. if (deleteFrames === void 0) { deleteFrames = true; }
  24915. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  24916. if (this.bones[i].animations[0]) {
  24917. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  24918. }
  24919. }
  24920. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  24921. };
  24922. Skeleton.prototype.getAnimationRange = function (name) {
  24923. return this._ranges[name];
  24924. };
  24925. /**
  24926. * Returns as an Array, all AnimationRanges defined on this skeleton
  24927. */
  24928. Skeleton.prototype.getAnimationRanges = function () {
  24929. var animationRanges = [];
  24930. var name;
  24931. var i = 0;
  24932. for (name in this._ranges) {
  24933. animationRanges[i] = this._ranges[name];
  24934. i++;
  24935. }
  24936. return animationRanges;
  24937. };
  24938. /**
  24939. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  24940. */
  24941. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  24942. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  24943. if (this._ranges[name] || !source.getAnimationRange(name)) {
  24944. return false;
  24945. }
  24946. var ret = true;
  24947. var frameOffset = this._getHighestAnimationFrame() + 1;
  24948. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  24949. var boneDict = {};
  24950. var sourceBones = source.bones;
  24951. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  24952. boneDict[sourceBones[i].name] = sourceBones[i];
  24953. }
  24954. if (this.bones.length !== sourceBones.length) {
  24955. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  24956. ret = false;
  24957. }
  24958. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  24959. var boneName = this.bones[i].name;
  24960. var sourceBone = boneDict[boneName];
  24961. if (sourceBone) {
  24962. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  24963. }
  24964. else {
  24965. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  24966. ret = false;
  24967. }
  24968. }
  24969. // do not call createAnimationRange(), since it also is done to bones, which was already done
  24970. var range = source.getAnimationRange(name);
  24971. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  24972. return ret;
  24973. };
  24974. Skeleton.prototype.returnToRest = function () {
  24975. for (var index = 0; index < this.bones.length; index++) {
  24976. this.bones[index].returnToRest();
  24977. }
  24978. };
  24979. Skeleton.prototype._getHighestAnimationFrame = function () {
  24980. var ret = 0;
  24981. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  24982. if (this.bones[i].animations[0]) {
  24983. var highest = this.bones[i].animations[0].getHighestFrame();
  24984. if (ret < highest) {
  24985. ret = highest;
  24986. }
  24987. }
  24988. }
  24989. return ret;
  24990. };
  24991. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  24992. var range = this.getAnimationRange(name);
  24993. if (!range) {
  24994. return null;
  24995. }
  24996. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  24997. };
  24998. Skeleton.prototype._markAsDirty = function () {
  24999. this._isDirty = true;
  25000. };
  25001. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  25002. this._meshesWithPoseMatrix.push(mesh);
  25003. };
  25004. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  25005. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  25006. if (index > -1) {
  25007. this._meshesWithPoseMatrix.splice(index, 1);
  25008. }
  25009. };
  25010. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  25011. for (var index = 0; index < this.bones.length; index++) {
  25012. var bone = this.bones[index];
  25013. var parentBone = bone.getParent();
  25014. if (parentBone) {
  25015. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  25016. }
  25017. else {
  25018. if (initialSkinMatrix) {
  25019. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  25020. }
  25021. else {
  25022. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  25023. }
  25024. }
  25025. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  25026. }
  25027. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  25028. };
  25029. Skeleton.prototype.prepare = function () {
  25030. if (!this._isDirty) {
  25031. return;
  25032. }
  25033. if (this.needInitialSkinMatrix) {
  25034. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  25035. var mesh = this._meshesWithPoseMatrix[index];
  25036. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  25037. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  25038. }
  25039. var poseMatrix = mesh.getPoseMatrix();
  25040. // Prepare bones
  25041. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  25042. var bone = this.bones[boneIndex];
  25043. if (!bone.getParent()) {
  25044. var matrix = bone.getBaseMatrix();
  25045. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  25046. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  25047. }
  25048. }
  25049. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  25050. }
  25051. }
  25052. else {
  25053. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  25054. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  25055. }
  25056. this._computeTransformMatrices(this._transformMatrices, null);
  25057. }
  25058. this._isDirty = false;
  25059. this._scene._activeBones += this.bones.length;
  25060. };
  25061. Skeleton.prototype.getAnimatables = function () {
  25062. if (!this._animatables || this._animatables.length !== this.bones.length) {
  25063. this._animatables = [];
  25064. for (var index = 0; index < this.bones.length; index++) {
  25065. this._animatables.push(this.bones[index]);
  25066. }
  25067. }
  25068. return this._animatables;
  25069. };
  25070. Skeleton.prototype.clone = function (name, id) {
  25071. var result = new Skeleton(name, id || name, this._scene);
  25072. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  25073. for (var index = 0; index < this.bones.length; index++) {
  25074. var source = this.bones[index];
  25075. var parentBone = null;
  25076. if (source.getParent()) {
  25077. var parentIndex = this.bones.indexOf(source.getParent());
  25078. parentBone = result.bones[parentIndex];
  25079. }
  25080. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  25081. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  25082. }
  25083. if (this._ranges) {
  25084. result._ranges = {};
  25085. for (var rangeName in this._ranges) {
  25086. result._ranges[rangeName] = this._ranges[rangeName].clone();
  25087. }
  25088. }
  25089. this._isDirty = true;
  25090. return result;
  25091. };
  25092. Skeleton.prototype.dispose = function () {
  25093. this._meshesWithPoseMatrix = [];
  25094. // Animations
  25095. this.getScene().stopAnimation(this);
  25096. // Remove from scene
  25097. this.getScene().removeSkeleton(this);
  25098. };
  25099. Skeleton.prototype.serialize = function () {
  25100. var serializationObject = {};
  25101. serializationObject.name = this.name;
  25102. serializationObject.id = this.id;
  25103. serializationObject.bones = [];
  25104. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  25105. for (var index = 0; index < this.bones.length; index++) {
  25106. var bone = this.bones[index];
  25107. var serializedBone = {
  25108. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  25109. name: bone.name,
  25110. matrix: bone.getLocalMatrix().toArray(),
  25111. rest: bone.getRestPose().toArray()
  25112. };
  25113. serializationObject.bones.push(serializedBone);
  25114. if (bone.length) {
  25115. serializedBone.length = bone.length;
  25116. }
  25117. if (bone.animations && bone.animations.length > 0) {
  25118. serializedBone.animation = bone.animations[0].serialize();
  25119. }
  25120. serializationObject.ranges = [];
  25121. for (var name in this._ranges) {
  25122. var range = {};
  25123. range.name = name;
  25124. range.from = this._ranges[name].from;
  25125. range.to = this._ranges[name].to;
  25126. serializationObject.ranges.push(range);
  25127. }
  25128. }
  25129. return serializationObject;
  25130. };
  25131. Skeleton.Parse = function (parsedSkeleton, scene) {
  25132. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  25133. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  25134. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  25135. var parsedBone = parsedSkeleton.bones[index];
  25136. var parentBone = null;
  25137. if (parsedBone.parentBoneIndex > -1) {
  25138. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  25139. }
  25140. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  25141. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  25142. if (parsedBone.length) {
  25143. bone.length = parsedBone.length;
  25144. }
  25145. if (parsedBone.animation) {
  25146. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  25147. }
  25148. }
  25149. // placed after bones, so createAnimationRange can cascade down
  25150. if (parsedSkeleton.ranges) {
  25151. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  25152. var data = parsedSkeleton.ranges[index];
  25153. skeleton.createAnimationRange(data.name, data.from, data.to);
  25154. }
  25155. }
  25156. return skeleton;
  25157. };
  25158. return Skeleton;
  25159. })();
  25160. BABYLON.Skeleton = Skeleton;
  25161. })(BABYLON || (BABYLON = {}));
  25162. var BABYLON;
  25163. (function (BABYLON) {
  25164. var PostProcess = (function () {
  25165. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  25166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  25167. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  25168. this.name = name;
  25169. this.width = -1;
  25170. this.height = -1;
  25171. this._reusable = false;
  25172. this._textures = new BABYLON.SmartArray(2);
  25173. this._currentRenderTextureInd = 0;
  25174. if (camera != null) {
  25175. this._camera = camera;
  25176. this._scene = camera.getScene();
  25177. camera.attachPostProcess(this);
  25178. this._engine = this._scene.getEngine();
  25179. }
  25180. else {
  25181. this._engine = engine;
  25182. }
  25183. this._renderRatio = ratio;
  25184. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  25185. this._reusable = reusable || false;
  25186. this._textureType = textureType;
  25187. this._samplers = samplers || [];
  25188. this._samplers.push("textureSampler");
  25189. this._fragmentUrl = fragmentUrl;
  25190. this._parameters = parameters || [];
  25191. this.updateEffect(defines);
  25192. }
  25193. PostProcess.prototype.updateEffect = function (defines) {
  25194. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  25195. };
  25196. PostProcess.prototype.isReusable = function () {
  25197. return this._reusable;
  25198. };
  25199. PostProcess.prototype.activate = function (camera, sourceTexture) {
  25200. camera = camera || this._camera;
  25201. var scene = camera.getScene();
  25202. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  25203. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  25204. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  25205. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  25206. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  25207. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  25208. if (this._textures.length > 0) {
  25209. for (var i = 0; i < this._textures.length; i++) {
  25210. this._engine._releaseTexture(this._textures.data[i]);
  25211. }
  25212. this._textures.reset();
  25213. }
  25214. this.width = desiredWidth;
  25215. this.height = desiredHeight;
  25216. 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 }));
  25217. if (this._reusable) {
  25218. 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 }));
  25219. }
  25220. if (this.onSizeChanged) {
  25221. this.onSizeChanged();
  25222. }
  25223. }
  25224. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  25225. if (this.onActivate) {
  25226. this.onActivate(camera);
  25227. }
  25228. // Clear
  25229. if (this.clearColor) {
  25230. this._engine.clear(this.clearColor, true, true);
  25231. }
  25232. else {
  25233. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  25234. }
  25235. if (this._reusable) {
  25236. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  25237. }
  25238. };
  25239. Object.defineProperty(PostProcess.prototype, "isSupported", {
  25240. get: function () {
  25241. return this._effect.isSupported;
  25242. },
  25243. enumerable: true,
  25244. configurable: true
  25245. });
  25246. PostProcess.prototype.apply = function () {
  25247. // Check
  25248. if (!this._effect.isReady())
  25249. return null;
  25250. // States
  25251. this._engine.enableEffect(this._effect);
  25252. this._engine.setState(false);
  25253. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25254. this._engine.setDepthBuffer(false);
  25255. this._engine.setDepthWrite(false);
  25256. // Texture
  25257. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  25258. // Parameters
  25259. if (this.onApply) {
  25260. this.onApply(this._effect);
  25261. }
  25262. return this._effect;
  25263. };
  25264. PostProcess.prototype.dispose = function (camera) {
  25265. camera = camera || this._camera;
  25266. if (this._textures.length > 0) {
  25267. for (var i = 0; i < this._textures.length; i++) {
  25268. this._engine._releaseTexture(this._textures.data[i]);
  25269. }
  25270. this._textures.reset();
  25271. }
  25272. if (!camera) {
  25273. return;
  25274. }
  25275. camera.detachPostProcess(this);
  25276. var index = camera._postProcesses.indexOf(this);
  25277. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  25278. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  25279. }
  25280. };
  25281. return PostProcess;
  25282. })();
  25283. BABYLON.PostProcess = PostProcess;
  25284. })(BABYLON || (BABYLON = {}));
  25285. var BABYLON;
  25286. (function (BABYLON) {
  25287. var PostProcessManager = (function () {
  25288. function PostProcessManager(scene) {
  25289. this._vertexDeclaration = [2];
  25290. this._vertexStrideSize = 2 * 4;
  25291. this._scene = scene;
  25292. }
  25293. PostProcessManager.prototype._prepareBuffers = function () {
  25294. if (this._vertexBuffer) {
  25295. return;
  25296. }
  25297. // VBO
  25298. var vertices = [];
  25299. vertices.push(1, 1);
  25300. vertices.push(-1, 1);
  25301. vertices.push(-1, -1);
  25302. vertices.push(1, -1);
  25303. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  25304. // Indices
  25305. var indices = [];
  25306. indices.push(0);
  25307. indices.push(1);
  25308. indices.push(2);
  25309. indices.push(0);
  25310. indices.push(2);
  25311. indices.push(3);
  25312. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  25313. };
  25314. // Methods
  25315. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  25316. var postProcesses = this._scene.activeCamera._postProcesses;
  25317. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  25318. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  25319. return false;
  25320. }
  25321. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  25322. return true;
  25323. };
  25324. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  25325. var engine = this._scene.getEngine();
  25326. for (var index = 0; index < postProcesses.length; index++) {
  25327. if (index < postProcesses.length - 1) {
  25328. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  25329. }
  25330. else {
  25331. if (targetTexture) {
  25332. engine.bindFramebuffer(targetTexture);
  25333. }
  25334. else {
  25335. engine.restoreDefaultFramebuffer();
  25336. }
  25337. }
  25338. var pp = postProcesses[index];
  25339. var effect = pp.apply();
  25340. if (effect) {
  25341. if (pp.onBeforeRender) {
  25342. pp.onBeforeRender(effect);
  25343. }
  25344. // VBOs
  25345. this._prepareBuffers();
  25346. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25347. // Draw order
  25348. engine.draw(true, 0, 6);
  25349. if (pp.onAfterRender) {
  25350. pp.onAfterRender(effect);
  25351. }
  25352. }
  25353. }
  25354. // Restore depth buffer
  25355. engine.setDepthBuffer(true);
  25356. engine.setDepthWrite(true);
  25357. };
  25358. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  25359. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  25360. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  25361. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  25362. return;
  25363. }
  25364. var engine = this._scene.getEngine();
  25365. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  25366. if (index < postProcessesTakenIndices.length - 1) {
  25367. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  25368. }
  25369. else {
  25370. if (targetTexture) {
  25371. engine.bindFramebuffer(targetTexture, faceIndex);
  25372. }
  25373. else {
  25374. engine.restoreDefaultFramebuffer();
  25375. }
  25376. }
  25377. if (doNotPresent) {
  25378. break;
  25379. }
  25380. var pp = postProcesses[postProcessesTakenIndices[index]];
  25381. var effect = pp.apply();
  25382. if (effect) {
  25383. if (pp.onBeforeRender) {
  25384. pp.onBeforeRender(effect);
  25385. }
  25386. // VBOs
  25387. this._prepareBuffers();
  25388. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25389. // Draw order
  25390. engine.draw(true, 0, 6);
  25391. if (pp.onAfterRender) {
  25392. pp.onAfterRender(effect);
  25393. }
  25394. }
  25395. }
  25396. // Restore depth buffer
  25397. engine.setDepthBuffer(true);
  25398. engine.setDepthWrite(true);
  25399. };
  25400. PostProcessManager.prototype.dispose = function () {
  25401. if (this._vertexBuffer) {
  25402. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25403. this._vertexBuffer = null;
  25404. }
  25405. if (this._indexBuffer) {
  25406. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25407. this._indexBuffer = null;
  25408. }
  25409. };
  25410. return PostProcessManager;
  25411. })();
  25412. BABYLON.PostProcessManager = PostProcessManager;
  25413. })(BABYLON || (BABYLON = {}));
  25414. var BABYLON;
  25415. (function (BABYLON) {
  25416. var PassPostProcess = (function (_super) {
  25417. __extends(PassPostProcess, _super);
  25418. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25419. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  25420. }
  25421. return PassPostProcess;
  25422. })(BABYLON.PostProcess);
  25423. BABYLON.PassPostProcess = PassPostProcess;
  25424. })(BABYLON || (BABYLON = {}));
  25425. var BABYLON;
  25426. (function (BABYLON) {
  25427. /**
  25428. * This is a holder class for the physics joint created by the physics plugin.
  25429. * It holds a set of functions to control the underlying joint.
  25430. */
  25431. var PhysicsJoint = (function () {
  25432. function PhysicsJoint(type, jointData) {
  25433. this.type = type;
  25434. this.jointData = jointData;
  25435. jointData.nativeParams = jointData.nativeParams || {};
  25436. }
  25437. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  25438. get: function () {
  25439. return this._physicsJoint;
  25440. },
  25441. set: function (newJoint) {
  25442. if (this._physicsJoint) {
  25443. }
  25444. this._physicsJoint = newJoint;
  25445. },
  25446. enumerable: true,
  25447. configurable: true
  25448. });
  25449. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  25450. set: function (physicsPlugin) {
  25451. this._physicsPlugin = physicsPlugin;
  25452. },
  25453. enumerable: true,
  25454. configurable: true
  25455. });
  25456. /**
  25457. * Execute a function that is physics-plugin specific.
  25458. * @param {Function} func the function that will be executed.
  25459. * It accepts two parameters: the physics world and the physics joint.
  25460. */
  25461. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  25462. func(this._physicsPlugin.world, this._physicsJoint);
  25463. };
  25464. //TODO check if the native joints are the same
  25465. //Joint Types
  25466. PhysicsJoint.DistanceJoint = 0;
  25467. PhysicsJoint.HingeJoint = 1;
  25468. PhysicsJoint.BallAndSocketJoint = 2;
  25469. PhysicsJoint.WheelJoint = 3;
  25470. PhysicsJoint.SliderJoint = 4;
  25471. //OIMO
  25472. PhysicsJoint.PrismaticJoint = 5;
  25473. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  25474. PhysicsJoint.UniversalJoint = 6;
  25475. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  25476. //Cannon
  25477. //Similar to a Ball-Joint. Different in params
  25478. //TODO check!!
  25479. PhysicsJoint.PointToPointJoint = 8;
  25480. //Cannon only at the moment
  25481. PhysicsJoint.SpringJoint = 9;
  25482. return PhysicsJoint;
  25483. })();
  25484. BABYLON.PhysicsJoint = PhysicsJoint;
  25485. /**
  25486. * A class representing a physics distance joint.
  25487. */
  25488. var DistanceJoint = (function (_super) {
  25489. __extends(DistanceJoint, _super);
  25490. function DistanceJoint(jointData) {
  25491. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  25492. }
  25493. /**
  25494. * Update the predefined distance.
  25495. */
  25496. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  25497. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  25498. };
  25499. return DistanceJoint;
  25500. })(PhysicsJoint);
  25501. BABYLON.DistanceJoint = DistanceJoint;
  25502. /**
  25503. * This class represents a single hinge physics joint
  25504. */
  25505. var HingeJoint = (function (_super) {
  25506. __extends(HingeJoint, _super);
  25507. function HingeJoint(jointData) {
  25508. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  25509. }
  25510. /**
  25511. * Set the motor values.
  25512. * Attention, this function is plugin specific. Engines won't react 100% the same.
  25513. * @param {number} force the force to apply
  25514. * @param {number} maxForce max force for this motor.
  25515. */
  25516. HingeJoint.prototype.setMotor = function (force, maxForce) {
  25517. this._physicsPlugin.setMotor(this, force, maxForce);
  25518. };
  25519. /**
  25520. * Set the motor's limits.
  25521. * Attention, this function is plugin specific. Engines won't react 100% the same.
  25522. */
  25523. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  25524. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  25525. };
  25526. return HingeJoint;
  25527. })(PhysicsJoint);
  25528. BABYLON.HingeJoint = HingeJoint;
  25529. /**
  25530. * This class represents a dual hinge physics joint (same as wheel joint)
  25531. */
  25532. var Hinge2Joint = (function (_super) {
  25533. __extends(Hinge2Joint, _super);
  25534. function Hinge2Joint(jointData) {
  25535. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  25536. }
  25537. /**
  25538. * Set the motor values.
  25539. * Attention, this function is plugin specific. Engines won't react 100% the same.
  25540. * @param {number} force the force to apply
  25541. * @param {number} maxForce max force for this motor.
  25542. * @param {motorIndex} the motor's index, 0 or 1.
  25543. */
  25544. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  25545. if (motorIndex === void 0) { motorIndex = 0; }
  25546. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  25547. };
  25548. /**
  25549. * Set the motor limits.
  25550. * Attention, this function is plugin specific. Engines won't react 100% the same.
  25551. * @param {number} upperLimit the upper limit
  25552. * @param {number} lowerLimit lower limit
  25553. * @param {motorIndex} the motor's index, 0 or 1.
  25554. */
  25555. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  25556. if (motorIndex === void 0) { motorIndex = 0; }
  25557. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  25558. };
  25559. return Hinge2Joint;
  25560. })(PhysicsJoint);
  25561. BABYLON.Hinge2Joint = Hinge2Joint;
  25562. })(BABYLON || (BABYLON = {}));
  25563. var BABYLON;
  25564. (function (BABYLON) {
  25565. var PhysicsImpostor = (function () {
  25566. function PhysicsImpostor(_mesh, type, _options) {
  25567. var _this = this;
  25568. if (_options === void 0) { _options = { mass: 0 }; }
  25569. this._mesh = _mesh;
  25570. this.type = type;
  25571. this._options = _options;
  25572. this._bodyUpdateRequired = false;
  25573. this._onBeforePhysicsStepCallbacks = new Array();
  25574. this._onAfterPhysicsStepCallbacks = new Array();
  25575. this._onPhysicsCollideCallbacks = [];
  25576. this._deltaPosition = BABYLON.Vector3.Zero();
  25577. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  25578. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  25579. /**
  25580. * this function is executed by the physics engine.
  25581. */
  25582. this.beforeStep = function () {
  25583. _this.mesh.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  25584. //conjugate deltaRotation
  25585. if (_this._deltaRotationConjugated) {
  25586. _this.mesh.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  25587. }
  25588. else {
  25589. _this._tmpRotationWithDelta.copyFrom(_this.mesh.rotationQuaternion);
  25590. }
  25591. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  25592. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  25593. func(_this);
  25594. });
  25595. };
  25596. /**
  25597. * this function is executed by the physics engine.
  25598. */
  25599. this.afterStep = function () {
  25600. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  25601. func(_this);
  25602. });
  25603. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  25604. _this.mesh.position.addInPlace(_this._deltaPosition);
  25605. if (_this._deltaRotation) {
  25606. _this.mesh.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  25607. }
  25608. };
  25609. //event and body object due to cannon's event-based architecture.
  25610. this.onCollide = function (e) {
  25611. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  25612. if (otherImpostor) {
  25613. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  25614. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  25615. }).forEach(function (obj) {
  25616. obj.callback(_this, otherImpostor);
  25617. });
  25618. }
  25619. };
  25620. this._physicsEngine = this._mesh.getScene().getPhysicsEngine();
  25621. if (!this._physicsEngine) {
  25622. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  25623. }
  25624. else {
  25625. //default options params
  25626. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  25627. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  25628. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  25629. this._joints = [];
  25630. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  25631. if (!this._mesh.parent) {
  25632. this._init();
  25633. }
  25634. }
  25635. }
  25636. /**
  25637. * This function will completly initialize this impostor.
  25638. * It will create a new body - but only if this mesh has no parent.
  25639. * If it has, this impostor will not be used other than to define the impostor
  25640. * of the child mesh.
  25641. */
  25642. PhysicsImpostor.prototype._init = function () {
  25643. this._physicsEngine.removeImpostor(this);
  25644. this.physicsBody = null;
  25645. this._parent = this._parent || this._getPhysicsParent();
  25646. if (!this.parent) {
  25647. this._physicsEngine.addImpostor(this);
  25648. }
  25649. };
  25650. PhysicsImpostor.prototype._getPhysicsParent = function () {
  25651. if (this.mesh.parent instanceof BABYLON.AbstractMesh) {
  25652. var parentMesh = this.mesh.parent;
  25653. return parentMesh.getPhysicsImpostor();
  25654. }
  25655. return;
  25656. };
  25657. /**
  25658. * Should a new body be generated.
  25659. */
  25660. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  25661. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  25662. };
  25663. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  25664. this.forceUpdate();
  25665. };
  25666. /**
  25667. * Force a regeneration of this or the parent's impostor's body.
  25668. * Use under cautious - This will remove all joints already implemented.
  25669. */
  25670. PhysicsImpostor.prototype.forceUpdate = function () {
  25671. this._init();
  25672. if (this.parent) {
  25673. this.parent.forceUpdate();
  25674. }
  25675. };
  25676. Object.defineProperty(PhysicsImpostor.prototype, "mesh", {
  25677. get: function () {
  25678. return this._mesh;
  25679. },
  25680. enumerable: true,
  25681. configurable: true
  25682. });
  25683. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  25684. /**
  25685. * Gets the body that holds this impostor. Either its own, or its parent.
  25686. */
  25687. get: function () {
  25688. return this._parent ? this._parent.physicsBody : this._physicsBody;
  25689. },
  25690. /**
  25691. * Set the physics body. Used mainly by the physics engine/plugin
  25692. */
  25693. set: function (physicsBody) {
  25694. if (this._physicsBody) {
  25695. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  25696. }
  25697. this._physicsBody = physicsBody;
  25698. this.resetUpdateFlags();
  25699. },
  25700. enumerable: true,
  25701. configurable: true
  25702. });
  25703. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  25704. get: function () {
  25705. return this._parent;
  25706. },
  25707. enumerable: true,
  25708. configurable: true
  25709. });
  25710. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  25711. this._bodyUpdateRequired = false;
  25712. };
  25713. /**
  25714. * Get a specific parametes from the options parameter.
  25715. */
  25716. PhysicsImpostor.prototype.getParam = function (paramName) {
  25717. return this._options[paramName];
  25718. };
  25719. /**
  25720. * Sets a specific parameter in the options given to the physics plugin
  25721. */
  25722. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  25723. this._options[paramName] = value;
  25724. this._bodyUpdateRequired = true;
  25725. };
  25726. /**
  25727. * Specifically change the body's mass option. Won't recreate the physics body object
  25728. */
  25729. PhysicsImpostor.prototype.setMass = function (mass) {
  25730. if (this.getParam("mass") !== mass) {
  25731. this.setParam("mass", mass);
  25732. }
  25733. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  25734. };
  25735. PhysicsImpostor.prototype.getLinearVelocity = function () {
  25736. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  25737. };
  25738. /**
  25739. * Set the body's linear velocity.
  25740. */
  25741. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  25742. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  25743. };
  25744. PhysicsImpostor.prototype.getAngularVelocity = function () {
  25745. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  25746. };
  25747. /**
  25748. * Set the body's linear velocity.
  25749. */
  25750. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  25751. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  25752. };
  25753. /**
  25754. * Execute a function with the physics plugin native code.
  25755. * Provide a function the will have two variables - the world object and the physics body object.
  25756. */
  25757. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  25758. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  25759. };
  25760. /**
  25761. * Register a function that will be executed before the physics world is stepping forward.
  25762. */
  25763. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  25764. this._onBeforePhysicsStepCallbacks.push(func);
  25765. };
  25766. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  25767. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  25768. if (index > -1) {
  25769. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  25770. }
  25771. else {
  25772. BABYLON.Tools.Warn("Function to remove was not found");
  25773. }
  25774. };
  25775. /**
  25776. * Register a function that will be executed after the physics step
  25777. */
  25778. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  25779. this._onAfterPhysicsStepCallbacks.push(func);
  25780. };
  25781. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  25782. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  25783. if (index > -1) {
  25784. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  25785. }
  25786. else {
  25787. BABYLON.Tools.Warn("Function to remove was not found");
  25788. }
  25789. };
  25790. /**
  25791. * register a function that will be executed when this impostor collides against a different body.
  25792. */
  25793. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  25794. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  25795. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  25796. };
  25797. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  25798. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  25799. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  25800. if (index > -1) {
  25801. this._onPhysicsCollideCallbacks.splice(index, 1);
  25802. }
  25803. else {
  25804. BABYLON.Tools.Warn("Function to remove was not found");
  25805. }
  25806. };
  25807. /**
  25808. * Apply a force
  25809. */
  25810. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  25811. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  25812. };
  25813. /**
  25814. * Apply an impulse
  25815. */
  25816. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  25817. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  25818. };
  25819. /**
  25820. * A help function to create a joint.
  25821. */
  25822. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  25823. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  25824. this.addJoint(otherImpostor, joint);
  25825. };
  25826. /**
  25827. * Add a joint to this impostor with a different impostor.
  25828. */
  25829. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  25830. this._joints.push({
  25831. otherImpostor: otherImpostor,
  25832. joint: joint
  25833. });
  25834. this._physicsEngine.addJoint(this, otherImpostor, joint);
  25835. };
  25836. /**
  25837. * Will keep this body still, in a sleep mode.
  25838. */
  25839. PhysicsImpostor.prototype.sleep = function () {
  25840. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  25841. };
  25842. /**
  25843. * Wake the body up.
  25844. */
  25845. PhysicsImpostor.prototype.wakeUp = function () {
  25846. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  25847. };
  25848. PhysicsImpostor.prototype.dispose = function (disposeChildren) {
  25849. if (disposeChildren === void 0) { disposeChildren = true; }
  25850. this.physicsBody = null;
  25851. if (this.parent) {
  25852. this.parent.forceUpdate();
  25853. }
  25854. else {
  25855. this.mesh.getChildMeshes().forEach(function (mesh) {
  25856. if (mesh.physicsImpostor) {
  25857. if (disposeChildren) {
  25858. mesh.physicsImpostor.dispose();
  25859. mesh.physicsImpostor = null;
  25860. }
  25861. }
  25862. });
  25863. }
  25864. };
  25865. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  25866. this._deltaPosition.copyFrom(position);
  25867. };
  25868. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  25869. if (!this._deltaRotation) {
  25870. this._deltaRotation = new BABYLON.Quaternion();
  25871. }
  25872. this._deltaRotation.copyFrom(rotation);
  25873. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  25874. };
  25875. //Impostor types
  25876. PhysicsImpostor.NoImpostor = 0;
  25877. PhysicsImpostor.SphereImpostor = 1;
  25878. PhysicsImpostor.BoxImpostor = 2;
  25879. PhysicsImpostor.PlaneImpostor = 3;
  25880. PhysicsImpostor.MeshImpostor = 4;
  25881. PhysicsImpostor.CapsuleImpostor = 5;
  25882. PhysicsImpostor.ConeImpostor = 6;
  25883. PhysicsImpostor.CylinderImpostor = 7;
  25884. PhysicsImpostor.ConvexHullImpostor = 8;
  25885. PhysicsImpostor.HeightmapImpostor = 9;
  25886. return PhysicsImpostor;
  25887. })();
  25888. BABYLON.PhysicsImpostor = PhysicsImpostor;
  25889. })(BABYLON || (BABYLON = {}));
  25890. var BABYLON;
  25891. (function (BABYLON) {
  25892. var PhysicsEngine = (function () {
  25893. function PhysicsEngine(gravity, _physicsPlugin) {
  25894. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  25895. this._physicsPlugin = _physicsPlugin;
  25896. //new methods and parameters
  25897. this._impostors = [];
  25898. this._joints = [];
  25899. if (!this._physicsPlugin.isSupported()) {
  25900. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  25901. + "Please make sure it is included.");
  25902. }
  25903. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  25904. this.setGravity(gravity);
  25905. this.setTimeStep();
  25906. }
  25907. PhysicsEngine.prototype.setGravity = function (gravity) {
  25908. this.gravity = gravity;
  25909. this._physicsPlugin.setGravity(this.gravity);
  25910. };
  25911. /**
  25912. * Set the time step of the physics engine.
  25913. * default is 1/60.
  25914. * To slow it down, enter 1/600 for example.
  25915. * To speed it up, 1/30
  25916. * @param {number} newTimeStep the new timestep to apply to this world.
  25917. */
  25918. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  25919. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  25920. this._physicsPlugin.setTimeStep(newTimeStep);
  25921. };
  25922. PhysicsEngine.prototype.dispose = function () {
  25923. this._impostors.forEach(function (impostor) {
  25924. impostor.dispose();
  25925. });
  25926. this._physicsPlugin.dispose();
  25927. };
  25928. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  25929. return this._physicsPlugin.name;
  25930. };
  25931. /**
  25932. * Adding a new impostor for the impostor tracking.
  25933. * This will be done by the impostor itself.
  25934. * @param {PhysicsImpostor} impostor the impostor to add
  25935. */
  25936. PhysicsEngine.prototype.addImpostor = function (impostor) {
  25937. this._impostors.push(impostor);
  25938. //if no parent, generate the body
  25939. if (!impostor.parent) {
  25940. this._physicsPlugin.generatePhysicsBody(impostor);
  25941. }
  25942. };
  25943. /**
  25944. * Remove an impostor from the engine.
  25945. * This impostor and its mesh will not longer be updated by the physics engine.
  25946. * @param {PhysicsImpostor} impostor the impostor to remove
  25947. */
  25948. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  25949. var index = this._impostors.indexOf(impostor);
  25950. if (index > -1) {
  25951. var removed = this._impostors.splice(index, 1);
  25952. //Is it needed?
  25953. if (removed.length) {
  25954. //this will also remove it from the world.
  25955. removed[0].physicsBody = null;
  25956. }
  25957. }
  25958. };
  25959. /**
  25960. * Add a joint to the physics engine
  25961. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  25962. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  25963. * @param {PhysicsJoint} the joint that will connect both impostors.
  25964. */
  25965. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  25966. var impostorJoint = {
  25967. mainImpostor: mainImpostor,
  25968. connectedImpostor: connectedImpostor,
  25969. joint: joint
  25970. };
  25971. joint.physicsPlugin = this._physicsPlugin;
  25972. this._joints.push(impostorJoint);
  25973. this._physicsPlugin.generateJoint(impostorJoint);
  25974. };
  25975. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  25976. var matchingJoints = this._joints.filter(function (impostorJoint) {
  25977. return (impostorJoint.connectedImpostor === connectedImpostor
  25978. && impostorJoint.joint === joint
  25979. && impostorJoint.mainImpostor === mainImpostor);
  25980. });
  25981. if (matchingJoints.length) {
  25982. this._physicsPlugin.removeJoint(matchingJoints[0]);
  25983. }
  25984. };
  25985. /**
  25986. * Called by the scene. no need to call it.
  25987. */
  25988. PhysicsEngine.prototype._step = function (delta) {
  25989. var _this = this;
  25990. //check if any mesh has no body / requires an update
  25991. this._impostors.forEach(function (impostor) {
  25992. if (impostor.isBodyInitRequired()) {
  25993. _this._physicsPlugin.generatePhysicsBody(impostor);
  25994. }
  25995. });
  25996. if (delta > 0.1) {
  25997. delta = 0.1;
  25998. }
  25999. else if (delta <= 0) {
  26000. delta = 1.0 / 60.0;
  26001. }
  26002. this._physicsPlugin.executeStep(delta, this._impostors);
  26003. };
  26004. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  26005. return this._physicsPlugin;
  26006. };
  26007. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  26008. for (var i = 0; i < this._impostors.length; ++i) {
  26009. if (this._impostors[i].physicsBody === body) {
  26010. return this._impostors[i];
  26011. }
  26012. }
  26013. };
  26014. // Statics, Legacy support.
  26015. /**
  26016. * @Deprecated
  26017. *
  26018. */
  26019. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  26020. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  26021. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  26022. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  26023. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  26024. PhysicsEngine.CapsuleImpostor = BABYLON.PhysicsImpostor.CapsuleImpostor;
  26025. PhysicsEngine.ConeImpostor = BABYLON.PhysicsImpostor.ConeImpostor;
  26026. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  26027. PhysicsEngine.ConvexHullImpostor = BABYLON.PhysicsImpostor.ConvexHullImpostor;
  26028. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  26029. PhysicsEngine.Epsilon = 0.001;
  26030. return PhysicsEngine;
  26031. })();
  26032. BABYLON.PhysicsEngine = PhysicsEngine;
  26033. })(BABYLON || (BABYLON = {}));
  26034. var BABYLON;
  26035. (function (BABYLON) {
  26036. var VertexData = (function () {
  26037. function VertexData() {
  26038. }
  26039. VertexData.prototype.set = function (data, kind) {
  26040. switch (kind) {
  26041. case BABYLON.VertexBuffer.PositionKind:
  26042. this.positions = data;
  26043. break;
  26044. case BABYLON.VertexBuffer.NormalKind:
  26045. this.normals = data;
  26046. break;
  26047. case BABYLON.VertexBuffer.UVKind:
  26048. this.uvs = data;
  26049. break;
  26050. case BABYLON.VertexBuffer.UV2Kind:
  26051. this.uvs2 = data;
  26052. break;
  26053. case BABYLON.VertexBuffer.UV3Kind:
  26054. this.uvs3 = data;
  26055. break;
  26056. case BABYLON.VertexBuffer.UV4Kind:
  26057. this.uvs4 = data;
  26058. break;
  26059. case BABYLON.VertexBuffer.UV5Kind:
  26060. this.uvs5 = data;
  26061. break;
  26062. case BABYLON.VertexBuffer.UV6Kind:
  26063. this.uvs6 = data;
  26064. break;
  26065. case BABYLON.VertexBuffer.ColorKind:
  26066. this.colors = data;
  26067. break;
  26068. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26069. this.matricesIndices = data;
  26070. break;
  26071. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26072. this.matricesWeights = data;
  26073. break;
  26074. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26075. this.matricesIndicesExtra = data;
  26076. break;
  26077. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26078. this.matricesWeightsExtra = data;
  26079. break;
  26080. }
  26081. };
  26082. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26083. this._applyTo(mesh, updatable);
  26084. };
  26085. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26086. this._applyTo(geometry, updatable);
  26087. };
  26088. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26089. this._update(mesh);
  26090. };
  26091. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26092. this._update(geometry);
  26093. };
  26094. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26095. if (this.positions) {
  26096. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26097. }
  26098. if (this.normals) {
  26099. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26100. }
  26101. if (this.uvs) {
  26102. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26103. }
  26104. if (this.uvs2) {
  26105. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26106. }
  26107. if (this.uvs3) {
  26108. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26109. }
  26110. if (this.uvs4) {
  26111. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26112. }
  26113. if (this.uvs5) {
  26114. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26115. }
  26116. if (this.uvs6) {
  26117. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26118. }
  26119. if (this.colors) {
  26120. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26121. }
  26122. if (this.matricesIndices) {
  26123. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26124. }
  26125. if (this.matricesWeights) {
  26126. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26127. }
  26128. if (this.matricesIndicesExtra) {
  26129. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26130. }
  26131. if (this.matricesWeightsExtra) {
  26132. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26133. }
  26134. if (this.indices) {
  26135. meshOrGeometry.setIndices(this.indices);
  26136. }
  26137. };
  26138. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26139. if (this.positions) {
  26140. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26141. }
  26142. if (this.normals) {
  26143. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26144. }
  26145. if (this.uvs) {
  26146. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26147. }
  26148. if (this.uvs2) {
  26149. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26150. }
  26151. if (this.uvs3) {
  26152. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26153. }
  26154. if (this.uvs4) {
  26155. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26156. }
  26157. if (this.uvs5) {
  26158. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26159. }
  26160. if (this.uvs6) {
  26161. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26162. }
  26163. if (this.colors) {
  26164. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26165. }
  26166. if (this.matricesIndices) {
  26167. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26168. }
  26169. if (this.matricesWeights) {
  26170. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26171. }
  26172. if (this.matricesIndicesExtra) {
  26173. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26174. }
  26175. if (this.matricesWeightsExtra) {
  26176. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26177. }
  26178. if (this.indices) {
  26179. meshOrGeometry.setIndices(this.indices);
  26180. }
  26181. };
  26182. VertexData.prototype.transform = function (matrix) {
  26183. var transformed = BABYLON.Vector3.Zero();
  26184. var index;
  26185. if (this.positions) {
  26186. var position = BABYLON.Vector3.Zero();
  26187. for (index = 0; index < this.positions.length; index += 3) {
  26188. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26189. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26190. this.positions[index] = transformed.x;
  26191. this.positions[index + 1] = transformed.y;
  26192. this.positions[index + 2] = transformed.z;
  26193. }
  26194. }
  26195. if (this.normals) {
  26196. var normal = BABYLON.Vector3.Zero();
  26197. for (index = 0; index < this.normals.length; index += 3) {
  26198. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26199. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26200. this.normals[index] = transformed.x;
  26201. this.normals[index + 1] = transformed.y;
  26202. this.normals[index + 2] = transformed.z;
  26203. }
  26204. }
  26205. };
  26206. VertexData.prototype.merge = function (other) {
  26207. if (other.indices) {
  26208. if (!this.indices) {
  26209. this.indices = [];
  26210. }
  26211. var offset = this.positions ? this.positions.length / 3 : 0;
  26212. for (var index = 0; index < other.indices.length; index++) {
  26213. //TODO check type - if Int32Array!
  26214. this.indices.push(other.indices[index] + offset);
  26215. }
  26216. }
  26217. this.positions = this._mergeElement(this.positions, other.positions);
  26218. this.normals = this._mergeElement(this.normals, other.normals);
  26219. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26220. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26221. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26222. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26223. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26224. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26225. this.colors = this._mergeElement(this.colors, other.colors);
  26226. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26227. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26228. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26229. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26230. };
  26231. VertexData.prototype._mergeElement = function (source, other) {
  26232. if (!other)
  26233. return source;
  26234. if (!source)
  26235. return other;
  26236. var len = other.length + source.length;
  26237. var isSrcTypedArray = source instanceof Float32Array;
  26238. var isOthTypedArray = other instanceof Float32Array;
  26239. // use non-loop method when the source is Float32Array
  26240. if (isSrcTypedArray) {
  26241. var ret32 = new Float32Array(len);
  26242. ret32.set(source);
  26243. ret32.set(other, source.length);
  26244. return ret32;
  26245. }
  26246. else if (!isOthTypedArray) {
  26247. return source.concat(other);
  26248. }
  26249. else {
  26250. var ret = source.slice(0); // copy source to a separate array
  26251. for (var i = 0, len = other.length; i < len; i++) {
  26252. ret.push(other[i]);
  26253. }
  26254. return ret;
  26255. }
  26256. };
  26257. VertexData.prototype.serialize = function () {
  26258. var serializationObject = this.serialize();
  26259. if (this.positions) {
  26260. serializationObject.positions = this.positions;
  26261. }
  26262. if (this.normals) {
  26263. serializationObject.normals = this.normals;
  26264. }
  26265. if (this.uvs) {
  26266. serializationObject.uvs = this.uvs;
  26267. }
  26268. if (this.uvs2) {
  26269. serializationObject.uvs2 = this.uvs2;
  26270. }
  26271. if (this.uvs3) {
  26272. serializationObject.uvs3 = this.uvs3;
  26273. }
  26274. if (this.uvs4) {
  26275. serializationObject.uvs4 = this.uvs4;
  26276. }
  26277. if (this.uvs5) {
  26278. serializationObject.uvs5 = this.uvs5;
  26279. }
  26280. if (this.uvs6) {
  26281. serializationObject.uvs6 = this.uvs6;
  26282. }
  26283. if (this.colors) {
  26284. serializationObject.colors = this.colors;
  26285. }
  26286. if (this.matricesIndices) {
  26287. serializationObject.matricesIndices = this.matricesIndices;
  26288. serializationObject.matricesIndices._isExpanded = true;
  26289. }
  26290. if (this.matricesWeights) {
  26291. serializationObject.matricesWeights = this.matricesWeights;
  26292. }
  26293. if (this.matricesIndicesExtra) {
  26294. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26295. serializationObject.matricesIndicesExtra._isExpanded = true;
  26296. }
  26297. if (this.matricesWeightsExtra) {
  26298. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26299. }
  26300. serializationObject.indices = this.indices;
  26301. return serializationObject;
  26302. };
  26303. // Statics
  26304. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26305. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26306. };
  26307. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26308. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26309. };
  26310. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26311. var result = new VertexData();
  26312. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26313. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26314. }
  26315. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26316. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26317. }
  26318. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26319. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26320. }
  26321. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26322. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26323. }
  26324. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26325. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26326. }
  26327. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26328. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26329. }
  26330. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26331. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26332. }
  26333. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26334. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26335. }
  26336. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26337. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26338. }
  26339. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26340. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26341. }
  26342. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26343. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26344. }
  26345. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26346. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  26347. }
  26348. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26349. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  26350. }
  26351. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26352. return result;
  26353. };
  26354. VertexData.CreateRibbon = function (options) {
  26355. var pathArray = options.pathArray;
  26356. var closeArray = options.closeArray || false;
  26357. var closePath = options.closePath || false;
  26358. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26359. var offset = options.offset || defaultOffset;
  26360. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26361. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26362. var positions = [];
  26363. var indices = [];
  26364. var normals = [];
  26365. var uvs = [];
  26366. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26367. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26368. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26369. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26370. var minlg; // minimal length among all paths from pathArray
  26371. var lg = []; // array of path lengths : nb of vertex per path
  26372. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26373. var p; // path iterator
  26374. var i; // point iterator
  26375. var j; // point iterator
  26376. // if single path in pathArray
  26377. if (pathArray.length < 2) {
  26378. var ar1 = [];
  26379. var ar2 = [];
  26380. for (i = 0; i < pathArray[0].length - offset; i++) {
  26381. ar1.push(pathArray[0][i]);
  26382. ar2.push(pathArray[0][i + offset]);
  26383. }
  26384. pathArray = [ar1, ar2];
  26385. }
  26386. // positions and horizontal distances (u)
  26387. var idc = 0;
  26388. var closePathCorr = (closePath) ? 1 : 0;
  26389. var path;
  26390. var l;
  26391. minlg = pathArray[0].length;
  26392. var vectlg;
  26393. var dist;
  26394. for (p = 0; p < pathArray.length; p++) {
  26395. uTotalDistance[p] = 0;
  26396. us[p] = [0];
  26397. path = pathArray[p];
  26398. l = path.length;
  26399. minlg = (minlg < l) ? minlg : l;
  26400. j = 0;
  26401. while (j < l) {
  26402. positions.push(path[j].x, path[j].y, path[j].z);
  26403. if (j > 0) {
  26404. vectlg = path[j].subtract(path[j - 1]).length();
  26405. dist = vectlg + uTotalDistance[p];
  26406. us[p].push(dist);
  26407. uTotalDistance[p] = dist;
  26408. }
  26409. j++;
  26410. }
  26411. if (closePath) {
  26412. j--;
  26413. positions.push(path[0].x, path[0].y, path[0].z);
  26414. vectlg = path[j].subtract(path[0]).length();
  26415. dist = vectlg + uTotalDistance[p];
  26416. us[p].push(dist);
  26417. uTotalDistance[p] = dist;
  26418. }
  26419. lg[p] = l + closePathCorr;
  26420. idx[p] = idc;
  26421. idc += (l + closePathCorr);
  26422. }
  26423. // vertical distances (v)
  26424. var path1;
  26425. var path2;
  26426. var vertex1;
  26427. var vertex2;
  26428. for (i = 0; i < minlg + closePathCorr; i++) {
  26429. vTotalDistance[i] = 0;
  26430. vs[i] = [0];
  26431. for (p = 0; p < pathArray.length - 1; p++) {
  26432. path1 = pathArray[p];
  26433. path2 = pathArray[p + 1];
  26434. if (i === minlg) {
  26435. vertex1 = path1[0];
  26436. vertex2 = path2[0];
  26437. }
  26438. else {
  26439. vertex1 = path1[i];
  26440. vertex2 = path2[i];
  26441. }
  26442. vectlg = vertex2.subtract(vertex1).length();
  26443. dist = vectlg + vTotalDistance[i];
  26444. vs[i].push(dist);
  26445. vTotalDistance[i] = dist;
  26446. }
  26447. if (closeArray) {
  26448. path1 = pathArray[p];
  26449. path2 = pathArray[0];
  26450. if (i === minlg) {
  26451. vertex2 = path2[0];
  26452. }
  26453. vectlg = vertex2.subtract(vertex1).length();
  26454. dist = vectlg + vTotalDistance[i];
  26455. vTotalDistance[i] = dist;
  26456. }
  26457. }
  26458. // uvs
  26459. var u;
  26460. var v;
  26461. for (p = 0; p < pathArray.length; p++) {
  26462. for (i = 0; i < minlg + closePathCorr; i++) {
  26463. u = us[p][i] / uTotalDistance[p];
  26464. v = vs[i][p] / vTotalDistance[i];
  26465. uvs.push(u, v);
  26466. }
  26467. }
  26468. // indices
  26469. p = 0; // path index
  26470. var pi = 0; // positions array index
  26471. var l1 = lg[p] - 1; // path1 length
  26472. var l2 = lg[p + 1] - 1; // path2 length
  26473. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26474. var shft = idx[1] - idx[0]; // shift
  26475. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26476. while (pi <= min && p < path1nb) {
  26477. // 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
  26478. indices.push(pi, pi + shft, pi + 1);
  26479. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26480. pi += 1;
  26481. if (pi === min) {
  26482. p++;
  26483. if (p === lg.length - 1) {
  26484. shft = idx[0] - idx[p];
  26485. l1 = lg[p] - 1;
  26486. l2 = lg[0] - 1;
  26487. }
  26488. else {
  26489. shft = idx[p + 1] - idx[p];
  26490. l1 = lg[p] - 1;
  26491. l2 = lg[p + 1] - 1;
  26492. }
  26493. pi = idx[p];
  26494. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26495. }
  26496. }
  26497. // normals
  26498. VertexData.ComputeNormals(positions, indices, normals);
  26499. if (closePath) {
  26500. var indexFirst = 0;
  26501. var indexLast = 0;
  26502. for (p = 0; p < pathArray.length; p++) {
  26503. indexFirst = idx[p] * 3;
  26504. if (p + 1 < pathArray.length) {
  26505. indexLast = (idx[p + 1] - 1) * 3;
  26506. }
  26507. else {
  26508. indexLast = normals.length - 3;
  26509. }
  26510. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26511. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26512. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26513. normals[indexLast] = normals[indexFirst];
  26514. normals[indexLast + 1] = normals[indexFirst + 1];
  26515. normals[indexLast + 2] = normals[indexFirst + 2];
  26516. }
  26517. }
  26518. // sides
  26519. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26520. // Result
  26521. var vertexData = new VertexData();
  26522. vertexData.indices = indices;
  26523. vertexData.positions = positions;
  26524. vertexData.normals = normals;
  26525. vertexData.uvs = uvs;
  26526. if (closePath) {
  26527. vertexData._idx = idx;
  26528. }
  26529. return vertexData;
  26530. };
  26531. VertexData.CreateBox = function (options) {
  26532. var normalsSource = [
  26533. new BABYLON.Vector3(0, 0, 1),
  26534. new BABYLON.Vector3(0, 0, -1),
  26535. new BABYLON.Vector3(1, 0, 0),
  26536. new BABYLON.Vector3(-1, 0, 0),
  26537. new BABYLON.Vector3(0, 1, 0),
  26538. new BABYLON.Vector3(0, -1, 0)
  26539. ];
  26540. var indices = [];
  26541. var positions = [];
  26542. var normals = [];
  26543. var uvs = [];
  26544. var width = options.width || options.size || 1;
  26545. var height = options.height || options.size || 1;
  26546. var depth = options.depth || options.size || 1;
  26547. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26548. var faceUV = options.faceUV || new Array(6);
  26549. var faceColors = options.faceColors;
  26550. var colors = [];
  26551. // default face colors and UV if undefined
  26552. for (var f = 0; f < 6; f++) {
  26553. if (faceUV[f] === undefined) {
  26554. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26555. }
  26556. if (faceColors && faceColors[f] === undefined) {
  26557. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26558. }
  26559. }
  26560. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26561. // Create each face in turn.
  26562. for (var index = 0; index < normalsSource.length; index++) {
  26563. var normal = normalsSource[index];
  26564. // Get two vectors perpendicular to the face normal and to each other.
  26565. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26566. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26567. // Six indices (two triangles) per face.
  26568. var verticesLength = positions.length / 3;
  26569. indices.push(verticesLength);
  26570. indices.push(verticesLength + 1);
  26571. indices.push(verticesLength + 2);
  26572. indices.push(verticesLength);
  26573. indices.push(verticesLength + 2);
  26574. indices.push(verticesLength + 3);
  26575. // Four vertices per face.
  26576. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26577. positions.push(vertex.x, vertex.y, vertex.z);
  26578. normals.push(normal.x, normal.y, normal.z);
  26579. uvs.push(faceUV[index].z, faceUV[index].w);
  26580. if (faceColors) {
  26581. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26582. }
  26583. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26584. positions.push(vertex.x, vertex.y, vertex.z);
  26585. normals.push(normal.x, normal.y, normal.z);
  26586. uvs.push(faceUV[index].x, faceUV[index].w);
  26587. if (faceColors) {
  26588. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26589. }
  26590. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26591. positions.push(vertex.x, vertex.y, vertex.z);
  26592. normals.push(normal.x, normal.y, normal.z);
  26593. uvs.push(faceUV[index].x, faceUV[index].y);
  26594. if (faceColors) {
  26595. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26596. }
  26597. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26598. positions.push(vertex.x, vertex.y, vertex.z);
  26599. normals.push(normal.x, normal.y, normal.z);
  26600. uvs.push(faceUV[index].z, faceUV[index].y);
  26601. if (faceColors) {
  26602. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26603. }
  26604. }
  26605. // sides
  26606. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26607. // Result
  26608. var vertexData = new VertexData();
  26609. vertexData.indices = indices;
  26610. vertexData.positions = positions;
  26611. vertexData.normals = normals;
  26612. vertexData.uvs = uvs;
  26613. if (faceColors) {
  26614. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26615. vertexData.colors = totalColors;
  26616. }
  26617. return vertexData;
  26618. };
  26619. VertexData.CreateSphere = function (options) {
  26620. var segments = options.segments || 32;
  26621. var diameterX = options.diameterX || options.diameter || 1;
  26622. var diameterY = options.diameterY || options.diameter || 1;
  26623. var diameterZ = options.diameterZ || options.diameter || 1;
  26624. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26625. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26626. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26627. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26628. var totalZRotationSteps = 2 + segments;
  26629. var totalYRotationSteps = 2 * totalZRotationSteps;
  26630. var indices = [];
  26631. var positions = [];
  26632. var normals = [];
  26633. var uvs = [];
  26634. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26635. var normalizedZ = zRotationStep / totalZRotationSteps;
  26636. var angleZ = normalizedZ * Math.PI * slice;
  26637. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26638. var normalizedY = yRotationStep / totalYRotationSteps;
  26639. var angleY = normalizedY * Math.PI * 2 * arc;
  26640. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26641. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26642. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26643. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26644. var vertex = complete.multiply(radius);
  26645. var normal = complete.divide(radius).normalize();
  26646. positions.push(vertex.x, vertex.y, vertex.z);
  26647. normals.push(normal.x, normal.y, normal.z);
  26648. uvs.push(normalizedY, normalizedZ);
  26649. }
  26650. if (zRotationStep > 0) {
  26651. var verticesCount = positions.length / 3;
  26652. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26653. indices.push((firstIndex));
  26654. indices.push((firstIndex + 1));
  26655. indices.push(firstIndex + totalYRotationSteps + 1);
  26656. indices.push((firstIndex + totalYRotationSteps + 1));
  26657. indices.push((firstIndex + 1));
  26658. indices.push((firstIndex + totalYRotationSteps + 2));
  26659. }
  26660. }
  26661. }
  26662. // Sides
  26663. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26664. // Result
  26665. var vertexData = new VertexData();
  26666. vertexData.indices = indices;
  26667. vertexData.positions = positions;
  26668. vertexData.normals = normals;
  26669. vertexData.uvs = uvs;
  26670. return vertexData;
  26671. };
  26672. // Cylinder and cone
  26673. VertexData.CreateCylinder = function (options) {
  26674. var height = options.height || 2;
  26675. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  26676. var diameterBottom = options.diameterBottom || options.diameter || 1;
  26677. var tessellation = options.tessellation || 24;
  26678. var subdivisions = options.subdivisions || 1;
  26679. var hasRings = options.hasRings;
  26680. var enclose = options.enclose;
  26681. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26682. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26683. var faceUV = options.faceUV || new Array(3);
  26684. var faceColors = options.faceColors;
  26685. // default face colors and UV if undefined
  26686. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  26687. var ringNb = (hasRings) ? subdivisions : 1;
  26688. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  26689. var f;
  26690. for (f = 0; f < surfaceNb; f++) {
  26691. if (faceColors && faceColors[f] === undefined) {
  26692. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26693. }
  26694. }
  26695. for (f = 0; f < surfaceNb; f++) {
  26696. if (faceUV && faceUV[f] === undefined) {
  26697. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26698. }
  26699. }
  26700. var indices = [];
  26701. var positions = [];
  26702. var normals = [];
  26703. var uvs = [];
  26704. var colors = [];
  26705. var angle_step = Math.PI * 2 * arc / tessellation;
  26706. var angle;
  26707. var h;
  26708. var radius;
  26709. var tan = (diameterBottom - diameterTop) / 2 / height;
  26710. var ringVertex = BABYLON.Vector3.Zero();
  26711. var ringNormal = BABYLON.Vector3.Zero();
  26712. var ringFirstVertex = BABYLON.Vector3.Zero();
  26713. var ringFirstNormal = BABYLON.Vector3.Zero();
  26714. var quadNormal = BABYLON.Vector3.Zero();
  26715. var Y = BABYLON.Axis.Y;
  26716. // positions, normals, uvs
  26717. var i;
  26718. var j;
  26719. var r;
  26720. var ringIdx = 1;
  26721. var s = 1; // surface index
  26722. var cs = 0;
  26723. var v = 0;
  26724. for (i = 0; i <= subdivisions; i++) {
  26725. h = i / subdivisions;
  26726. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26727. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  26728. for (r = 0; r < ringIdx; r++) {
  26729. if (hasRings) {
  26730. s += r;
  26731. }
  26732. if (enclose) {
  26733. s += 2 * r;
  26734. }
  26735. for (j = 0; j <= tessellation; j++) {
  26736. angle = j * angle_step;
  26737. // position
  26738. ringVertex.x = Math.cos(-angle) * radius;
  26739. ringVertex.y = -height / 2 + h * height;
  26740. ringVertex.z = Math.sin(-angle) * radius;
  26741. // normal
  26742. if (diameterTop === 0 && i === subdivisions) {
  26743. // if no top cap, reuse former normals
  26744. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26745. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26746. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26747. }
  26748. else {
  26749. ringNormal.x = ringVertex.x;
  26750. ringNormal.z = ringVertex.z;
  26751. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26752. ringNormal.normalize();
  26753. }
  26754. // keep first ring vertex values for enclose
  26755. if (j === 0) {
  26756. ringFirstVertex.copyFrom(ringVertex);
  26757. ringFirstNormal.copyFrom(ringNormal);
  26758. }
  26759. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26760. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26761. if (hasRings) {
  26762. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  26763. }
  26764. else {
  26765. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  26766. }
  26767. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  26768. if (faceColors) {
  26769. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  26770. }
  26771. }
  26772. // if enclose, add four vertices and their dedicated normals
  26773. if (arc !== 1 && enclose) {
  26774. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26775. positions.push(0, ringVertex.y, 0);
  26776. positions.push(0, ringVertex.y, 0);
  26777. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  26778. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  26779. quadNormal.normalize();
  26780. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26781. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  26782. quadNormal.normalize();
  26783. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26784. if (hasRings) {
  26785. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  26786. }
  26787. else {
  26788. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  26789. }
  26790. uvs.push(faceUV[s + 1].x, v);
  26791. uvs.push(faceUV[s + 1].z, v);
  26792. if (hasRings) {
  26793. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  26794. }
  26795. else {
  26796. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  26797. }
  26798. uvs.push(faceUV[s + 2].x, v);
  26799. uvs.push(faceUV[s + 2].z, v);
  26800. if (faceColors) {
  26801. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26802. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26803. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26804. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26805. }
  26806. }
  26807. if (cs !== s) {
  26808. cs = s;
  26809. }
  26810. }
  26811. }
  26812. // indices
  26813. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  26814. var s;
  26815. i = 0;
  26816. for (s = 0; s < subdivisions; s++) {
  26817. for (j = 0; j < tessellation; j++) {
  26818. var i0 = i * (e + 1) + j;
  26819. var i1 = (i + 1) * (e + 1) + j;
  26820. var i2 = i * (e + 1) + (j + 1);
  26821. var i3 = (i + 1) * (e + 1) + (j + 1);
  26822. indices.push(i0, i1, i2);
  26823. indices.push(i3, i2, i1);
  26824. }
  26825. if (arc !== 1 && enclose) {
  26826. indices.push(i0 + 2, i1 + 2, i2 + 2);
  26827. indices.push(i3 + 2, i2 + 2, i1 + 2);
  26828. indices.push(i0 + 4, i1 + 4, i2 + 4);
  26829. indices.push(i3 + 4, i2 + 4, i1 + 4);
  26830. }
  26831. i = (hasRings) ? (i + 2) : (i + 1);
  26832. }
  26833. // Caps
  26834. var createCylinderCap = function (isTop) {
  26835. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26836. if (radius === 0) {
  26837. return;
  26838. }
  26839. // Cap positions, normals & uvs
  26840. var angle;
  26841. var circleVector;
  26842. var i;
  26843. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  26844. var c;
  26845. if (faceColors) {
  26846. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  26847. }
  26848. // cap center
  26849. var vbase = positions.length / 3;
  26850. var offset = isTop ? height / 2 : -height / 2;
  26851. var center = new BABYLON.Vector3(0, offset, 0);
  26852. positions.push(center.x, center.y, center.z);
  26853. normals.push(0, isTop ? 1 : -1, 0);
  26854. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  26855. if (faceColors) {
  26856. colors.push(c.r, c.g, c.b, c.a);
  26857. }
  26858. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26859. for (i = 0; i <= tessellation; i++) {
  26860. angle = Math.PI * 2 * i * arc / tessellation;
  26861. var cos = Math.cos(-angle);
  26862. var sin = Math.sin(-angle);
  26863. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  26864. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  26865. positions.push(circleVector.x, circleVector.y, circleVector.z);
  26866. normals.push(0, isTop ? 1 : -1, 0);
  26867. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  26868. if (faceColors) {
  26869. colors.push(c.r, c.g, c.b, c.a);
  26870. }
  26871. }
  26872. // Cap indices
  26873. for (i = 0; i < tessellation; i++) {
  26874. if (!isTop) {
  26875. indices.push(vbase);
  26876. indices.push(vbase + (i + 1));
  26877. indices.push(vbase + (i + 2));
  26878. }
  26879. else {
  26880. indices.push(vbase);
  26881. indices.push(vbase + (i + 2));
  26882. indices.push(vbase + (i + 1));
  26883. }
  26884. }
  26885. };
  26886. // add caps to geometry
  26887. createCylinderCap(false);
  26888. createCylinderCap(true);
  26889. // Sides
  26890. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26891. var vertexData = new VertexData();
  26892. vertexData.indices = indices;
  26893. vertexData.positions = positions;
  26894. vertexData.normals = normals;
  26895. vertexData.uvs = uvs;
  26896. if (faceColors) {
  26897. vertexData.colors = colors;
  26898. }
  26899. return vertexData;
  26900. };
  26901. VertexData.CreateTorus = function (options) {
  26902. var indices = [];
  26903. var positions = [];
  26904. var normals = [];
  26905. var uvs = [];
  26906. var diameter = options.diameter || 1;
  26907. var thickness = options.thickness || 0.5;
  26908. var tessellation = options.tessellation || 16;
  26909. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26910. var stride = tessellation + 1;
  26911. for (var i = 0; i <= tessellation; i++) {
  26912. var u = i / tessellation;
  26913. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26914. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26915. for (var j = 0; j <= tessellation; j++) {
  26916. var v = 1 - j / tessellation;
  26917. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26918. var dx = Math.cos(innerAngle);
  26919. var dy = Math.sin(innerAngle);
  26920. // Create a vertex.
  26921. var normal = new BABYLON.Vector3(dx, dy, 0);
  26922. var position = normal.scale(thickness / 2);
  26923. var textureCoordinate = new BABYLON.Vector2(u, v);
  26924. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26925. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26926. positions.push(position.x, position.y, position.z);
  26927. normals.push(normal.x, normal.y, normal.z);
  26928. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26929. // And create indices for two triangles.
  26930. var nextI = (i + 1) % stride;
  26931. var nextJ = (j + 1) % stride;
  26932. indices.push(i * stride + j);
  26933. indices.push(i * stride + nextJ);
  26934. indices.push(nextI * stride + j);
  26935. indices.push(i * stride + nextJ);
  26936. indices.push(nextI * stride + nextJ);
  26937. indices.push(nextI * stride + j);
  26938. }
  26939. }
  26940. // Sides
  26941. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26942. // Result
  26943. var vertexData = new VertexData();
  26944. vertexData.indices = indices;
  26945. vertexData.positions = positions;
  26946. vertexData.normals = normals;
  26947. vertexData.uvs = uvs;
  26948. return vertexData;
  26949. };
  26950. VertexData.CreateLineSystem = function (options) {
  26951. var indices = [];
  26952. var positions = [];
  26953. var lines = options.lines;
  26954. var idx = 0;
  26955. for (var l = 0; l < lines.length; l++) {
  26956. var points = lines[l];
  26957. for (var index = 0; index < points.length; index++) {
  26958. positions.push(points[index].x, points[index].y, points[index].z);
  26959. if (index > 0) {
  26960. indices.push(idx - 1);
  26961. indices.push(idx);
  26962. }
  26963. idx++;
  26964. }
  26965. }
  26966. var vertexData = new VertexData();
  26967. vertexData.indices = indices;
  26968. vertexData.positions = positions;
  26969. return vertexData;
  26970. };
  26971. VertexData.CreateDashedLines = function (options) {
  26972. var dashSize = options.dashSize || 3;
  26973. var gapSize = options.gapSize || 1;
  26974. var dashNb = options.dashNb || 200;
  26975. var points = options.points;
  26976. var positions = new Array();
  26977. var indices = new Array();
  26978. var curvect = BABYLON.Vector3.Zero();
  26979. var lg = 0;
  26980. var nb = 0;
  26981. var shft = 0;
  26982. var dashshft = 0;
  26983. var curshft = 0;
  26984. var idx = 0;
  26985. var i = 0;
  26986. for (i = 0; i < points.length - 1; i++) {
  26987. points[i + 1].subtractToRef(points[i], curvect);
  26988. lg += curvect.length();
  26989. }
  26990. shft = lg / dashNb;
  26991. dashshft = dashSize * shft / (dashSize + gapSize);
  26992. for (i = 0; i < points.length - 1; i++) {
  26993. points[i + 1].subtractToRef(points[i], curvect);
  26994. nb = Math.floor(curvect.length() / shft);
  26995. curvect.normalize();
  26996. for (var j = 0; j < nb; j++) {
  26997. curshft = shft * j;
  26998. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26999. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27000. indices.push(idx, idx + 1);
  27001. idx += 2;
  27002. }
  27003. }
  27004. // Result
  27005. var vertexData = new VertexData();
  27006. vertexData.positions = positions;
  27007. vertexData.indices = indices;
  27008. return vertexData;
  27009. };
  27010. VertexData.CreateGround = function (options) {
  27011. var indices = [];
  27012. var positions = [];
  27013. var normals = [];
  27014. var uvs = [];
  27015. var row, col;
  27016. var width = options.width || 1;
  27017. var height = options.height || 1;
  27018. var subdivisions = options.subdivisions || 1;
  27019. for (row = 0; row <= subdivisions; row++) {
  27020. for (col = 0; col <= subdivisions; col++) {
  27021. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  27022. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27023. positions.push(position.x, position.y, position.z);
  27024. normals.push(normal.x, normal.y, normal.z);
  27025. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  27026. }
  27027. }
  27028. for (row = 0; row < subdivisions; row++) {
  27029. for (col = 0; col < subdivisions; col++) {
  27030. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27031. indices.push(col + 1 + row * (subdivisions + 1));
  27032. indices.push(col + row * (subdivisions + 1));
  27033. indices.push(col + (row + 1) * (subdivisions + 1));
  27034. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27035. indices.push(col + row * (subdivisions + 1));
  27036. }
  27037. }
  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.CreateTiledGround = function (options) {
  27047. var xmin = options.xmin;
  27048. var zmin = options.zmin;
  27049. var xmax = options.xmax;
  27050. var zmax = options.zmax;
  27051. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27052. var precision = options.precision || { w: 1, h: 1 };
  27053. var indices = [];
  27054. var positions = [];
  27055. var normals = [];
  27056. var uvs = [];
  27057. var row, col, tileRow, tileCol;
  27058. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  27059. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27060. precision.w = (precision.w < 1) ? 1 : precision.w;
  27061. precision.h = (precision.h < 1) ? 1 : precision.h;
  27062. var tileSize = {
  27063. 'w': (xmax - xmin) / subdivisions.w,
  27064. 'h': (zmax - zmin) / subdivisions.h
  27065. };
  27066. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27067. // Indices
  27068. var base = positions.length / 3;
  27069. var rowLength = precision.w + 1;
  27070. for (row = 0; row < precision.h; row++) {
  27071. for (col = 0; col < precision.w; col++) {
  27072. var square = [
  27073. base + col + row * rowLength,
  27074. base + (col + 1) + row * rowLength,
  27075. base + (col + 1) + (row + 1) * rowLength,
  27076. base + col + (row + 1) * rowLength
  27077. ];
  27078. indices.push(square[1]);
  27079. indices.push(square[2]);
  27080. indices.push(square[3]);
  27081. indices.push(square[0]);
  27082. indices.push(square[1]);
  27083. indices.push(square[3]);
  27084. }
  27085. }
  27086. // Position, normals and uvs
  27087. var position = BABYLON.Vector3.Zero();
  27088. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27089. for (row = 0; row <= precision.h; row++) {
  27090. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27091. for (col = 0; col <= precision.w; col++) {
  27092. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27093. position.y = 0;
  27094. positions.push(position.x, position.y, position.z);
  27095. normals.push(normal.x, normal.y, normal.z);
  27096. uvs.push(col / precision.w, row / precision.h);
  27097. }
  27098. }
  27099. }
  27100. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27101. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27102. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27103. }
  27104. }
  27105. // Result
  27106. var vertexData = new VertexData();
  27107. vertexData.indices = indices;
  27108. vertexData.positions = positions;
  27109. vertexData.normals = normals;
  27110. vertexData.uvs = uvs;
  27111. return vertexData;
  27112. };
  27113. VertexData.CreateGroundFromHeightMap = function (options) {
  27114. var indices = [];
  27115. var positions = [];
  27116. var normals = [];
  27117. var uvs = [];
  27118. var row, col;
  27119. // Vertices
  27120. for (row = 0; row <= options.subdivisions; row++) {
  27121. for (col = 0; col <= options.subdivisions; col++) {
  27122. 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));
  27123. // Compute height
  27124. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27125. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27126. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27127. var r = options.buffer[pos] / 255.0;
  27128. var g = options.buffer[pos + 1] / 255.0;
  27129. var b = options.buffer[pos + 2] / 255.0;
  27130. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27131. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27132. // Add vertex
  27133. positions.push(position.x, position.y, position.z);
  27134. normals.push(0, 0, 0);
  27135. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27136. }
  27137. }
  27138. // Indices
  27139. for (row = 0; row < options.subdivisions; row++) {
  27140. for (col = 0; col < options.subdivisions; col++) {
  27141. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27142. indices.push(col + 1 + row * (options.subdivisions + 1));
  27143. indices.push(col + row * (options.subdivisions + 1));
  27144. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27145. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27146. indices.push(col + row * (options.subdivisions + 1));
  27147. }
  27148. }
  27149. // Normals
  27150. VertexData.ComputeNormals(positions, indices, normals);
  27151. // Result
  27152. var vertexData = new VertexData();
  27153. vertexData.indices = indices;
  27154. vertexData.positions = positions;
  27155. vertexData.normals = normals;
  27156. vertexData.uvs = uvs;
  27157. return vertexData;
  27158. };
  27159. VertexData.CreatePlane = function (options) {
  27160. var indices = [];
  27161. var positions = [];
  27162. var normals = [];
  27163. var uvs = [];
  27164. var width = options.width || options.size || 1;
  27165. var height = options.height || options.size || 1;
  27166. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27167. // Vertices
  27168. var halfWidth = width / 2.0;
  27169. var halfHeight = height / 2.0;
  27170. positions.push(-halfWidth, -halfHeight, 0);
  27171. normals.push(0, 0, -1.0);
  27172. uvs.push(0.0, 0.0);
  27173. positions.push(halfWidth, -halfHeight, 0);
  27174. normals.push(0, 0, -1.0);
  27175. uvs.push(1.0, 0.0);
  27176. positions.push(halfWidth, halfHeight, 0);
  27177. normals.push(0, 0, -1.0);
  27178. uvs.push(1.0, 1.0);
  27179. positions.push(-halfWidth, halfHeight, 0);
  27180. normals.push(0, 0, -1.0);
  27181. uvs.push(0.0, 1.0);
  27182. // Indices
  27183. indices.push(0);
  27184. indices.push(1);
  27185. indices.push(2);
  27186. indices.push(0);
  27187. indices.push(2);
  27188. indices.push(3);
  27189. // Sides
  27190. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27191. // Result
  27192. var vertexData = new VertexData();
  27193. vertexData.indices = indices;
  27194. vertexData.positions = positions;
  27195. vertexData.normals = normals;
  27196. vertexData.uvs = uvs;
  27197. return vertexData;
  27198. };
  27199. VertexData.CreateDisc = function (options) {
  27200. var positions = [];
  27201. var indices = [];
  27202. var normals = [];
  27203. var uvs = [];
  27204. var radius = options.radius || 0.5;
  27205. var tessellation = options.tessellation || 64;
  27206. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27207. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27208. // positions and uvs
  27209. positions.push(0, 0, 0); // disc center first
  27210. uvs.push(0.5, 0.5);
  27211. var theta = Math.PI * 2 * arc;
  27212. var step = theta / tessellation;
  27213. for (var a = 0; a < theta; a += step) {
  27214. var x = Math.cos(a);
  27215. var y = Math.sin(a);
  27216. var u = (x + 1) / 2;
  27217. var v = (1 - y) / 2;
  27218. positions.push(radius * x, radius * y, 0);
  27219. uvs.push(u, v);
  27220. }
  27221. if (arc === 1) {
  27222. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27223. uvs.push(uvs[2], uvs[3]);
  27224. }
  27225. //indices
  27226. var vertexNb = positions.length / 3;
  27227. for (var i = 1; i < vertexNb - 1; i++) {
  27228. indices.push(i + 1, 0, i);
  27229. }
  27230. // result
  27231. VertexData.ComputeNormals(positions, indices, normals);
  27232. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27233. var vertexData = new VertexData();
  27234. vertexData.indices = indices;
  27235. vertexData.positions = positions;
  27236. vertexData.normals = normals;
  27237. vertexData.uvs = uvs;
  27238. return vertexData;
  27239. };
  27240. VertexData.CreateIcoSphere = function (options) {
  27241. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27242. var radius = options.radius || 1;
  27243. var flat = (options.flat === undefined) ? true : options.flat;
  27244. var subdivisions = options.subdivisions || 4;
  27245. var radiusX = options.radiusX || radius;
  27246. var radiusY = options.radiusY || radius;
  27247. var radiusZ = options.radiusZ || radius;
  27248. var t = (1 + Math.sqrt(5)) / 2;
  27249. // 12 vertex x,y,z
  27250. var ico_vertices = [
  27251. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27252. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27253. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27254. ];
  27255. // index of 3 vertex makes a face of icopshere
  27256. var ico_indices = [
  27257. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27258. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27259. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27260. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27261. ];
  27262. // vertex for uv have aliased position, not for UV
  27263. var vertices_unalias_id = [
  27264. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27265. // vertex alias
  27266. 0,
  27267. 2,
  27268. 3,
  27269. 3,
  27270. 3,
  27271. 4,
  27272. 7,
  27273. 8,
  27274. 9,
  27275. 9,
  27276. 10,
  27277. 11 // 23: B + 12
  27278. ];
  27279. // uv as integer step (not pixels !)
  27280. var ico_vertexuv = [
  27281. 5, 1, 3, 1, 6, 4, 0, 0,
  27282. 5, 3, 4, 2, 2, 2, 4, 0,
  27283. 2, 0, 1, 1, 6, 0, 6, 2,
  27284. // vertex alias (for same vertex on different faces)
  27285. 0, 4,
  27286. 3, 3,
  27287. 4, 4,
  27288. 3, 1,
  27289. 4, 2,
  27290. 4, 4,
  27291. 0, 2,
  27292. 1, 1,
  27293. 2, 2,
  27294. 3, 3,
  27295. 1, 3,
  27296. 2, 4 // 23: B + 12
  27297. ];
  27298. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27299. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27300. // First island of uv mapping
  27301. // v = 4h 3+ 2
  27302. // v = 3h 9+ 4
  27303. // v = 2h 9+ 5 B
  27304. // v = 1h 9 1 0
  27305. // v = 0h 3 8 7 A
  27306. // u = 0 1 2 3 4 5 6 *a
  27307. // Second island of uv mapping
  27308. // v = 4h 0+ B+ 4+
  27309. // v = 3h A+ 2+
  27310. // v = 2h 7+ 6 3+
  27311. // v = 1h 8+ 3+
  27312. // v = 0h
  27313. // u = 0 1 2 3 4 5 6 *a
  27314. // Face layout on texture UV mapping
  27315. // ============
  27316. // \ 4 /\ 16 / ======
  27317. // \ / \ / /\ 11 /
  27318. // \/ 7 \/ / \ /
  27319. // ======= / 10 \/
  27320. // /\ 17 /\ =======
  27321. // / \ / \ \ 15 /\
  27322. // / 8 \/ 12 \ \ / \
  27323. // ============ \/ 6 \
  27324. // \ 18 /\ ============
  27325. // \ / \ \ 5 /\ 0 /
  27326. // \/ 13 \ \ / \ /
  27327. // ======= \/ 1 \/
  27328. // =============
  27329. // /\ 19 /\ 2 /\
  27330. // / \ / \ / \
  27331. // / 14 \/ 9 \/ 3 \
  27332. // ===================
  27333. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27334. var ustep = 138 / 1024;
  27335. var vstep = 239 / 1024;
  27336. var uoffset = 60 / 1024;
  27337. var voffset = 26 / 1024;
  27338. // Second island should have margin, not to touch the first island
  27339. // avoid any borderline artefact in pixel rounding
  27340. var island_u_offset = -40 / 1024;
  27341. var island_v_offset = +20 / 1024;
  27342. // face is either island 0 or 1 :
  27343. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27344. var island = [
  27345. 0, 0, 0, 0, 1,
  27346. 0, 0, 1, 1, 0,
  27347. 0, 0, 1, 1, 0,
  27348. 0, 1, 1, 1, 0 // 15 - 19
  27349. ];
  27350. var indices = [];
  27351. var positions = [];
  27352. var normals = [];
  27353. var uvs = [];
  27354. var current_indice = 0;
  27355. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27356. var face_vertex_pos = new Array(3);
  27357. var face_vertex_uv = new Array(3);
  27358. var v012;
  27359. for (v012 = 0; v012 < 3; v012++) {
  27360. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27361. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27362. }
  27363. // create all with normals
  27364. for (var face = 0; face < 20; face++) {
  27365. // 3 vertex per face
  27366. for (v012 = 0; v012 < 3; v012++) {
  27367. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27368. var v_id = ico_indices[3 * face + v012];
  27369. // vertex have 3D position (x,y,z)
  27370. 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]);
  27371. // Normalize to get normal, then scale to radius
  27372. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27373. // uv Coordinates from vertex ID
  27374. 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);
  27375. }
  27376. // Subdivide the face (interpolate pos, norm, uv)
  27377. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27378. // - norm is linear interpolation of vertex corner normal
  27379. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27380. // - uv is linear interpolation
  27381. //
  27382. // Topology is as below for sub-divide by 2
  27383. // vertex shown as v0,v1,v2
  27384. // interp index is i1 to progress in range [v0,v1[
  27385. // interp index is i2 to progress in range [v0,v2[
  27386. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27387. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27388. //
  27389. //
  27390. // i2 v2
  27391. // ^ ^
  27392. // / / \
  27393. // / / \
  27394. // / / \
  27395. // / / (0,1) \
  27396. // / #---------\
  27397. // / / \ (0,0)'/ \
  27398. // / / \ / \
  27399. // / / \ / \
  27400. // / / (0,0) \ / (1,0) \
  27401. // / #---------#---------\
  27402. // v0 v1
  27403. //
  27404. // --------------------> i1
  27405. //
  27406. // interp of (i1,i2):
  27407. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27408. // along i1 : lerp(x0,x1, i1/(S-i2))
  27409. //
  27410. // centroid of triangle is needed to get help normal computation
  27411. // (c1,c2) are used for centroid location
  27412. var interp_vertex = function (i1, i2, c1, c2) {
  27413. // vertex is interpolated from
  27414. // - face_vertex_pos[0..2]
  27415. // - face_vertex_uv[0..2]
  27416. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27417. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27418. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27419. pos_interp.normalize();
  27420. var vertex_normal;
  27421. if (flat) {
  27422. // in flat mode, recalculate normal as face centroid normal
  27423. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27424. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27425. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27426. }
  27427. else {
  27428. // in smooth mode, recalculate normal from each single vertex position
  27429. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27430. }
  27431. // Vertex normal need correction due to X,Y,Z radius scaling
  27432. vertex_normal.x /= radiusX;
  27433. vertex_normal.y /= radiusY;
  27434. vertex_normal.z /= radiusZ;
  27435. vertex_normal.normalize();
  27436. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27437. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27438. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27439. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27440. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27441. uvs.push(uv_interp.x, uv_interp.y);
  27442. // push each vertex has member of a face
  27443. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27444. indices.push(current_indice);
  27445. current_indice++;
  27446. };
  27447. for (var i2 = 0; i2 < subdivisions; i2++) {
  27448. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27449. // face : (i1,i2) for /\ :
  27450. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27451. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27452. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27453. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27454. if (i1 + i2 + 1 < subdivisions) {
  27455. // face : (i1,i2)' for \/ :
  27456. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27457. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27458. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27459. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27460. }
  27461. }
  27462. }
  27463. }
  27464. // Sides
  27465. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27466. // Result
  27467. var vertexData = new VertexData();
  27468. vertexData.indices = indices;
  27469. vertexData.positions = positions;
  27470. vertexData.normals = normals;
  27471. vertexData.uvs = uvs;
  27472. return vertexData;
  27473. };
  27474. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27475. VertexData.CreatePolyhedron = function (options) {
  27476. // provided polyhedron types :
  27477. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27478. // 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)
  27479. var polyhedra = [];
  27480. 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]] };
  27481. 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]] };
  27482. polyhedra[2] = {
  27483. 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]],
  27484. 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]]
  27485. };
  27486. polyhedra[3] = {
  27487. 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]],
  27488. 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]]
  27489. };
  27490. polyhedra[4] = {
  27491. 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]],
  27492. 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]]
  27493. };
  27494. 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]] };
  27495. 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]] };
  27496. 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]] };
  27497. 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]] };
  27498. 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]] };
  27499. 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]] };
  27500. 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]] };
  27501. 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]] };
  27502. 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]] };
  27503. polyhedra[14] = {
  27504. 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]],
  27505. 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]]
  27506. };
  27507. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27508. var size = options.size;
  27509. var sizeX = options.sizeX || size || 1;
  27510. var sizeY = options.sizeY || size || 1;
  27511. var sizeZ = options.sizeZ || size || 1;
  27512. var data = options.custom || polyhedra[type];
  27513. var nbfaces = data.face.length;
  27514. var faceUV = options.faceUV || new Array(nbfaces);
  27515. var faceColors = options.faceColors;
  27516. var flat = (options.flat === undefined) ? true : options.flat;
  27517. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27518. var positions = [];
  27519. var indices = [];
  27520. var normals = [];
  27521. var uvs = [];
  27522. var colors = [];
  27523. var index = 0;
  27524. var faceIdx = 0; // face cursor in the array "indexes"
  27525. var indexes = [];
  27526. var i = 0;
  27527. var f = 0;
  27528. var u, v, ang, x, y, tmp;
  27529. // default face colors and UV if undefined
  27530. if (flat) {
  27531. for (f = 0; f < nbfaces; f++) {
  27532. if (faceColors && faceColors[f] === undefined) {
  27533. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27534. }
  27535. if (faceUV && faceUV[f] === undefined) {
  27536. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27537. }
  27538. }
  27539. }
  27540. if (!flat) {
  27541. for (i = 0; i < data.vertex.length; i++) {
  27542. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27543. uvs.push(0, 0);
  27544. }
  27545. for (f = 0; f < nbfaces; f++) {
  27546. for (i = 0; i < data.face[f].length - 2; i++) {
  27547. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27548. }
  27549. }
  27550. }
  27551. else {
  27552. for (f = 0; f < nbfaces; f++) {
  27553. var fl = data.face[f].length; // number of vertices of the current face
  27554. ang = 2 * Math.PI / fl;
  27555. x = 0.5 * Math.tan(ang / 2);
  27556. y = 0.5;
  27557. // positions, uvs, colors
  27558. for (i = 0; i < fl; i++) {
  27559. // positions
  27560. 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);
  27561. indexes.push(index);
  27562. index++;
  27563. // uvs
  27564. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27565. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27566. uvs.push(u, v);
  27567. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27568. y = x * Math.sin(ang) + y * Math.cos(ang);
  27569. x = tmp;
  27570. // colors
  27571. if (faceColors) {
  27572. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27573. }
  27574. }
  27575. // indices from indexes
  27576. for (i = 0; i < fl - 2; i++) {
  27577. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27578. }
  27579. faceIdx += fl;
  27580. }
  27581. }
  27582. VertexData.ComputeNormals(positions, indices, normals);
  27583. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27584. var vertexData = new VertexData();
  27585. vertexData.positions = positions;
  27586. vertexData.indices = indices;
  27587. vertexData.normals = normals;
  27588. vertexData.uvs = uvs;
  27589. if (faceColors && flat) {
  27590. vertexData.colors = colors;
  27591. }
  27592. return vertexData;
  27593. };
  27594. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27595. VertexData.CreateTorusKnot = function (options) {
  27596. var indices = [];
  27597. var positions = [];
  27598. var normals = [];
  27599. var uvs = [];
  27600. var radius = options.radius || 2;
  27601. var tube = options.tube || 0.5;
  27602. var radialSegments = options.radialSegments || 32;
  27603. var tubularSegments = options.tubularSegments || 32;
  27604. var p = options.p || 2;
  27605. var q = options.q || 3;
  27606. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27607. // Helper
  27608. var getPos = function (angle) {
  27609. var cu = Math.cos(angle);
  27610. var su = Math.sin(angle);
  27611. var quOverP = q / p * angle;
  27612. var cs = Math.cos(quOverP);
  27613. var tx = radius * (2 + cs) * 0.5 * cu;
  27614. var ty = radius * (2 + cs) * su * 0.5;
  27615. var tz = radius * Math.sin(quOverP) * 0.5;
  27616. return new BABYLON.Vector3(tx, ty, tz);
  27617. };
  27618. // Vertices
  27619. var i;
  27620. var j;
  27621. for (i = 0; i <= radialSegments; i++) {
  27622. var modI = i % radialSegments;
  27623. var u = modI / radialSegments * 2 * p * Math.PI;
  27624. var p1 = getPos(u);
  27625. var p2 = getPos(u + 0.01);
  27626. var tang = p2.subtract(p1);
  27627. var n = p2.add(p1);
  27628. var bitan = BABYLON.Vector3.Cross(tang, n);
  27629. n = BABYLON.Vector3.Cross(bitan, tang);
  27630. bitan.normalize();
  27631. n.normalize();
  27632. for (j = 0; j < tubularSegments; j++) {
  27633. var modJ = j % tubularSegments;
  27634. var v = modJ / tubularSegments * 2 * Math.PI;
  27635. var cx = -tube * Math.cos(v);
  27636. var cy = tube * Math.sin(v);
  27637. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27638. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27639. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27640. uvs.push(i / radialSegments);
  27641. uvs.push(j / tubularSegments);
  27642. }
  27643. }
  27644. for (i = 0; i < radialSegments; i++) {
  27645. for (j = 0; j < tubularSegments; j++) {
  27646. var jNext = (j + 1) % tubularSegments;
  27647. var a = i * tubularSegments + j;
  27648. var b = (i + 1) * tubularSegments + j;
  27649. var c = (i + 1) * tubularSegments + jNext;
  27650. var d = i * tubularSegments + jNext;
  27651. indices.push(d);
  27652. indices.push(b);
  27653. indices.push(a);
  27654. indices.push(d);
  27655. indices.push(c);
  27656. indices.push(b);
  27657. }
  27658. }
  27659. // Normals
  27660. VertexData.ComputeNormals(positions, indices, normals);
  27661. // Sides
  27662. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27663. // Result
  27664. var vertexData = new VertexData();
  27665. vertexData.indices = indices;
  27666. vertexData.positions = positions;
  27667. vertexData.normals = normals;
  27668. vertexData.uvs = uvs;
  27669. return vertexData;
  27670. };
  27671. // Tools
  27672. /**
  27673. * @param {any} - positions (number[] or Float32Array)
  27674. * @param {any} - indices (number[] or Uint16Array)
  27675. * @param {any} - normals (number[] or Float32Array)
  27676. */
  27677. VertexData.ComputeNormals = function (positions, indices, normals) {
  27678. var index = 0;
  27679. var p1p2x = 0.0;
  27680. var p1p2y = 0.0;
  27681. var p1p2z = 0.0;
  27682. var p3p2x = 0.0;
  27683. var p3p2y = 0.0;
  27684. var p3p2z = 0.0;
  27685. var faceNormalx = 0.0;
  27686. var faceNormaly = 0.0;
  27687. var faceNormalz = 0.0;
  27688. var length = 0.0;
  27689. var i1 = 0;
  27690. var i2 = 0;
  27691. var i3 = 0;
  27692. for (index = 0; index < positions.length; index++) {
  27693. normals[index] = 0.0;
  27694. }
  27695. // indice triplet = 1 face
  27696. var nbFaces = indices.length / 3;
  27697. for (index = 0; index < nbFaces; index++) {
  27698. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  27699. i2 = indices[index * 3 + 1];
  27700. i3 = indices[index * 3 + 2];
  27701. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  27702. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27703. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27704. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  27705. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27706. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27707. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  27708. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  27709. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  27710. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27711. length = (length === 0) ? 1.0 : length;
  27712. faceNormalx /= length; // normalize this normal
  27713. faceNormaly /= length;
  27714. faceNormalz /= length;
  27715. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  27716. normals[i1 * 3 + 1] += faceNormaly;
  27717. normals[i1 * 3 + 2] += faceNormalz;
  27718. normals[i2 * 3] += faceNormalx;
  27719. normals[i2 * 3 + 1] += faceNormaly;
  27720. normals[i2 * 3 + 2] += faceNormalz;
  27721. normals[i3 * 3] += faceNormalx;
  27722. normals[i3 * 3 + 1] += faceNormaly;
  27723. normals[i3 * 3 + 2] += faceNormalz;
  27724. }
  27725. // last normalization of each normal
  27726. for (index = 0; index < normals.length / 3; index++) {
  27727. faceNormalx = normals[index * 3];
  27728. faceNormaly = normals[index * 3 + 1];
  27729. faceNormalz = normals[index * 3 + 2];
  27730. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27731. length = (length === 0) ? 1.0 : length;
  27732. faceNormalx /= length;
  27733. faceNormaly /= length;
  27734. faceNormalz /= length;
  27735. normals[index * 3] = faceNormalx;
  27736. normals[index * 3 + 1] = faceNormaly;
  27737. normals[index * 3 + 2] = faceNormalz;
  27738. }
  27739. };
  27740. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27741. var li = indices.length;
  27742. var ln = normals.length;
  27743. var i;
  27744. var n;
  27745. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27746. switch (sideOrientation) {
  27747. case BABYLON.Mesh.FRONTSIDE:
  27748. // nothing changed
  27749. break;
  27750. case BABYLON.Mesh.BACKSIDE:
  27751. var tmp;
  27752. // indices
  27753. for (i = 0; i < li; i += 3) {
  27754. tmp = indices[i];
  27755. indices[i] = indices[i + 2];
  27756. indices[i + 2] = tmp;
  27757. }
  27758. // normals
  27759. for (n = 0; n < ln; n++) {
  27760. normals[n] = -normals[n];
  27761. }
  27762. break;
  27763. case BABYLON.Mesh.DOUBLESIDE:
  27764. // positions
  27765. var lp = positions.length;
  27766. var l = lp / 3;
  27767. for (var p = 0; p < lp; p++) {
  27768. positions[lp + p] = positions[p];
  27769. }
  27770. // indices
  27771. for (i = 0; i < li; i += 3) {
  27772. indices[i + li] = indices[i + 2] + l;
  27773. indices[i + 1 + li] = indices[i + 1] + l;
  27774. indices[i + 2 + li] = indices[i] + l;
  27775. }
  27776. // normals
  27777. for (n = 0; n < ln; n++) {
  27778. normals[ln + n] = -normals[n];
  27779. }
  27780. // uvs
  27781. var lu = uvs.length;
  27782. for (var u = 0; u < lu; u++) {
  27783. uvs[u + lu] = uvs[u];
  27784. }
  27785. break;
  27786. }
  27787. };
  27788. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27789. var vertexData = new VertexData();
  27790. // positions
  27791. var positions = parsedVertexData.positions;
  27792. if (positions) {
  27793. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27794. }
  27795. // normals
  27796. var normals = parsedVertexData.normals;
  27797. if (normals) {
  27798. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27799. }
  27800. // uvs
  27801. var uvs = parsedVertexData.uvs;
  27802. if (uvs) {
  27803. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27804. }
  27805. // uv2s
  27806. var uv2s = parsedVertexData.uv2s;
  27807. if (uv2s) {
  27808. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27809. }
  27810. // uv3s
  27811. var uv3s = parsedVertexData.uv3s;
  27812. if (uv3s) {
  27813. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27814. }
  27815. // uv4s
  27816. var uv4s = parsedVertexData.uv4s;
  27817. if (uv4s) {
  27818. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27819. }
  27820. // uv5s
  27821. var uv5s = parsedVertexData.uv5s;
  27822. if (uv5s) {
  27823. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27824. }
  27825. // uv6s
  27826. var uv6s = parsedVertexData.uv6s;
  27827. if (uv6s) {
  27828. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27829. }
  27830. // colors
  27831. var colors = parsedVertexData.colors;
  27832. if (colors) {
  27833. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27834. }
  27835. // matricesIndices
  27836. var matricesIndices = parsedVertexData.matricesIndices;
  27837. if (matricesIndices) {
  27838. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27839. }
  27840. // matricesWeights
  27841. var matricesWeights = parsedVertexData.matricesWeights;
  27842. if (matricesWeights) {
  27843. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27844. }
  27845. // indices
  27846. var indices = parsedVertexData.indices;
  27847. if (indices) {
  27848. vertexData.indices = indices;
  27849. }
  27850. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27851. };
  27852. return VertexData;
  27853. })();
  27854. BABYLON.VertexData = VertexData;
  27855. })(BABYLON || (BABYLON = {}));
  27856. var BABYLON;
  27857. (function (BABYLON) {
  27858. var Tags = (function () {
  27859. function Tags() {
  27860. }
  27861. Tags.EnableFor = function (obj) {
  27862. obj._tags = obj._tags || {};
  27863. obj.hasTags = function () {
  27864. return Tags.HasTags(obj);
  27865. };
  27866. obj.addTags = function (tagsString) {
  27867. return Tags.AddTagsTo(obj, tagsString);
  27868. };
  27869. obj.removeTags = function (tagsString) {
  27870. return Tags.RemoveTagsFrom(obj, tagsString);
  27871. };
  27872. obj.matchesTagsQuery = function (tagsQuery) {
  27873. return Tags.MatchesQuery(obj, tagsQuery);
  27874. };
  27875. };
  27876. Tags.DisableFor = function (obj) {
  27877. delete obj._tags;
  27878. delete obj.hasTags;
  27879. delete obj.addTags;
  27880. delete obj.removeTags;
  27881. delete obj.matchesTagsQuery;
  27882. };
  27883. Tags.HasTags = function (obj) {
  27884. if (!obj._tags) {
  27885. return false;
  27886. }
  27887. return !BABYLON.Tools.IsEmpty(obj._tags);
  27888. };
  27889. Tags.GetTags = function (obj, asString) {
  27890. if (asString === void 0) { asString = true; }
  27891. if (!obj._tags) {
  27892. return null;
  27893. }
  27894. if (asString) {
  27895. var tagsArray = [];
  27896. for (var tag in obj._tags) {
  27897. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  27898. tagsArray.push(tag);
  27899. }
  27900. }
  27901. return tagsArray.join(" ");
  27902. }
  27903. else {
  27904. return obj._tags;
  27905. }
  27906. };
  27907. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27908. // a tag cannot start with '||', '&&', and '!'
  27909. // it cannot contain whitespaces
  27910. Tags.AddTagsTo = function (obj, tagsString) {
  27911. if (!tagsString) {
  27912. return;
  27913. }
  27914. if (typeof tagsString !== "string") {
  27915. return;
  27916. }
  27917. var tags = tagsString.split(" ");
  27918. for (var t in tags) {
  27919. Tags._AddTagTo(obj, tags[t]);
  27920. }
  27921. };
  27922. Tags._AddTagTo = function (obj, tag) {
  27923. tag = tag.trim();
  27924. if (tag === "" || tag === "true" || tag === "false") {
  27925. return;
  27926. }
  27927. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27928. return;
  27929. }
  27930. Tags.EnableFor(obj);
  27931. obj._tags[tag] = true;
  27932. };
  27933. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27934. if (!Tags.HasTags(obj)) {
  27935. return;
  27936. }
  27937. var tags = tagsString.split(" ");
  27938. for (var t in tags) {
  27939. Tags._RemoveTagFrom(obj, tags[t]);
  27940. }
  27941. };
  27942. Tags._RemoveTagFrom = function (obj, tag) {
  27943. delete obj._tags[tag];
  27944. };
  27945. Tags.MatchesQuery = function (obj, tagsQuery) {
  27946. if (tagsQuery === undefined) {
  27947. return true;
  27948. }
  27949. if (tagsQuery === "") {
  27950. return Tags.HasTags(obj);
  27951. }
  27952. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27953. };
  27954. return Tags;
  27955. })();
  27956. BABYLON.Tags = Tags;
  27957. })(BABYLON || (BABYLON = {}));
  27958. var BABYLON;
  27959. (function (BABYLON) {
  27960. var Internals;
  27961. (function (Internals) {
  27962. var AndOrNotEvaluator = (function () {
  27963. function AndOrNotEvaluator() {
  27964. }
  27965. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27966. if (!query.match(/\([^\(\)]*\)/g)) {
  27967. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27968. }
  27969. else {
  27970. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27971. // remove parenthesis
  27972. r = r.slice(1, r.length - 1);
  27973. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27974. });
  27975. }
  27976. if (query === "true") {
  27977. return true;
  27978. }
  27979. if (query === "false") {
  27980. return false;
  27981. }
  27982. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27983. };
  27984. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27985. evaluateCallback = evaluateCallback || (function (r) {
  27986. return r === "true" ? true : false;
  27987. });
  27988. var result;
  27989. var or = parenthesisContent.split("||");
  27990. for (var i in or) {
  27991. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27992. var and = ori.split("&&");
  27993. if (and.length > 1) {
  27994. for (var j = 0; j < and.length; ++j) {
  27995. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27996. if (andj !== "true" && andj !== "false") {
  27997. if (andj[0] === "!") {
  27998. result = !evaluateCallback(andj.substring(1));
  27999. }
  28000. else {
  28001. result = evaluateCallback(andj);
  28002. }
  28003. }
  28004. else {
  28005. result = andj === "true" ? true : false;
  28006. }
  28007. if (!result) {
  28008. ori = "false";
  28009. break;
  28010. }
  28011. }
  28012. }
  28013. if (result || ori === "true") {
  28014. result = true;
  28015. break;
  28016. }
  28017. // result equals false (or undefined)
  28018. if (ori !== "true" && ori !== "false") {
  28019. if (ori[0] === "!") {
  28020. result = !evaluateCallback(ori.substring(1));
  28021. }
  28022. else {
  28023. result = evaluateCallback(ori);
  28024. }
  28025. }
  28026. else {
  28027. result = ori === "true" ? true : false;
  28028. }
  28029. }
  28030. // the whole parenthesis scope is replaced by 'true' or 'false'
  28031. return result ? "true" : "false";
  28032. };
  28033. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  28034. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  28035. // remove whitespaces
  28036. r = r.replace(/[\s]/g, function () { return ""; });
  28037. return r.length % 2 ? "!" : "";
  28038. });
  28039. booleanString = booleanString.trim();
  28040. if (booleanString === "!true") {
  28041. booleanString = "false";
  28042. }
  28043. else if (booleanString === "!false") {
  28044. booleanString = "true";
  28045. }
  28046. return booleanString;
  28047. };
  28048. return AndOrNotEvaluator;
  28049. })();
  28050. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  28051. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28052. })(BABYLON || (BABYLON = {}));
  28053. var BABYLON;
  28054. (function (BABYLON) {
  28055. var PostProcessRenderPass = (function () {
  28056. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  28057. this._enabled = true;
  28058. this._refCount = 0;
  28059. this._name = name;
  28060. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  28061. this.setRenderList(renderList);
  28062. this._renderTexture.onBeforeRender = beforeRender;
  28063. this._renderTexture.onAfterRender = afterRender;
  28064. this._scene = scene;
  28065. this._renderList = renderList;
  28066. }
  28067. // private
  28068. PostProcessRenderPass.prototype._incRefCount = function () {
  28069. if (this._refCount === 0) {
  28070. this._scene.customRenderTargets.push(this._renderTexture);
  28071. }
  28072. return ++this._refCount;
  28073. };
  28074. PostProcessRenderPass.prototype._decRefCount = function () {
  28075. this._refCount--;
  28076. if (this._refCount <= 0) {
  28077. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  28078. }
  28079. return this._refCount;
  28080. };
  28081. PostProcessRenderPass.prototype._update = function () {
  28082. this.setRenderList(this._renderList);
  28083. };
  28084. // public
  28085. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  28086. this._renderTexture.renderList = renderList;
  28087. };
  28088. PostProcessRenderPass.prototype.getRenderTexture = function () {
  28089. return this._renderTexture;
  28090. };
  28091. return PostProcessRenderPass;
  28092. })();
  28093. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  28094. })(BABYLON || (BABYLON = {}));
  28095. var BABYLON;
  28096. (function (BABYLON) {
  28097. var PostProcessRenderEffect = (function () {
  28098. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  28099. this._engine = engine;
  28100. this._name = name;
  28101. this._singleInstance = singleInstance || true;
  28102. this._getPostProcess = getPostProcess;
  28103. this._cameras = [];
  28104. this._indicesForCamera = [];
  28105. this._postProcesses = {};
  28106. this._renderPasses = {};
  28107. this._renderEffectAsPasses = {};
  28108. }
  28109. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  28110. get: function () {
  28111. for (var index in this._postProcesses) {
  28112. if (!this._postProcesses[index].isSupported) {
  28113. return false;
  28114. }
  28115. }
  28116. return true;
  28117. },
  28118. enumerable: true,
  28119. configurable: true
  28120. });
  28121. PostProcessRenderEffect.prototype._update = function () {
  28122. for (var renderPassName in this._renderPasses) {
  28123. this._renderPasses[renderPassName]._update();
  28124. }
  28125. };
  28126. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  28127. this._renderPasses[renderPass._name] = renderPass;
  28128. this._linkParameters();
  28129. };
  28130. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  28131. delete this._renderPasses[renderPass._name];
  28132. this._linkParameters();
  28133. };
  28134. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  28135. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  28136. this._linkParameters();
  28137. };
  28138. PostProcessRenderEffect.prototype.getPass = function (passName) {
  28139. for (var renderPassName in this._renderPasses) {
  28140. if (renderPassName === passName) {
  28141. return this._renderPasses[passName];
  28142. }
  28143. }
  28144. };
  28145. PostProcessRenderEffect.prototype.emptyPasses = function () {
  28146. this._renderPasses = {};
  28147. this._linkParameters();
  28148. };
  28149. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  28150. var cameraKey;
  28151. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28152. for (var i = 0; i < _cam.length; i++) {
  28153. var camera = _cam[i];
  28154. var cameraName = camera.name;
  28155. if (this._singleInstance) {
  28156. cameraKey = 0;
  28157. }
  28158. else {
  28159. cameraKey = cameraName;
  28160. }
  28161. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  28162. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  28163. if (!this._indicesForCamera[cameraName]) {
  28164. this._indicesForCamera[cameraName] = [];
  28165. }
  28166. this._indicesForCamera[cameraName].push(index);
  28167. if (this._cameras.indexOf(camera) === -1) {
  28168. this._cameras[cameraName] = camera;
  28169. }
  28170. for (var passName in this._renderPasses) {
  28171. this._renderPasses[passName]._incRefCount();
  28172. }
  28173. }
  28174. this._linkParameters();
  28175. };
  28176. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  28177. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28178. for (var i = 0; i < _cam.length; i++) {
  28179. var camera = _cam[i];
  28180. var cameraName = camera.name;
  28181. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  28182. var index = this._cameras.indexOf(cameraName);
  28183. this._indicesForCamera.splice(index, 1);
  28184. this._cameras.splice(index, 1);
  28185. for (var passName in this._renderPasses) {
  28186. this._renderPasses[passName]._decRefCount();
  28187. }
  28188. }
  28189. };
  28190. PostProcessRenderEffect.prototype._enable = function (cameras) {
  28191. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28192. for (var i = 0; i < _cam.length; i++) {
  28193. var camera = _cam[i];
  28194. var cameraName = camera.name;
  28195. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  28196. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  28197. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  28198. }
  28199. }
  28200. for (var passName in this._renderPasses) {
  28201. this._renderPasses[passName]._incRefCount();
  28202. }
  28203. }
  28204. };
  28205. PostProcessRenderEffect.prototype._disable = function (cameras) {
  28206. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28207. for (var i = 0; i < _cam.length; i++) {
  28208. var camera = _cam[i];
  28209. var cameraName = camera.Name;
  28210. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  28211. for (var passName in this._renderPasses) {
  28212. this._renderPasses[passName]._decRefCount();
  28213. }
  28214. }
  28215. };
  28216. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  28217. if (this._singleInstance) {
  28218. return this._postProcesses[0];
  28219. }
  28220. else {
  28221. return this._postProcesses[camera.name];
  28222. }
  28223. };
  28224. PostProcessRenderEffect.prototype._linkParameters = function () {
  28225. var _this = this;
  28226. for (var index in this._postProcesses) {
  28227. if (this.applyParameters) {
  28228. this.applyParameters(this._postProcesses[index]);
  28229. }
  28230. this._postProcesses[index].onBeforeRender = function (effect) {
  28231. _this._linkTextures(effect);
  28232. };
  28233. }
  28234. };
  28235. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  28236. for (var renderPassName in this._renderPasses) {
  28237. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  28238. }
  28239. for (var renderEffectName in this._renderEffectAsPasses) {
  28240. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  28241. }
  28242. };
  28243. return PostProcessRenderEffect;
  28244. })();
  28245. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  28246. })(BABYLON || (BABYLON = {}));
  28247. var BABYLON;
  28248. (function (BABYLON) {
  28249. var PostProcessRenderPipeline = (function () {
  28250. function PostProcessRenderPipeline(engine, name) {
  28251. this._engine = engine;
  28252. this._name = name;
  28253. this._renderEffects = {};
  28254. this._renderEffectsForIsolatedPass = {};
  28255. this._cameras = [];
  28256. }
  28257. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  28258. get: function () {
  28259. for (var renderEffectName in this._renderEffects) {
  28260. if (!this._renderEffects[renderEffectName].isSupported) {
  28261. return false;
  28262. }
  28263. }
  28264. return true;
  28265. },
  28266. enumerable: true,
  28267. configurable: true
  28268. });
  28269. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  28270. this._renderEffects[renderEffect._name] = renderEffect;
  28271. };
  28272. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  28273. var renderEffects = this._renderEffects[renderEffectName];
  28274. if (!renderEffects) {
  28275. return;
  28276. }
  28277. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28278. };
  28279. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  28280. var renderEffects = this._renderEffects[renderEffectName];
  28281. if (!renderEffects) {
  28282. return;
  28283. }
  28284. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28285. };
  28286. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  28287. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28288. var indicesToDelete = [];
  28289. var i;
  28290. for (i = 0; i < _cam.length; i++) {
  28291. var camera = _cam[i];
  28292. var cameraName = camera.name;
  28293. if (this._cameras.indexOf(camera) === -1) {
  28294. this._cameras[cameraName] = camera;
  28295. }
  28296. else if (unique) {
  28297. indicesToDelete.push(i);
  28298. }
  28299. }
  28300. for (i = 0; i < indicesToDelete.length; i++) {
  28301. cameras.splice(indicesToDelete[i], 1);
  28302. }
  28303. for (var renderEffectName in this._renderEffects) {
  28304. this._renderEffects[renderEffectName]._attachCameras(_cam);
  28305. }
  28306. };
  28307. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  28308. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28309. for (var renderEffectName in this._renderEffects) {
  28310. this._renderEffects[renderEffectName]._detachCameras(_cam);
  28311. }
  28312. for (var i = 0; i < _cam.length; i++) {
  28313. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  28314. }
  28315. };
  28316. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  28317. var _this = this;
  28318. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28319. var pass = null;
  28320. var renderEffectName;
  28321. for (renderEffectName in this._renderEffects) {
  28322. pass = this._renderEffects[renderEffectName].getPass(passName);
  28323. if (pass != null) {
  28324. break;
  28325. }
  28326. }
  28327. if (pass === null) {
  28328. return;
  28329. }
  28330. for (renderEffectName in this._renderEffects) {
  28331. this._renderEffects[renderEffectName]._disable(_cam);
  28332. }
  28333. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  28334. for (var i = 0; i < _cam.length; i++) {
  28335. var camera = _cam[i];
  28336. var cameraName = camera.name;
  28337. 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); });
  28338. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  28339. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  28340. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  28341. }
  28342. };
  28343. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  28344. var _this = this;
  28345. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28346. for (var i = 0; i < _cam.length; i++) {
  28347. var camera = _cam[i];
  28348. var cameraName = camera.name;
  28349. 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); });
  28350. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  28351. }
  28352. for (var renderEffectName in this._renderEffects) {
  28353. this._renderEffects[renderEffectName]._enable(_cam);
  28354. }
  28355. };
  28356. PostProcessRenderPipeline.prototype._update = function () {
  28357. for (var renderEffectName in this._renderEffects) {
  28358. this._renderEffects[renderEffectName]._update();
  28359. }
  28360. for (var i = 0; i < this._cameras.length; i++) {
  28361. var cameraName = this._cameras[i].name;
  28362. if (this._renderEffectsForIsolatedPass[cameraName]) {
  28363. this._renderEffectsForIsolatedPass[cameraName]._update();
  28364. }
  28365. }
  28366. };
  28367. PostProcessRenderPipeline.prototype.dispose = function () {
  28368. // Must be implemented by children
  28369. };
  28370. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  28371. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  28372. return PostProcessRenderPipeline;
  28373. })();
  28374. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  28375. })(BABYLON || (BABYLON = {}));
  28376. var BABYLON;
  28377. (function (BABYLON) {
  28378. var PostProcessRenderPipelineManager = (function () {
  28379. function PostProcessRenderPipelineManager() {
  28380. this._renderPipelines = {};
  28381. }
  28382. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  28383. this._renderPipelines[renderPipeline._name] = renderPipeline;
  28384. };
  28385. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  28386. var renderPipeline = this._renderPipelines[renderPipelineName];
  28387. if (!renderPipeline) {
  28388. return;
  28389. }
  28390. renderPipeline._attachCameras(cameras, unique);
  28391. };
  28392. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  28393. var renderPipeline = this._renderPipelines[renderPipelineName];
  28394. if (!renderPipeline) {
  28395. return;
  28396. }
  28397. renderPipeline._detachCameras(cameras);
  28398. };
  28399. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28400. var renderPipeline = this._renderPipelines[renderPipelineName];
  28401. if (!renderPipeline) {
  28402. return;
  28403. }
  28404. renderPipeline._enableEffect(renderEffectName, cameras);
  28405. };
  28406. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28407. var renderPipeline = this._renderPipelines[renderPipelineName];
  28408. if (!renderPipeline) {
  28409. return;
  28410. }
  28411. renderPipeline._disableEffect(renderEffectName, cameras);
  28412. };
  28413. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  28414. var renderPipeline = this._renderPipelines[renderPipelineName];
  28415. if (!renderPipeline) {
  28416. return;
  28417. }
  28418. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  28419. };
  28420. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  28421. var renderPipeline = this._renderPipelines[renderPipelineName];
  28422. if (!renderPipeline) {
  28423. return;
  28424. }
  28425. renderPipeline._disableDisplayOnlyPass(cameras);
  28426. };
  28427. PostProcessRenderPipelineManager.prototype.update = function () {
  28428. for (var renderPipelineName in this._renderPipelines) {
  28429. var pipeline = this._renderPipelines[renderPipelineName];
  28430. if (!pipeline.isSupported) {
  28431. pipeline.dispose();
  28432. delete this._renderPipelines[renderPipelineName];
  28433. }
  28434. else {
  28435. pipeline._update();
  28436. }
  28437. }
  28438. };
  28439. return PostProcessRenderPipelineManager;
  28440. })();
  28441. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  28442. })(BABYLON || (BABYLON = {}));
  28443. var BABYLON;
  28444. (function (BABYLON) {
  28445. var BoundingBoxRenderer = (function () {
  28446. function BoundingBoxRenderer(scene) {
  28447. this.frontColor = new BABYLON.Color3(1, 1, 1);
  28448. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  28449. this.showBackLines = true;
  28450. this.renderList = new BABYLON.SmartArray(32);
  28451. this._scene = scene;
  28452. }
  28453. BoundingBoxRenderer.prototype._prepareRessources = function () {
  28454. if (this._colorShader) {
  28455. return;
  28456. }
  28457. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  28458. attributes: ["position"],
  28459. uniforms: ["worldViewProjection", "color"]
  28460. });
  28461. var engine = this._scene.getEngine();
  28462. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  28463. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  28464. 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]);
  28465. };
  28466. BoundingBoxRenderer.prototype.reset = function () {
  28467. this.renderList.reset();
  28468. };
  28469. BoundingBoxRenderer.prototype.render = function () {
  28470. if (this.renderList.length === 0) {
  28471. return;
  28472. }
  28473. this._prepareRessources();
  28474. if (!this._colorShader.isReady()) {
  28475. return;
  28476. }
  28477. var engine = this._scene.getEngine();
  28478. engine.setDepthWrite(false);
  28479. this._colorShader._preBind();
  28480. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  28481. var boundingBox = this.renderList.data[boundingBoxIndex];
  28482. var min = boundingBox.minimum;
  28483. var max = boundingBox.maximum;
  28484. var diff = max.subtract(min);
  28485. var median = min.add(diff.scale(0.5));
  28486. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  28487. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  28488. .multiply(boundingBox.getWorldMatrix());
  28489. // VBOs
  28490. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  28491. if (this.showBackLines) {
  28492. // Back
  28493. engine.setDepthFunctionToGreaterOrEqual();
  28494. this._scene.resetCachedMaterial();
  28495. this._colorShader.setColor4("color", this.backColor.toColor4());
  28496. this._colorShader.bind(worldMatrix);
  28497. // Draw order
  28498. engine.draw(false, 0, 24);
  28499. }
  28500. // Front
  28501. engine.setDepthFunctionToLess();
  28502. this._scene.resetCachedMaterial();
  28503. this._colorShader.setColor4("color", this.frontColor.toColor4());
  28504. this._colorShader.bind(worldMatrix);
  28505. // Draw order
  28506. engine.draw(false, 0, 24);
  28507. }
  28508. this._colorShader.unbind();
  28509. engine.setDepthFunctionToLessOrEqual();
  28510. engine.setDepthWrite(true);
  28511. };
  28512. BoundingBoxRenderer.prototype.dispose = function () {
  28513. if (!this._colorShader) {
  28514. return;
  28515. }
  28516. this._colorShader.dispose();
  28517. this._vb.dispose();
  28518. this._scene.getEngine()._releaseBuffer(this._ib);
  28519. };
  28520. return BoundingBoxRenderer;
  28521. })();
  28522. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  28523. })(BABYLON || (BABYLON = {}));
  28524. var BABYLON;
  28525. (function (BABYLON) {
  28526. var Condition = (function () {
  28527. function Condition(actionManager) {
  28528. this._actionManager = actionManager;
  28529. }
  28530. Condition.prototype.isValid = function () {
  28531. return true;
  28532. };
  28533. Condition.prototype._getProperty = function (propertyPath) {
  28534. return this._actionManager._getProperty(propertyPath);
  28535. };
  28536. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  28537. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28538. };
  28539. return Condition;
  28540. })();
  28541. BABYLON.Condition = Condition;
  28542. var ValueCondition = (function (_super) {
  28543. __extends(ValueCondition, _super);
  28544. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  28545. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  28546. _super.call(this, actionManager);
  28547. this.propertyPath = propertyPath;
  28548. this.value = value;
  28549. this.operator = operator;
  28550. this._target = this._getEffectiveTarget(target, this.propertyPath);
  28551. this._property = this._getProperty(this.propertyPath);
  28552. }
  28553. Object.defineProperty(ValueCondition, "IsEqual", {
  28554. get: function () {
  28555. return ValueCondition._IsEqual;
  28556. },
  28557. enumerable: true,
  28558. configurable: true
  28559. });
  28560. Object.defineProperty(ValueCondition, "IsDifferent", {
  28561. get: function () {
  28562. return ValueCondition._IsDifferent;
  28563. },
  28564. enumerable: true,
  28565. configurable: true
  28566. });
  28567. Object.defineProperty(ValueCondition, "IsGreater", {
  28568. get: function () {
  28569. return ValueCondition._IsGreater;
  28570. },
  28571. enumerable: true,
  28572. configurable: true
  28573. });
  28574. Object.defineProperty(ValueCondition, "IsLesser", {
  28575. get: function () {
  28576. return ValueCondition._IsLesser;
  28577. },
  28578. enumerable: true,
  28579. configurable: true
  28580. });
  28581. // Methods
  28582. ValueCondition.prototype.isValid = function () {
  28583. switch (this.operator) {
  28584. case ValueCondition.IsGreater:
  28585. return this._target[this._property] > this.value;
  28586. case ValueCondition.IsLesser:
  28587. return this._target[this._property] < this.value;
  28588. case ValueCondition.IsEqual:
  28589. case ValueCondition.IsDifferent:
  28590. var check;
  28591. if (this.value.equals) {
  28592. check = this.value.equals(this._target[this._property]);
  28593. }
  28594. else {
  28595. check = this.value === this._target[this._property];
  28596. }
  28597. return this.operator === ValueCondition.IsEqual ? check : !check;
  28598. }
  28599. return false;
  28600. };
  28601. // Statics
  28602. ValueCondition._IsEqual = 0;
  28603. ValueCondition._IsDifferent = 1;
  28604. ValueCondition._IsGreater = 2;
  28605. ValueCondition._IsLesser = 3;
  28606. return ValueCondition;
  28607. })(Condition);
  28608. BABYLON.ValueCondition = ValueCondition;
  28609. var PredicateCondition = (function (_super) {
  28610. __extends(PredicateCondition, _super);
  28611. function PredicateCondition(actionManager, predicate) {
  28612. _super.call(this, actionManager);
  28613. this.predicate = predicate;
  28614. }
  28615. PredicateCondition.prototype.isValid = function () {
  28616. return this.predicate();
  28617. };
  28618. return PredicateCondition;
  28619. })(Condition);
  28620. BABYLON.PredicateCondition = PredicateCondition;
  28621. var StateCondition = (function (_super) {
  28622. __extends(StateCondition, _super);
  28623. function StateCondition(actionManager, target, value) {
  28624. _super.call(this, actionManager);
  28625. this.value = value;
  28626. this._target = target;
  28627. }
  28628. // Methods
  28629. StateCondition.prototype.isValid = function () {
  28630. return this._target.state === this.value;
  28631. };
  28632. return StateCondition;
  28633. })(Condition);
  28634. BABYLON.StateCondition = StateCondition;
  28635. })(BABYLON || (BABYLON = {}));
  28636. var BABYLON;
  28637. (function (BABYLON) {
  28638. var Action = (function () {
  28639. function Action(triggerOptions, condition) {
  28640. this.triggerOptions = triggerOptions;
  28641. if (triggerOptions.parameter) {
  28642. this.trigger = triggerOptions.trigger;
  28643. this._triggerParameter = triggerOptions.parameter;
  28644. }
  28645. else {
  28646. this.trigger = triggerOptions;
  28647. }
  28648. this._nextActiveAction = this;
  28649. this._condition = condition;
  28650. }
  28651. // Methods
  28652. Action.prototype._prepare = function () {
  28653. };
  28654. Action.prototype.getTriggerParameter = function () {
  28655. return this._triggerParameter;
  28656. };
  28657. Action.prototype._executeCurrent = function (evt) {
  28658. if (this._nextActiveAction._condition) {
  28659. var condition = this._nextActiveAction._condition;
  28660. var currentRenderId = this._actionManager.getScene().getRenderId();
  28661. // We cache the current evaluation for the current frame
  28662. if (condition._evaluationId === currentRenderId) {
  28663. if (!condition._currentResult) {
  28664. return;
  28665. }
  28666. }
  28667. else {
  28668. condition._evaluationId = currentRenderId;
  28669. if (!condition.isValid()) {
  28670. condition._currentResult = false;
  28671. return;
  28672. }
  28673. condition._currentResult = true;
  28674. }
  28675. }
  28676. this._nextActiveAction.execute(evt);
  28677. this.skipToNextActiveAction();
  28678. };
  28679. Action.prototype.execute = function (evt) {
  28680. };
  28681. Action.prototype.skipToNextActiveAction = function () {
  28682. if (this._nextActiveAction._child) {
  28683. if (!this._nextActiveAction._child._actionManager) {
  28684. this._nextActiveAction._child._actionManager = this._actionManager;
  28685. }
  28686. this._nextActiveAction = this._nextActiveAction._child;
  28687. }
  28688. else {
  28689. this._nextActiveAction = this;
  28690. }
  28691. };
  28692. Action.prototype.then = function (action) {
  28693. this._child = action;
  28694. action._actionManager = this._actionManager;
  28695. action._prepare();
  28696. return action;
  28697. };
  28698. Action.prototype._getProperty = function (propertyPath) {
  28699. return this._actionManager._getProperty(propertyPath);
  28700. };
  28701. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  28702. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28703. };
  28704. return Action;
  28705. })();
  28706. BABYLON.Action = Action;
  28707. })(BABYLON || (BABYLON = {}));
  28708. var BABYLON;
  28709. (function (BABYLON) {
  28710. /**
  28711. * ActionEvent is the event beint sent when an action is triggered.
  28712. */
  28713. var ActionEvent = (function () {
  28714. /**
  28715. * @constructor
  28716. * @param source The mesh or sprite that triggered the action.
  28717. * @param pointerX The X mouse cursor position at the time of the event
  28718. * @param pointerY The Y mouse cursor position at the time of the event
  28719. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  28720. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  28721. */
  28722. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  28723. this.source = source;
  28724. this.pointerX = pointerX;
  28725. this.pointerY = pointerY;
  28726. this.meshUnderPointer = meshUnderPointer;
  28727. this.sourceEvent = sourceEvent;
  28728. this.additionalData = additionalData;
  28729. }
  28730. /**
  28731. * Helper function to auto-create an ActionEvent from a source mesh.
  28732. * @param source The source mesh that triggered the event
  28733. * @param evt {Event} The original (browser) event
  28734. */
  28735. ActionEvent.CreateNew = function (source, evt, additionalData) {
  28736. var scene = source.getScene();
  28737. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28738. };
  28739. /**
  28740. * Helper function to auto-create an ActionEvent from a source mesh.
  28741. * @param source The source sprite that triggered the event
  28742. * @param scene Scene associated with the sprite
  28743. * @param evt {Event} The original (browser) event
  28744. */
  28745. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  28746. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28747. };
  28748. /**
  28749. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  28750. * @param scene the scene where the event occurred
  28751. * @param evt {Event} The original (browser) event
  28752. */
  28753. ActionEvent.CreateNewFromScene = function (scene, evt) {
  28754. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  28755. };
  28756. return ActionEvent;
  28757. })();
  28758. BABYLON.ActionEvent = ActionEvent;
  28759. /**
  28760. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  28761. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  28762. */
  28763. var ActionManager = (function () {
  28764. function ActionManager(scene) {
  28765. // Members
  28766. this.actions = new Array();
  28767. this._scene = scene;
  28768. scene._actionManagers.push(this);
  28769. }
  28770. Object.defineProperty(ActionManager, "NothingTrigger", {
  28771. get: function () {
  28772. return ActionManager._NothingTrigger;
  28773. },
  28774. enumerable: true,
  28775. configurable: true
  28776. });
  28777. Object.defineProperty(ActionManager, "OnPickTrigger", {
  28778. get: function () {
  28779. return ActionManager._OnPickTrigger;
  28780. },
  28781. enumerable: true,
  28782. configurable: true
  28783. });
  28784. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  28785. get: function () {
  28786. return ActionManager._OnLeftPickTrigger;
  28787. },
  28788. enumerable: true,
  28789. configurable: true
  28790. });
  28791. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  28792. get: function () {
  28793. return ActionManager._OnRightPickTrigger;
  28794. },
  28795. enumerable: true,
  28796. configurable: true
  28797. });
  28798. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  28799. get: function () {
  28800. return ActionManager._OnCenterPickTrigger;
  28801. },
  28802. enumerable: true,
  28803. configurable: true
  28804. });
  28805. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  28806. get: function () {
  28807. return ActionManager._OnPickDownTrigger;
  28808. },
  28809. enumerable: true,
  28810. configurable: true
  28811. });
  28812. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28813. get: function () {
  28814. return ActionManager._OnPickUpTrigger;
  28815. },
  28816. enumerable: true,
  28817. configurable: true
  28818. });
  28819. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  28820. /// This trigger will only be raised if you also declared a OnPickDown
  28821. get: function () {
  28822. return ActionManager._OnPickOutTrigger;
  28823. },
  28824. enumerable: true,
  28825. configurable: true
  28826. });
  28827. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  28828. get: function () {
  28829. return ActionManager._OnLongPressTrigger;
  28830. },
  28831. enumerable: true,
  28832. configurable: true
  28833. });
  28834. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  28835. get: function () {
  28836. return ActionManager._OnPointerOverTrigger;
  28837. },
  28838. enumerable: true,
  28839. configurable: true
  28840. });
  28841. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28842. get: function () {
  28843. return ActionManager._OnPointerOutTrigger;
  28844. },
  28845. enumerable: true,
  28846. configurable: true
  28847. });
  28848. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28849. get: function () {
  28850. return ActionManager._OnEveryFrameTrigger;
  28851. },
  28852. enumerable: true,
  28853. configurable: true
  28854. });
  28855. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28856. get: function () {
  28857. return ActionManager._OnIntersectionEnterTrigger;
  28858. },
  28859. enumerable: true,
  28860. configurable: true
  28861. });
  28862. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28863. get: function () {
  28864. return ActionManager._OnIntersectionExitTrigger;
  28865. },
  28866. enumerable: true,
  28867. configurable: true
  28868. });
  28869. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28870. get: function () {
  28871. return ActionManager._OnKeyDownTrigger;
  28872. },
  28873. enumerable: true,
  28874. configurable: true
  28875. });
  28876. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28877. get: function () {
  28878. return ActionManager._OnKeyUpTrigger;
  28879. },
  28880. enumerable: true,
  28881. configurable: true
  28882. });
  28883. // Methods
  28884. ActionManager.prototype.dispose = function () {
  28885. var index = this._scene._actionManagers.indexOf(this);
  28886. if (index > -1) {
  28887. this._scene._actionManagers.splice(index, 1);
  28888. }
  28889. };
  28890. ActionManager.prototype.getScene = function () {
  28891. return this._scene;
  28892. };
  28893. /**
  28894. * Does this action manager handles actions of any of the given triggers
  28895. * @param {number[]} triggers - the triggers to be tested
  28896. * @return {boolean} whether one (or more) of the triggers is handeled
  28897. */
  28898. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28899. for (var index = 0; index < this.actions.length; index++) {
  28900. var action = this.actions[index];
  28901. if (triggers.indexOf(action.trigger) > -1) {
  28902. return true;
  28903. }
  28904. }
  28905. return false;
  28906. };
  28907. /**
  28908. * Does this action manager handles actions of a given trigger
  28909. * @param {number} trigger - the trigger to be tested
  28910. * @return {boolean} whether the trigger is handeled
  28911. */
  28912. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28913. for (var index = 0; index < this.actions.length; index++) {
  28914. var action = this.actions[index];
  28915. if (action.trigger === trigger) {
  28916. return true;
  28917. }
  28918. }
  28919. return false;
  28920. };
  28921. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28922. /**
  28923. * Does this action manager has pointer triggers
  28924. * @return {boolean} whether or not it has pointer triggers
  28925. */
  28926. get: function () {
  28927. for (var index = 0; index < this.actions.length; index++) {
  28928. var action = this.actions[index];
  28929. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28930. return true;
  28931. }
  28932. }
  28933. return false;
  28934. },
  28935. enumerable: true,
  28936. configurable: true
  28937. });
  28938. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28939. /**
  28940. * Does this action manager has pick triggers
  28941. * @return {boolean} whether or not it has pick triggers
  28942. */
  28943. get: function () {
  28944. for (var index = 0; index < this.actions.length; index++) {
  28945. var action = this.actions[index];
  28946. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  28947. return true;
  28948. }
  28949. }
  28950. return false;
  28951. },
  28952. enumerable: true,
  28953. configurable: true
  28954. });
  28955. /**
  28956. * Registers an action to this action manager
  28957. * @param {BABYLON.Action} action - the action to be registered
  28958. * @return {BABYLON.Action} the action amended (prepared) after registration
  28959. */
  28960. ActionManager.prototype.registerAction = function (action) {
  28961. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28962. if (this.getScene().actionManager !== this) {
  28963. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28964. return null;
  28965. }
  28966. }
  28967. this.actions.push(action);
  28968. action._actionManager = this;
  28969. action._prepare();
  28970. return action;
  28971. };
  28972. /**
  28973. * Process a specific trigger
  28974. * @param {number} trigger - the trigger to process
  28975. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28976. */
  28977. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28978. for (var index = 0; index < this.actions.length; index++) {
  28979. var action = this.actions[index];
  28980. if (action.trigger === trigger) {
  28981. if (trigger === ActionManager.OnKeyUpTrigger
  28982. || trigger === ActionManager.OnKeyDownTrigger) {
  28983. var parameter = action.getTriggerParameter();
  28984. if (parameter) {
  28985. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28986. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28987. if (actualkey !== parameter.toLowerCase()) {
  28988. continue;
  28989. }
  28990. }
  28991. }
  28992. action._executeCurrent(evt);
  28993. }
  28994. }
  28995. };
  28996. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28997. var properties = propertyPath.split(".");
  28998. for (var index = 0; index < properties.length - 1; index++) {
  28999. target = target[properties[index]];
  29000. }
  29001. return target;
  29002. };
  29003. ActionManager.prototype._getProperty = function (propertyPath) {
  29004. var properties = propertyPath.split(".");
  29005. return properties[properties.length - 1];
  29006. };
  29007. ActionManager.Parse = function (parsedActions, object, scene) {
  29008. var actionManager = new BABYLON.ActionManager(scene);
  29009. if (object === null)
  29010. scene.actionManager = actionManager;
  29011. else
  29012. object.actionManager = actionManager;
  29013. // instanciate a new object
  29014. var instanciate = function (name, params) {
  29015. var newInstance = Object.create(BABYLON[name].prototype);
  29016. newInstance.constructor.apply(newInstance, params);
  29017. return newInstance;
  29018. };
  29019. var parseParameter = function (name, value, target, propertyPath) {
  29020. if (propertyPath === null) {
  29021. // String, boolean or float
  29022. var floatValue = parseFloat(value);
  29023. if (value === "true" || value === "false")
  29024. return value === "true";
  29025. else
  29026. return isNaN(floatValue) ? value : floatValue;
  29027. }
  29028. var effectiveTarget = propertyPath.split(".");
  29029. var values = value.split(",");
  29030. // Get effective Target
  29031. for (var i = 0; i < effectiveTarget.length; i++) {
  29032. target = target[effectiveTarget[i]];
  29033. }
  29034. // Return appropriate value with its type
  29035. if (typeof (target) === "boolean")
  29036. return values[0] === "true";
  29037. if (typeof (target) === "string")
  29038. return values[0];
  29039. // Parameters with multiple values such as Vector3 etc.
  29040. var split = new Array();
  29041. for (var i = 0; i < values.length; i++)
  29042. split.push(parseFloat(values[i]));
  29043. if (target instanceof BABYLON.Vector3)
  29044. return BABYLON.Vector3.FromArray(split);
  29045. if (target instanceof BABYLON.Vector4)
  29046. return BABYLON.Vector4.FromArray(split);
  29047. if (target instanceof BABYLON.Color3)
  29048. return BABYLON.Color3.FromArray(split);
  29049. if (target instanceof BABYLON.Color4)
  29050. return BABYLON.Color4.FromArray(split);
  29051. return parseFloat(values[0]);
  29052. };
  29053. // traverse graph per trigger
  29054. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  29055. if (combineArray === void 0) { combineArray = null; }
  29056. if (parsedAction.detached)
  29057. return;
  29058. var parameters = new Array();
  29059. var target = null;
  29060. var propertyPath = null;
  29061. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  29062. // Parameters
  29063. if (parsedAction.type === 2)
  29064. parameters.push(actionManager);
  29065. else
  29066. parameters.push(trigger);
  29067. if (combine) {
  29068. var actions = new Array();
  29069. for (var j = 0; j < parsedAction.combine.length; j++) {
  29070. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  29071. }
  29072. parameters.push(actions);
  29073. }
  29074. else {
  29075. for (var i = 0; i < parsedAction.properties.length; i++) {
  29076. var value = parsedAction.properties[i].value;
  29077. var name = parsedAction.properties[i].name;
  29078. var targetType = parsedAction.properties[i].targetType;
  29079. if (name === "target")
  29080. if (targetType !== null && targetType === "SceneProperties")
  29081. value = target = scene;
  29082. else
  29083. value = target = scene.getNodeByName(value);
  29084. else if (name === "parent")
  29085. value = scene.getNodeByName(value);
  29086. else if (name === "sound")
  29087. value = scene.getSoundByName(value);
  29088. else if (name !== "propertyPath") {
  29089. if (parsedAction.type === 2 && name === "operator")
  29090. value = BABYLON.ValueCondition[value];
  29091. else
  29092. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  29093. }
  29094. else {
  29095. propertyPath = value;
  29096. }
  29097. parameters.push(value);
  29098. }
  29099. }
  29100. if (combineArray === null) {
  29101. parameters.push(condition);
  29102. }
  29103. else {
  29104. parameters.push(null);
  29105. }
  29106. // If interpolate value action
  29107. if (parsedAction.name === "InterpolateValueAction") {
  29108. var param = parameters[parameters.length - 2];
  29109. parameters[parameters.length - 1] = param;
  29110. parameters[parameters.length - 2] = condition;
  29111. }
  29112. // Action or condition(s) and not CombineAction
  29113. var newAction = instanciate(parsedAction.name, parameters);
  29114. if (newAction instanceof BABYLON.Condition && condition !== null) {
  29115. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  29116. if (action)
  29117. action.then(nothing);
  29118. else
  29119. actionManager.registerAction(nothing);
  29120. action = nothing;
  29121. }
  29122. if (combineArray === null) {
  29123. if (newAction instanceof BABYLON.Condition) {
  29124. condition = newAction;
  29125. newAction = action;
  29126. }
  29127. else {
  29128. condition = null;
  29129. if (action)
  29130. action.then(newAction);
  29131. else
  29132. actionManager.registerAction(newAction);
  29133. }
  29134. }
  29135. else {
  29136. combineArray.push(newAction);
  29137. }
  29138. for (var i = 0; i < parsedAction.children.length; i++)
  29139. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  29140. };
  29141. // triggers
  29142. for (var i = 0; i < parsedActions.children.length; i++) {
  29143. var triggerParams;
  29144. var trigger = parsedActions.children[i];
  29145. if (trigger.properties.length > 0) {
  29146. var param = trigger.properties[0].value;
  29147. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  29148. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  29149. }
  29150. else
  29151. triggerParams = BABYLON.ActionManager[trigger.name];
  29152. for (var j = 0; j < trigger.children.length; j++) {
  29153. if (!trigger.detached)
  29154. traverse(trigger.children[j], triggerParams, null, null);
  29155. }
  29156. }
  29157. };
  29158. // Statics
  29159. ActionManager._NothingTrigger = 0;
  29160. ActionManager._OnPickTrigger = 1;
  29161. ActionManager._OnLeftPickTrigger = 2;
  29162. ActionManager._OnRightPickTrigger = 3;
  29163. ActionManager._OnCenterPickTrigger = 4;
  29164. ActionManager._OnPickDownTrigger = 5;
  29165. ActionManager._OnPickUpTrigger = 6;
  29166. ActionManager._OnLongPressTrigger = 7;
  29167. ActionManager._OnPointerOverTrigger = 8;
  29168. ActionManager._OnPointerOutTrigger = 9;
  29169. ActionManager._OnEveryFrameTrigger = 10;
  29170. ActionManager._OnIntersectionEnterTrigger = 11;
  29171. ActionManager._OnIntersectionExitTrigger = 12;
  29172. ActionManager._OnKeyDownTrigger = 13;
  29173. ActionManager._OnKeyUpTrigger = 14;
  29174. ActionManager._OnPickOutTrigger = 15;
  29175. ActionManager.DragMovementThreshold = 10; // in pixels
  29176. ActionManager.LongPressDelay = 500; // in milliseconds
  29177. return ActionManager;
  29178. })();
  29179. BABYLON.ActionManager = ActionManager;
  29180. })(BABYLON || (BABYLON = {}));
  29181. var BABYLON;
  29182. (function (BABYLON) {
  29183. var InterpolateValueAction = (function (_super) {
  29184. __extends(InterpolateValueAction, _super);
  29185. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  29186. if (duration === void 0) { duration = 1000; }
  29187. _super.call(this, triggerOptions, condition);
  29188. this.propertyPath = propertyPath;
  29189. this.value = value;
  29190. this.duration = duration;
  29191. this.stopOtherAnimations = stopOtherAnimations;
  29192. this.onInterpolationDone = onInterpolationDone;
  29193. this._target = target;
  29194. }
  29195. InterpolateValueAction.prototype._prepare = function () {
  29196. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29197. this._property = this._getProperty(this.propertyPath);
  29198. };
  29199. InterpolateValueAction.prototype.execute = function () {
  29200. var scene = this._actionManager.getScene();
  29201. var keys = [
  29202. {
  29203. frame: 0,
  29204. value: this._target[this._property]
  29205. }, {
  29206. frame: 100,
  29207. value: this.value
  29208. }
  29209. ];
  29210. var dataType;
  29211. if (typeof this.value === "number") {
  29212. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  29213. }
  29214. else if (this.value instanceof BABYLON.Color3) {
  29215. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  29216. }
  29217. else if (this.value instanceof BABYLON.Vector3) {
  29218. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  29219. }
  29220. else if (this.value instanceof BABYLON.Matrix) {
  29221. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  29222. }
  29223. else if (this.value instanceof BABYLON.Quaternion) {
  29224. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  29225. }
  29226. else {
  29227. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  29228. return;
  29229. }
  29230. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  29231. animation.setKeys(keys);
  29232. if (this.stopOtherAnimations) {
  29233. scene.stopAnimation(this._target);
  29234. }
  29235. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  29236. };
  29237. return InterpolateValueAction;
  29238. })(BABYLON.Action);
  29239. BABYLON.InterpolateValueAction = InterpolateValueAction;
  29240. })(BABYLON || (BABYLON = {}));
  29241. var BABYLON;
  29242. (function (BABYLON) {
  29243. var SwitchBooleanAction = (function (_super) {
  29244. __extends(SwitchBooleanAction, _super);
  29245. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  29246. _super.call(this, triggerOptions, condition);
  29247. this.propertyPath = propertyPath;
  29248. this._target = target;
  29249. }
  29250. SwitchBooleanAction.prototype._prepare = function () {
  29251. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29252. this._property = this._getProperty(this.propertyPath);
  29253. };
  29254. SwitchBooleanAction.prototype.execute = function () {
  29255. this._target[this._property] = !this._target[this._property];
  29256. };
  29257. return SwitchBooleanAction;
  29258. })(BABYLON.Action);
  29259. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  29260. var SetStateAction = (function (_super) {
  29261. __extends(SetStateAction, _super);
  29262. function SetStateAction(triggerOptions, target, value, condition) {
  29263. _super.call(this, triggerOptions, condition);
  29264. this.value = value;
  29265. this._target = target;
  29266. }
  29267. SetStateAction.prototype.execute = function () {
  29268. this._target.state = this.value;
  29269. };
  29270. return SetStateAction;
  29271. })(BABYLON.Action);
  29272. BABYLON.SetStateAction = SetStateAction;
  29273. var SetValueAction = (function (_super) {
  29274. __extends(SetValueAction, _super);
  29275. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  29276. _super.call(this, triggerOptions, condition);
  29277. this.propertyPath = propertyPath;
  29278. this.value = value;
  29279. this._target = target;
  29280. }
  29281. SetValueAction.prototype._prepare = function () {
  29282. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29283. this._property = this._getProperty(this.propertyPath);
  29284. };
  29285. SetValueAction.prototype.execute = function () {
  29286. this._target[this._property] = this.value;
  29287. };
  29288. return SetValueAction;
  29289. })(BABYLON.Action);
  29290. BABYLON.SetValueAction = SetValueAction;
  29291. var IncrementValueAction = (function (_super) {
  29292. __extends(IncrementValueAction, _super);
  29293. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  29294. _super.call(this, triggerOptions, condition);
  29295. this.propertyPath = propertyPath;
  29296. this.value = value;
  29297. this._target = target;
  29298. }
  29299. IncrementValueAction.prototype._prepare = function () {
  29300. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29301. this._property = this._getProperty(this.propertyPath);
  29302. if (typeof this._target[this._property] !== "number") {
  29303. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  29304. }
  29305. };
  29306. IncrementValueAction.prototype.execute = function () {
  29307. this._target[this._property] += this.value;
  29308. };
  29309. return IncrementValueAction;
  29310. })(BABYLON.Action);
  29311. BABYLON.IncrementValueAction = IncrementValueAction;
  29312. var PlayAnimationAction = (function (_super) {
  29313. __extends(PlayAnimationAction, _super);
  29314. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  29315. _super.call(this, triggerOptions, condition);
  29316. this.from = from;
  29317. this.to = to;
  29318. this.loop = loop;
  29319. this._target = target;
  29320. }
  29321. PlayAnimationAction.prototype._prepare = function () {
  29322. };
  29323. PlayAnimationAction.prototype.execute = function () {
  29324. var scene = this._actionManager.getScene();
  29325. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  29326. };
  29327. return PlayAnimationAction;
  29328. })(BABYLON.Action);
  29329. BABYLON.PlayAnimationAction = PlayAnimationAction;
  29330. var StopAnimationAction = (function (_super) {
  29331. __extends(StopAnimationAction, _super);
  29332. function StopAnimationAction(triggerOptions, target, condition) {
  29333. _super.call(this, triggerOptions, condition);
  29334. this._target = target;
  29335. }
  29336. StopAnimationAction.prototype._prepare = function () {
  29337. };
  29338. StopAnimationAction.prototype.execute = function () {
  29339. var scene = this._actionManager.getScene();
  29340. scene.stopAnimation(this._target);
  29341. };
  29342. return StopAnimationAction;
  29343. })(BABYLON.Action);
  29344. BABYLON.StopAnimationAction = StopAnimationAction;
  29345. var DoNothingAction = (function (_super) {
  29346. __extends(DoNothingAction, _super);
  29347. function DoNothingAction(triggerOptions, condition) {
  29348. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  29349. _super.call(this, triggerOptions, condition);
  29350. }
  29351. DoNothingAction.prototype.execute = function () {
  29352. };
  29353. return DoNothingAction;
  29354. })(BABYLON.Action);
  29355. BABYLON.DoNothingAction = DoNothingAction;
  29356. var CombineAction = (function (_super) {
  29357. __extends(CombineAction, _super);
  29358. function CombineAction(triggerOptions, children, condition) {
  29359. _super.call(this, triggerOptions, condition);
  29360. this.children = children;
  29361. }
  29362. CombineAction.prototype._prepare = function () {
  29363. for (var index = 0; index < this.children.length; index++) {
  29364. this.children[index]._actionManager = this._actionManager;
  29365. this.children[index]._prepare();
  29366. }
  29367. };
  29368. CombineAction.prototype.execute = function (evt) {
  29369. for (var index = 0; index < this.children.length; index++) {
  29370. this.children[index].execute(evt);
  29371. }
  29372. };
  29373. return CombineAction;
  29374. })(BABYLON.Action);
  29375. BABYLON.CombineAction = CombineAction;
  29376. var ExecuteCodeAction = (function (_super) {
  29377. __extends(ExecuteCodeAction, _super);
  29378. function ExecuteCodeAction(triggerOptions, func, condition) {
  29379. _super.call(this, triggerOptions, condition);
  29380. this.func = func;
  29381. }
  29382. ExecuteCodeAction.prototype.execute = function (evt) {
  29383. this.func(evt);
  29384. };
  29385. return ExecuteCodeAction;
  29386. })(BABYLON.Action);
  29387. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  29388. var SetParentAction = (function (_super) {
  29389. __extends(SetParentAction, _super);
  29390. function SetParentAction(triggerOptions, target, parent, condition) {
  29391. _super.call(this, triggerOptions, condition);
  29392. this._target = target;
  29393. this._parent = parent;
  29394. }
  29395. SetParentAction.prototype._prepare = function () {
  29396. };
  29397. SetParentAction.prototype.execute = function () {
  29398. if (this._target.parent === this._parent) {
  29399. return;
  29400. }
  29401. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  29402. invertParentWorldMatrix.invert();
  29403. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  29404. this._target.parent = this._parent;
  29405. };
  29406. return SetParentAction;
  29407. })(BABYLON.Action);
  29408. BABYLON.SetParentAction = SetParentAction;
  29409. var PlaySoundAction = (function (_super) {
  29410. __extends(PlaySoundAction, _super);
  29411. function PlaySoundAction(triggerOptions, sound, condition) {
  29412. _super.call(this, triggerOptions, condition);
  29413. this._sound = sound;
  29414. }
  29415. PlaySoundAction.prototype._prepare = function () {
  29416. };
  29417. PlaySoundAction.prototype.execute = function () {
  29418. if (this._sound !== undefined)
  29419. this._sound.play();
  29420. };
  29421. return PlaySoundAction;
  29422. })(BABYLON.Action);
  29423. BABYLON.PlaySoundAction = PlaySoundAction;
  29424. var StopSoundAction = (function (_super) {
  29425. __extends(StopSoundAction, _super);
  29426. function StopSoundAction(triggerOptions, sound, condition) {
  29427. _super.call(this, triggerOptions, condition);
  29428. this._sound = sound;
  29429. }
  29430. StopSoundAction.prototype._prepare = function () {
  29431. };
  29432. StopSoundAction.prototype.execute = function () {
  29433. if (this._sound !== undefined)
  29434. this._sound.stop();
  29435. };
  29436. return StopSoundAction;
  29437. })(BABYLON.Action);
  29438. BABYLON.StopSoundAction = StopSoundAction;
  29439. })(BABYLON || (BABYLON = {}));
  29440. var BABYLON;
  29441. (function (BABYLON) {
  29442. var Geometry = (function () {
  29443. function Geometry(id, scene, vertexData, updatable, mesh) {
  29444. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29445. this._totalVertices = 0;
  29446. this._isDisposed = false;
  29447. this.id = id;
  29448. this._engine = scene.getEngine();
  29449. this._meshes = [];
  29450. this._scene = scene;
  29451. //Init vertex buffer cache
  29452. this._vertexBuffers = {};
  29453. this._indices = [];
  29454. // vertexData
  29455. if (vertexData) {
  29456. this.setAllVerticesData(vertexData, updatable);
  29457. }
  29458. else {
  29459. this._totalVertices = 0;
  29460. this._indices = [];
  29461. }
  29462. // applyToMesh
  29463. if (mesh) {
  29464. this.applyToMesh(mesh);
  29465. mesh.computeWorldMatrix(true);
  29466. }
  29467. }
  29468. Object.defineProperty(Geometry.prototype, "extend", {
  29469. get: function () {
  29470. return this._extend;
  29471. },
  29472. enumerable: true,
  29473. configurable: true
  29474. });
  29475. Geometry.prototype.getScene = function () {
  29476. return this._scene;
  29477. };
  29478. Geometry.prototype.getEngine = function () {
  29479. return this._engine;
  29480. };
  29481. Geometry.prototype.isReady = function () {
  29482. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29483. };
  29484. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29485. vertexData.applyToGeometry(this, updatable);
  29486. this.notifyUpdate();
  29487. };
  29488. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29489. if (this._vertexBuffers[kind]) {
  29490. this._vertexBuffers[kind].dispose();
  29491. }
  29492. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29493. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29494. stride = this._vertexBuffers[kind].getStrideSize();
  29495. this._totalVertices = data.length / stride;
  29496. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29497. var meshes = this._meshes;
  29498. var numOfMeshes = meshes.length;
  29499. for (var index = 0; index < numOfMeshes; index++) {
  29500. var mesh = meshes[index];
  29501. mesh._resetPointsArrayCache();
  29502. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29503. mesh._createGlobalSubMesh();
  29504. mesh.computeWorldMatrix(true);
  29505. }
  29506. }
  29507. this.notifyUpdate(kind);
  29508. };
  29509. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29510. var vertexBuffer = this.getVertexBuffer(kind);
  29511. if (!vertexBuffer) {
  29512. return;
  29513. }
  29514. vertexBuffer.updateDirectly(data, offset);
  29515. this.notifyUpdate(kind);
  29516. };
  29517. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29518. var vertexBuffer = this.getVertexBuffer(kind);
  29519. if (!vertexBuffer) {
  29520. return;
  29521. }
  29522. vertexBuffer.update(data);
  29523. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29524. var stride = vertexBuffer.getStrideSize();
  29525. this._totalVertices = data.length / stride;
  29526. if (updateExtends) {
  29527. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29528. }
  29529. var meshes = this._meshes;
  29530. var numOfMeshes = meshes.length;
  29531. for (var index = 0; index < numOfMeshes; index++) {
  29532. var mesh = meshes[index];
  29533. mesh._resetPointsArrayCache();
  29534. if (updateExtends) {
  29535. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29536. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29537. var subMesh = mesh.subMeshes[subIndex];
  29538. subMesh.refreshBoundingInfo();
  29539. }
  29540. }
  29541. }
  29542. }
  29543. this.notifyUpdate(kind);
  29544. };
  29545. Geometry.prototype.getTotalVertices = function () {
  29546. if (!this.isReady()) {
  29547. return 0;
  29548. }
  29549. return this._totalVertices;
  29550. };
  29551. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  29552. var vertexBuffer = this.getVertexBuffer(kind);
  29553. if (!vertexBuffer) {
  29554. return null;
  29555. }
  29556. var orig = vertexBuffer.getData();
  29557. if (!copyWhenShared || this._meshes.length === 1) {
  29558. return orig;
  29559. }
  29560. else {
  29561. var len = orig.length;
  29562. var copy = [];
  29563. for (var i = 0; i < len; i++) {
  29564. copy.push(orig[i]);
  29565. }
  29566. return copy;
  29567. }
  29568. };
  29569. Geometry.prototype.getVertexBuffer = function (kind) {
  29570. if (!this.isReady()) {
  29571. return null;
  29572. }
  29573. return this._vertexBuffers[kind];
  29574. };
  29575. Geometry.prototype.getVertexBuffers = function () {
  29576. if (!this.isReady()) {
  29577. return null;
  29578. }
  29579. return this._vertexBuffers;
  29580. };
  29581. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29582. if (!this._vertexBuffers) {
  29583. if (this._delayInfo) {
  29584. return this._delayInfo.indexOf(kind) !== -1;
  29585. }
  29586. return false;
  29587. }
  29588. return this._vertexBuffers[kind] !== undefined;
  29589. };
  29590. Geometry.prototype.getVerticesDataKinds = function () {
  29591. var result = [];
  29592. var kind;
  29593. if (!this._vertexBuffers && this._delayInfo) {
  29594. for (kind in this._delayInfo) {
  29595. result.push(kind);
  29596. }
  29597. }
  29598. else {
  29599. for (kind in this._vertexBuffers) {
  29600. result.push(kind);
  29601. }
  29602. }
  29603. return result;
  29604. };
  29605. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29606. if (this._indexBuffer) {
  29607. this._engine._releaseBuffer(this._indexBuffer);
  29608. }
  29609. this._indices = indices;
  29610. if (this._meshes.length !== 0 && this._indices) {
  29611. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29612. }
  29613. if (totalVertices !== undefined) {
  29614. this._totalVertices = totalVertices;
  29615. }
  29616. var meshes = this._meshes;
  29617. var numOfMeshes = meshes.length;
  29618. for (var index = 0; index < numOfMeshes; index++) {
  29619. meshes[index]._createGlobalSubMesh();
  29620. }
  29621. this.notifyUpdate();
  29622. };
  29623. Geometry.prototype.getTotalIndices = function () {
  29624. if (!this.isReady()) {
  29625. return 0;
  29626. }
  29627. return this._indices.length;
  29628. };
  29629. Geometry.prototype.getIndices = function (copyWhenShared) {
  29630. if (!this.isReady()) {
  29631. return null;
  29632. }
  29633. var orig = this._indices;
  29634. if (!copyWhenShared || this._meshes.length === 1) {
  29635. return orig;
  29636. }
  29637. else {
  29638. var len = orig.length;
  29639. var copy = [];
  29640. for (var i = 0; i < len; i++) {
  29641. copy.push(orig[i]);
  29642. }
  29643. return copy;
  29644. }
  29645. };
  29646. Geometry.prototype.getIndexBuffer = function () {
  29647. if (!this.isReady()) {
  29648. return null;
  29649. }
  29650. return this._indexBuffer;
  29651. };
  29652. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29653. var meshes = this._meshes;
  29654. var index = meshes.indexOf(mesh);
  29655. if (index === -1) {
  29656. return;
  29657. }
  29658. for (var kind in this._vertexBuffers) {
  29659. this._vertexBuffers[kind].dispose();
  29660. }
  29661. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  29662. this._indexBuffer = null;
  29663. }
  29664. meshes.splice(index, 1);
  29665. mesh._geometry = null;
  29666. if (meshes.length === 0 && shouldDispose) {
  29667. this.dispose();
  29668. }
  29669. };
  29670. Geometry.prototype.applyToMesh = function (mesh) {
  29671. if (mesh._geometry === this) {
  29672. return;
  29673. }
  29674. var previousGeometry = mesh._geometry;
  29675. if (previousGeometry) {
  29676. previousGeometry.releaseForMesh(mesh);
  29677. }
  29678. var meshes = this._meshes;
  29679. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29680. mesh._geometry = this;
  29681. this._scene.pushGeometry(this);
  29682. meshes.push(mesh);
  29683. if (this.isReady()) {
  29684. this._applyToMesh(mesh);
  29685. }
  29686. else {
  29687. mesh._boundingInfo = this._boundingInfo;
  29688. }
  29689. };
  29690. Geometry.prototype._applyToMesh = function (mesh) {
  29691. var numOfMeshes = this._meshes.length;
  29692. // vertexBuffers
  29693. for (var kind in this._vertexBuffers) {
  29694. if (numOfMeshes === 1) {
  29695. this._vertexBuffers[kind].create();
  29696. }
  29697. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  29698. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29699. mesh._resetPointsArrayCache();
  29700. if (!this._extend) {
  29701. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  29702. }
  29703. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29704. mesh._createGlobalSubMesh();
  29705. //bounding info was just created again, world matrix should be applied again.
  29706. mesh._updateBoundingInfo();
  29707. }
  29708. }
  29709. // indexBuffer
  29710. if (numOfMeshes === 1 && this._indices) {
  29711. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29712. }
  29713. if (this._indexBuffer) {
  29714. this._indexBuffer.references = numOfMeshes;
  29715. }
  29716. };
  29717. Geometry.prototype.notifyUpdate = function (kind) {
  29718. if (this.onGeometryUpdated) {
  29719. this.onGeometryUpdated(this, kind);
  29720. }
  29721. };
  29722. Geometry.prototype.load = function (scene, onLoaded) {
  29723. var _this = this;
  29724. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29725. return;
  29726. }
  29727. if (this.isReady()) {
  29728. if (onLoaded) {
  29729. onLoaded();
  29730. }
  29731. return;
  29732. }
  29733. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29734. scene._addPendingData(this);
  29735. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29736. _this._delayLoadingFunction(JSON.parse(data), _this);
  29737. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29738. _this._delayInfo = [];
  29739. scene._removePendingData(_this);
  29740. var meshes = _this._meshes;
  29741. var numOfMeshes = meshes.length;
  29742. for (var index = 0; index < numOfMeshes; index++) {
  29743. _this._applyToMesh(meshes[index]);
  29744. }
  29745. if (onLoaded) {
  29746. onLoaded();
  29747. }
  29748. }, function () { }, scene.database);
  29749. };
  29750. Geometry.prototype.isDisposed = function () {
  29751. return this._isDisposed;
  29752. };
  29753. Geometry.prototype.dispose = function () {
  29754. var meshes = this._meshes;
  29755. var numOfMeshes = meshes.length;
  29756. var index;
  29757. for (index = 0; index < numOfMeshes; index++) {
  29758. this.releaseForMesh(meshes[index]);
  29759. }
  29760. this._meshes = [];
  29761. for (var kind in this._vertexBuffers) {
  29762. this._vertexBuffers[kind].dispose();
  29763. }
  29764. this._vertexBuffers = [];
  29765. this._totalVertices = 0;
  29766. if (this._indexBuffer) {
  29767. this._engine._releaseBuffer(this._indexBuffer);
  29768. }
  29769. this._indexBuffer = null;
  29770. this._indices = [];
  29771. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29772. this.delayLoadingFile = null;
  29773. this._delayLoadingFunction = null;
  29774. this._delayInfo = [];
  29775. this._boundingInfo = null;
  29776. this._scene.removeGeometry(this);
  29777. this._isDisposed = true;
  29778. };
  29779. Geometry.prototype.copy = function (id) {
  29780. var vertexData = new BABYLON.VertexData();
  29781. vertexData.indices = [];
  29782. var indices = this.getIndices();
  29783. for (var index = 0; index < indices.length; index++) {
  29784. vertexData.indices.push(indices[index]);
  29785. }
  29786. var updatable = false;
  29787. var stopChecking = false;
  29788. var kind;
  29789. for (kind in this._vertexBuffers) {
  29790. // using slice() to make a copy of the array and not just reference it
  29791. var data = this.getVerticesData(kind);
  29792. if (data instanceof Float32Array) {
  29793. vertexData.set(new Float32Array(data), kind);
  29794. }
  29795. else {
  29796. vertexData.set(data.slice(0), kind);
  29797. }
  29798. if (!stopChecking) {
  29799. updatable = this.getVertexBuffer(kind).isUpdatable();
  29800. stopChecking = !updatable;
  29801. }
  29802. }
  29803. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29804. geometry.delayLoadState = this.delayLoadState;
  29805. geometry.delayLoadingFile = this.delayLoadingFile;
  29806. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29807. for (kind in this._delayInfo) {
  29808. geometry._delayInfo = geometry._delayInfo || [];
  29809. geometry._delayInfo.push(kind);
  29810. }
  29811. // Bounding info
  29812. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29813. return geometry;
  29814. };
  29815. Geometry.prototype.serialize = function () {
  29816. var serializationObject = {};
  29817. serializationObject.id = this.id;
  29818. if (BABYLON.Tags.HasTags(this)) {
  29819. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29820. }
  29821. return serializationObject;
  29822. };
  29823. Geometry.prototype.serializeVerticeData = function () {
  29824. var serializationObject = this.serialize();
  29825. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29826. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29827. }
  29828. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29829. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29830. }
  29831. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29832. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29833. }
  29834. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29835. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29836. }
  29837. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29838. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29839. }
  29840. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29841. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29842. }
  29843. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29844. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29845. }
  29846. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29847. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29848. }
  29849. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29850. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29851. }
  29852. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29853. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29854. serializationObject.matricesIndices._isExpanded = true;
  29855. }
  29856. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29857. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29858. }
  29859. serializationObject.indices = this.getIndices();
  29860. return serializationObject;
  29861. };
  29862. // Statics
  29863. Geometry.ExtractFromMesh = function (mesh, id) {
  29864. var geometry = mesh._geometry;
  29865. if (!geometry) {
  29866. return null;
  29867. }
  29868. return geometry.copy(id);
  29869. };
  29870. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29871. // be aware Math.random() could cause collisions
  29872. Geometry.RandomId = function () {
  29873. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  29874. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  29875. return v.toString(16);
  29876. });
  29877. };
  29878. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29879. var scene = mesh.getScene();
  29880. // Geometry
  29881. var geometryId = parsedGeometry.geometryId;
  29882. if (geometryId) {
  29883. var geometry = scene.getGeometryByID(geometryId);
  29884. if (geometry) {
  29885. geometry.applyToMesh(mesh);
  29886. }
  29887. }
  29888. else if (parsedGeometry instanceof ArrayBuffer) {
  29889. var binaryInfo = mesh._binaryInfo;
  29890. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29891. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29892. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29893. }
  29894. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29895. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29896. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29897. }
  29898. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29899. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29900. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29901. }
  29902. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29903. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29904. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29905. }
  29906. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29907. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29908. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29909. }
  29910. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29911. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29912. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29913. }
  29914. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29915. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29916. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29917. }
  29918. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29919. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29920. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29921. }
  29922. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29923. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29924. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29925. }
  29926. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29927. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29928. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29929. }
  29930. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29931. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29932. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29933. }
  29934. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29935. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29936. mesh.setIndices(indicesData);
  29937. }
  29938. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29939. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29940. mesh.subMeshes = [];
  29941. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29942. var materialIndex = subMeshesData[(i * 5) + 0];
  29943. var verticesStart = subMeshesData[(i * 5) + 1];
  29944. var verticesCount = subMeshesData[(i * 5) + 2];
  29945. var indexStart = subMeshesData[(i * 5) + 3];
  29946. var indexCount = subMeshesData[(i * 5) + 4];
  29947. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29948. }
  29949. }
  29950. }
  29951. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29952. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  29953. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  29954. if (parsedGeometry.uvs) {
  29955. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  29956. }
  29957. if (parsedGeometry.uvs2) {
  29958. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  29959. }
  29960. if (parsedGeometry.uvs3) {
  29961. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  29962. }
  29963. if (parsedGeometry.uvs4) {
  29964. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  29965. }
  29966. if (parsedGeometry.uvs5) {
  29967. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  29968. }
  29969. if (parsedGeometry.uvs6) {
  29970. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  29971. }
  29972. if (parsedGeometry.colors) {
  29973. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  29974. }
  29975. if (parsedGeometry.matricesIndices) {
  29976. if (!parsedGeometry.matricesIndices._isExpanded) {
  29977. var floatIndices = [];
  29978. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29979. var matricesIndex = parsedGeometry.matricesIndices[i];
  29980. floatIndices.push(matricesIndex & 0x000000FF);
  29981. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29982. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29983. floatIndices.push(matricesIndex >> 24);
  29984. }
  29985. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  29986. }
  29987. else {
  29988. delete parsedGeometry.matricesIndices._isExpanded;
  29989. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  29990. }
  29991. }
  29992. if (parsedGeometry.matricesIndicesExtra) {
  29993. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29994. var floatIndices = [];
  29995. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29996. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29997. floatIndices.push(matricesIndex & 0x000000FF);
  29998. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29999. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30000. floatIndices.push(matricesIndex >> 24);
  30001. }
  30002. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  30003. }
  30004. else {
  30005. delete parsedGeometry.matricesIndices._isExpanded;
  30006. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  30007. }
  30008. }
  30009. if (parsedGeometry.matricesWeights) {
  30010. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  30011. }
  30012. if (parsedGeometry.matricesWeightsExtra) {
  30013. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  30014. }
  30015. mesh.setIndices(parsedGeometry.indices);
  30016. }
  30017. // SubMeshes
  30018. if (parsedGeometry.subMeshes) {
  30019. mesh.subMeshes = [];
  30020. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  30021. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  30022. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  30023. }
  30024. }
  30025. // Flat shading
  30026. if (mesh._shouldGenerateFlatShading) {
  30027. mesh.convertToFlatShadedMesh();
  30028. delete mesh._shouldGenerateFlatShading;
  30029. }
  30030. // Update
  30031. mesh.computeWorldMatrix(true);
  30032. // Octree
  30033. if (scene['_selectionOctree']) {
  30034. scene['_selectionOctree'].addMesh(mesh);
  30035. }
  30036. };
  30037. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  30038. if (scene.getGeometryByID(parsedVertexData.id)) {
  30039. return null; // null since geometry could be something else than a box...
  30040. }
  30041. var geometry = new Geometry(parsedVertexData.id, scene);
  30042. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  30043. if (parsedVertexData.delayLoadingFile) {
  30044. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30045. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  30046. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  30047. geometry._delayInfo = [];
  30048. if (parsedVertexData.hasUVs) {
  30049. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  30050. }
  30051. if (parsedVertexData.hasUVs2) {
  30052. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  30053. }
  30054. if (parsedVertexData.hasUVs3) {
  30055. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30056. }
  30057. if (parsedVertexData.hasUVs4) {
  30058. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30059. }
  30060. if (parsedVertexData.hasUVs5) {
  30061. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30062. }
  30063. if (parsedVertexData.hasUVs6) {
  30064. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30065. }
  30066. if (parsedVertexData.hasColors) {
  30067. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30068. }
  30069. if (parsedVertexData.hasMatricesIndices) {
  30070. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30071. }
  30072. if (parsedVertexData.hasMatricesWeights) {
  30073. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30074. }
  30075. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  30076. }
  30077. else {
  30078. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  30079. }
  30080. scene.pushGeometry(geometry, true);
  30081. return geometry;
  30082. };
  30083. return Geometry;
  30084. })();
  30085. BABYLON.Geometry = Geometry;
  30086. /////// Primitives //////////////////////////////////////////////
  30087. var Geometry;
  30088. (function (Geometry) {
  30089. var Primitives;
  30090. (function (Primitives) {
  30091. /// Abstract class
  30092. var _Primitive = (function (_super) {
  30093. __extends(_Primitive, _super);
  30094. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  30095. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  30096. this._canBeRegenerated = _canBeRegenerated;
  30097. this._beingRegenerated = true;
  30098. this.regenerate();
  30099. this._beingRegenerated = false;
  30100. }
  30101. _Primitive.prototype.canBeRegenerated = function () {
  30102. return this._canBeRegenerated;
  30103. };
  30104. _Primitive.prototype.regenerate = function () {
  30105. if (!this._canBeRegenerated) {
  30106. return;
  30107. }
  30108. this._beingRegenerated = true;
  30109. this.setAllVerticesData(this._regenerateVertexData(), false);
  30110. this._beingRegenerated = false;
  30111. };
  30112. _Primitive.prototype.asNewGeometry = function (id) {
  30113. return _super.prototype.copy.call(this, id);
  30114. };
  30115. // overrides
  30116. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  30117. if (!this._beingRegenerated) {
  30118. return;
  30119. }
  30120. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  30121. };
  30122. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  30123. if (!this._beingRegenerated) {
  30124. return;
  30125. }
  30126. _super.prototype.setVerticesData.call(this, kind, data, false);
  30127. };
  30128. // to override
  30129. // protected
  30130. _Primitive.prototype._regenerateVertexData = function () {
  30131. throw new Error("Abstract method");
  30132. };
  30133. _Primitive.prototype.copy = function (id) {
  30134. throw new Error("Must be overriden in sub-classes.");
  30135. };
  30136. _Primitive.prototype.serialize = function () {
  30137. var serializationObject = _super.prototype.serialize.call(this);
  30138. serializationObject.canBeRegenerated = this.canBeRegenerated();
  30139. return serializationObject;
  30140. };
  30141. return _Primitive;
  30142. })(Geometry);
  30143. Primitives._Primitive = _Primitive;
  30144. var Ribbon = (function (_super) {
  30145. __extends(Ribbon, _super);
  30146. // Members
  30147. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  30148. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30149. _super.call(this, id, scene, canBeRegenerated, mesh);
  30150. this.pathArray = pathArray;
  30151. this.closeArray = closeArray;
  30152. this.closePath = closePath;
  30153. this.offset = offset;
  30154. this.side = side;
  30155. }
  30156. Ribbon.prototype._regenerateVertexData = function () {
  30157. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  30158. };
  30159. Ribbon.prototype.copy = function (id) {
  30160. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  30161. };
  30162. return Ribbon;
  30163. })(_Primitive);
  30164. Primitives.Ribbon = Ribbon;
  30165. var Box = (function (_super) {
  30166. __extends(Box, _super);
  30167. // Members
  30168. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  30169. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30170. _super.call(this, id, scene, canBeRegenerated, mesh);
  30171. this.size = size;
  30172. this.side = side;
  30173. }
  30174. Box.prototype._regenerateVertexData = function () {
  30175. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  30176. };
  30177. Box.prototype.copy = function (id) {
  30178. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30179. };
  30180. Box.prototype.serialize = function () {
  30181. var serializationObject = _super.prototype.serialize.call(this);
  30182. serializationObject.size = this.size;
  30183. return serializationObject;
  30184. };
  30185. Box.Parse = function (parsedBox, scene) {
  30186. if (scene.getGeometryByID(parsedBox.id)) {
  30187. return null; // null since geometry could be something else than a box...
  30188. }
  30189. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  30190. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  30191. scene.pushGeometry(box, true);
  30192. return box;
  30193. };
  30194. return Box;
  30195. })(_Primitive);
  30196. Primitives.Box = Box;
  30197. var Sphere = (function (_super) {
  30198. __extends(Sphere, _super);
  30199. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  30200. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30201. _super.call(this, id, scene, canBeRegenerated, mesh);
  30202. this.segments = segments;
  30203. this.diameter = diameter;
  30204. this.side = side;
  30205. }
  30206. Sphere.prototype._regenerateVertexData = function () {
  30207. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  30208. };
  30209. Sphere.prototype.copy = function (id) {
  30210. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  30211. };
  30212. Sphere.prototype.serialize = function () {
  30213. var serializationObject = _super.prototype.serialize.call(this);
  30214. serializationObject.segments = this.segments;
  30215. serializationObject.diameter = this.diameter;
  30216. return serializationObject;
  30217. };
  30218. Sphere.Parse = function (parsedSphere, scene) {
  30219. if (scene.getGeometryByID(parsedSphere.id)) {
  30220. return null; // null since geometry could be something else than a sphere...
  30221. }
  30222. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  30223. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  30224. scene.pushGeometry(sphere, true);
  30225. return sphere;
  30226. };
  30227. return Sphere;
  30228. })(_Primitive);
  30229. Primitives.Sphere = Sphere;
  30230. var Disc = (function (_super) {
  30231. __extends(Disc, _super);
  30232. // Members
  30233. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  30234. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30235. _super.call(this, id, scene, canBeRegenerated, mesh);
  30236. this.radius = radius;
  30237. this.tessellation = tessellation;
  30238. this.side = side;
  30239. }
  30240. Disc.prototype._regenerateVertexData = function () {
  30241. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  30242. };
  30243. Disc.prototype.copy = function (id) {
  30244. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  30245. };
  30246. return Disc;
  30247. })(_Primitive);
  30248. Primitives.Disc = Disc;
  30249. var Cylinder = (function (_super) {
  30250. __extends(Cylinder, _super);
  30251. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  30252. if (subdivisions === void 0) { subdivisions = 1; }
  30253. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30254. _super.call(this, id, scene, canBeRegenerated, mesh);
  30255. this.height = height;
  30256. this.diameterTop = diameterTop;
  30257. this.diameterBottom = diameterBottom;
  30258. this.tessellation = tessellation;
  30259. this.subdivisions = subdivisions;
  30260. this.side = side;
  30261. }
  30262. Cylinder.prototype._regenerateVertexData = function () {
  30263. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  30264. };
  30265. Cylinder.prototype.copy = function (id) {
  30266. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  30267. };
  30268. Cylinder.prototype.serialize = function () {
  30269. var serializationObject = _super.prototype.serialize.call(this);
  30270. serializationObject.height = this.height;
  30271. serializationObject.diameterTop = this.diameterTop;
  30272. serializationObject.diameterBottom = this.diameterBottom;
  30273. serializationObject.tessellation = this.tessellation;
  30274. return serializationObject;
  30275. };
  30276. Cylinder.Parse = function (parsedCylinder, scene) {
  30277. if (scene.getGeometryByID(parsedCylinder.id)) {
  30278. return null; // null since geometry could be something else than a cylinder...
  30279. }
  30280. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  30281. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  30282. scene.pushGeometry(cylinder, true);
  30283. return cylinder;
  30284. };
  30285. return Cylinder;
  30286. })(_Primitive);
  30287. Primitives.Cylinder = Cylinder;
  30288. var Torus = (function (_super) {
  30289. __extends(Torus, _super);
  30290. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  30291. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30292. _super.call(this, id, scene, canBeRegenerated, mesh);
  30293. this.diameter = diameter;
  30294. this.thickness = thickness;
  30295. this.tessellation = tessellation;
  30296. this.side = side;
  30297. }
  30298. Torus.prototype._regenerateVertexData = function () {
  30299. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  30300. };
  30301. Torus.prototype.copy = function (id) {
  30302. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  30303. };
  30304. Torus.prototype.serialize = function () {
  30305. var serializationObject = _super.prototype.serialize.call(this);
  30306. serializationObject.diameter = this.diameter;
  30307. serializationObject.thickness = this.thickness;
  30308. serializationObject.tessellation = this.tessellation;
  30309. return serializationObject;
  30310. };
  30311. Torus.Parse = function (parsedTorus, scene) {
  30312. if (scene.getGeometryByID(parsedTorus.id)) {
  30313. return null; // null since geometry could be something else than a torus...
  30314. }
  30315. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  30316. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  30317. scene.pushGeometry(torus, true);
  30318. return torus;
  30319. };
  30320. return Torus;
  30321. })(_Primitive);
  30322. Primitives.Torus = Torus;
  30323. var Ground = (function (_super) {
  30324. __extends(Ground, _super);
  30325. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  30326. _super.call(this, id, scene, canBeRegenerated, mesh);
  30327. this.width = width;
  30328. this.height = height;
  30329. this.subdivisions = subdivisions;
  30330. }
  30331. Ground.prototype._regenerateVertexData = function () {
  30332. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  30333. };
  30334. Ground.prototype.copy = function (id) {
  30335. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  30336. };
  30337. Ground.prototype.serialize = function () {
  30338. var serializationObject = _super.prototype.serialize.call(this);
  30339. serializationObject.width = this.width;
  30340. serializationObject.height = this.height;
  30341. serializationObject.subdivisions = this.subdivisions;
  30342. return serializationObject;
  30343. };
  30344. Ground.Parse = function (parsedGround, scene) {
  30345. if (scene.getGeometryByID(parsedGround.id)) {
  30346. return null; // null since geometry could be something else than a ground...
  30347. }
  30348. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  30349. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  30350. scene.pushGeometry(ground, true);
  30351. return ground;
  30352. };
  30353. return Ground;
  30354. })(_Primitive);
  30355. Primitives.Ground = Ground;
  30356. var TiledGround = (function (_super) {
  30357. __extends(TiledGround, _super);
  30358. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  30359. _super.call(this, id, scene, canBeRegenerated, mesh);
  30360. this.xmin = xmin;
  30361. this.zmin = zmin;
  30362. this.xmax = xmax;
  30363. this.zmax = zmax;
  30364. this.subdivisions = subdivisions;
  30365. this.precision = precision;
  30366. }
  30367. TiledGround.prototype._regenerateVertexData = function () {
  30368. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30369. };
  30370. TiledGround.prototype.copy = function (id) {
  30371. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30372. };
  30373. return TiledGround;
  30374. })(_Primitive);
  30375. Primitives.TiledGround = TiledGround;
  30376. var Plane = (function (_super) {
  30377. __extends(Plane, _super);
  30378. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30379. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30380. _super.call(this, id, scene, canBeRegenerated, mesh);
  30381. this.size = size;
  30382. this.side = side;
  30383. }
  30384. Plane.prototype._regenerateVertexData = function () {
  30385. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30386. };
  30387. Plane.prototype.copy = function (id) {
  30388. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30389. };
  30390. Plane.prototype.serialize = function () {
  30391. var serializationObject = _super.prototype.serialize.call(this);
  30392. serializationObject.size = this.size;
  30393. return serializationObject;
  30394. };
  30395. Plane.Parse = function (parsedPlane, scene) {
  30396. if (scene.getGeometryByID(parsedPlane.id)) {
  30397. return null; // null since geometry could be something else than a ground...
  30398. }
  30399. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30400. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30401. scene.pushGeometry(plane, true);
  30402. return plane;
  30403. };
  30404. return Plane;
  30405. })(_Primitive);
  30406. Primitives.Plane = Plane;
  30407. var TorusKnot = (function (_super) {
  30408. __extends(TorusKnot, _super);
  30409. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30410. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30411. _super.call(this, id, scene, canBeRegenerated, mesh);
  30412. this.radius = radius;
  30413. this.tube = tube;
  30414. this.radialSegments = radialSegments;
  30415. this.tubularSegments = tubularSegments;
  30416. this.p = p;
  30417. this.q = q;
  30418. this.side = side;
  30419. }
  30420. TorusKnot.prototype._regenerateVertexData = function () {
  30421. 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 });
  30422. };
  30423. TorusKnot.prototype.copy = function (id) {
  30424. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30425. };
  30426. TorusKnot.prototype.serialize = function () {
  30427. var serializationObject = _super.prototype.serialize.call(this);
  30428. serializationObject.radius = this.radius;
  30429. serializationObject.tube = this.tube;
  30430. serializationObject.radialSegments = this.radialSegments;
  30431. serializationObject.tubularSegments = this.tubularSegments;
  30432. serializationObject.p = this.p;
  30433. serializationObject.q = this.q;
  30434. return serializationObject;
  30435. };
  30436. ;
  30437. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30438. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30439. return null; // null since geometry could be something else than a ground...
  30440. }
  30441. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30442. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30443. scene.pushGeometry(torusKnot, true);
  30444. return torusKnot;
  30445. };
  30446. return TorusKnot;
  30447. })(_Primitive);
  30448. Primitives.TorusKnot = TorusKnot;
  30449. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30450. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30451. })(BABYLON || (BABYLON = {}));
  30452. var BABYLON;
  30453. (function (BABYLON) {
  30454. var GroundMesh = (function (_super) {
  30455. __extends(GroundMesh, _super);
  30456. function GroundMesh(name, scene) {
  30457. _super.call(this, name, scene);
  30458. this.generateOctree = false;
  30459. this._worldInverse = new BABYLON.Matrix();
  30460. }
  30461. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  30462. get: function () {
  30463. return this._subdivisions;
  30464. },
  30465. enumerable: true,
  30466. configurable: true
  30467. });
  30468. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  30469. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  30470. this._subdivisions = chunksCount;
  30471. this.subdivide(this._subdivisions);
  30472. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  30473. };
  30474. /**
  30475. * Returns a height (y) value in the Worl system :
  30476. * the ground altitude at the coordinates (x, z) expressed in the World system.
  30477. * Returns the ground y position if (x, z) are outside the ground surface.
  30478. * Not pertinent if the ground is rotated.
  30479. */
  30480. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  30481. // express x and y in the ground local system
  30482. x -= this.position.x;
  30483. z -= this.position.z;
  30484. x /= this.scaling.x;
  30485. z /= this.scaling.z;
  30486. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  30487. return this.position.y;
  30488. }
  30489. if (!this._heightQuads || this._heightQuads.length == 0) {
  30490. this._initHeightQuads();
  30491. this._computeHeightQuads();
  30492. }
  30493. var facet = this._getFacetAt(x, z);
  30494. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  30495. // return y in the World system
  30496. return y * this.scaling.y + this.position.y;
  30497. };
  30498. /**
  30499. * Returns a normalized vector (Vector3) orthogonal to the ground
  30500. * at the ground coordinates (x, z) expressed in the World system.
  30501. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  30502. * Not pertinent if the ground is rotated.
  30503. */
  30504. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  30505. var normal = new BABYLON.Vector3(0, 1, 0);
  30506. this.getNormalAtCoordinatesToRef(x, z, normal);
  30507. return normal;
  30508. };
  30509. /**
  30510. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  30511. * at the ground coordinates (x, z) expressed in the World system.
  30512. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  30513. * Not pertinent if the ground is rotated.
  30514. */
  30515. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  30516. // express x and y in the ground local system
  30517. x -= this.position.x;
  30518. z -= this.position.z;
  30519. x /= this.scaling.x;
  30520. z /= this.scaling.z;
  30521. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  30522. return;
  30523. }
  30524. if (!this._heightQuads || this._heightQuads.length == 0) {
  30525. this._initHeightQuads();
  30526. this._computeHeightQuads();
  30527. }
  30528. var facet = this._getFacetAt(x, z);
  30529. ref.x = facet.x;
  30530. ref.y = facet.y;
  30531. ref.z = facet.z;
  30532. };
  30533. /**
  30534. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  30535. * if the ground has been updated.
  30536. * This can be used in the render loop
  30537. */
  30538. GroundMesh.prototype.updateCoordinateHeights = function () {
  30539. if (!this._heightQuads || this._heightQuads.length == 0) {
  30540. this._initHeightQuads();
  30541. }
  30542. this._computeHeightQuads();
  30543. };
  30544. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  30545. GroundMesh.prototype._getFacetAt = function (x, z) {
  30546. // retrieve col and row from x, z coordinates in the ground local system
  30547. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  30548. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  30549. var quad = this._heightQuads[row * this._subdivisions + col];
  30550. var facet;
  30551. if (z < quad.slope.x * x + quad.slope.y) {
  30552. facet = quad.facet1;
  30553. }
  30554. else {
  30555. facet = quad.facet2;
  30556. }
  30557. return facet;
  30558. };
  30559. // Creates and populates the heightMap array with "facet" elements :
  30560. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  30561. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  30562. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  30563. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  30564. GroundMesh.prototype._initHeightQuads = function () {
  30565. this._heightQuads = new Array();
  30566. for (var row = 0; row < this._subdivisions; row++) {
  30567. for (var col = 0; col < this._subdivisions; col++) {
  30568. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  30569. this._heightQuads[row * this._subdivisions + col] = quad;
  30570. }
  30571. }
  30572. };
  30573. // Compute each quad element values and update the the heightMap array :
  30574. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  30575. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  30576. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  30577. GroundMesh.prototype._computeHeightQuads = function () {
  30578. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30579. var v1 = BABYLON.Tmp.Vector3[0];
  30580. var v2 = BABYLON.Tmp.Vector3[1];
  30581. var v3 = BABYLON.Tmp.Vector3[2];
  30582. var v4 = BABYLON.Tmp.Vector3[3];
  30583. var v1v2 = BABYLON.Tmp.Vector3[4];
  30584. var v1v3 = BABYLON.Tmp.Vector3[5];
  30585. var v1v4 = BABYLON.Tmp.Vector3[6];
  30586. var norm1 = BABYLON.Tmp.Vector3[7];
  30587. var norm2 = BABYLON.Tmp.Vector3[8];
  30588. var i = 0;
  30589. var j = 0;
  30590. var k = 0;
  30591. var cd = 0; // 2D slope coefficient : z = cd * x + h
  30592. var h = 0;
  30593. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  30594. var d2 = 0;
  30595. for (var row = 0; row < this._subdivisions; row++) {
  30596. for (var col = 0; col < this._subdivisions; col++) {
  30597. i = col * 3;
  30598. j = row * (this._subdivisions + 1) * 3;
  30599. k = (row + 1) * (this._subdivisions + 1) * 3;
  30600. v1.x = positions[j + i];
  30601. v1.y = positions[j + i + 1];
  30602. v1.z = positions[j + i + 2];
  30603. v2.x = positions[j + i + 3];
  30604. v2.y = positions[j + i + 4];
  30605. v2.z = positions[j + i + 5];
  30606. v3.x = positions[k + i];
  30607. v3.y = positions[k + i + 1];
  30608. v3.z = positions[k + i + 2];
  30609. v4.x = positions[k + i + 3];
  30610. v4.y = positions[k + i + 4];
  30611. v4.z = positions[k + i + 5];
  30612. // 2D slope V1V4
  30613. cd = (v4.z - v1.z) / (v4.x - v1.x);
  30614. h = v1.z - cd * v1.x; // v1 belongs to the slope
  30615. // facet equations :
  30616. // we compute each facet normal vector
  30617. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  30618. // we compute the value d by applying the equation to v1 which belongs to the plane
  30619. // then we store the facet equation in a Vector4
  30620. v2.subtractToRef(v1, v1v2);
  30621. v3.subtractToRef(v1, v1v3);
  30622. v4.subtractToRef(v1, v1v4);
  30623. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  30624. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  30625. norm1.normalize();
  30626. norm2.normalize();
  30627. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  30628. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  30629. var quad = this._heightQuads[row * this._subdivisions + col];
  30630. quad.slope.copyFromFloats(cd, h);
  30631. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  30632. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  30633. }
  30634. }
  30635. };
  30636. return GroundMesh;
  30637. })(BABYLON.Mesh);
  30638. BABYLON.GroundMesh = GroundMesh;
  30639. })(BABYLON || (BABYLON = {}));
  30640. var BABYLON;
  30641. (function (BABYLON) {
  30642. var LinesMesh = (function (_super) {
  30643. __extends(LinesMesh, _super);
  30644. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  30645. if (parent === void 0) { parent = null; }
  30646. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  30647. this.color = new BABYLON.Color3(1, 1, 1);
  30648. this.alpha = 1;
  30649. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  30650. attributes: ["position"],
  30651. uniforms: ["worldViewProjection", "color"],
  30652. needAlphaBlending: true
  30653. });
  30654. }
  30655. Object.defineProperty(LinesMesh.prototype, "material", {
  30656. get: function () {
  30657. return this._colorShader;
  30658. },
  30659. enumerable: true,
  30660. configurable: true
  30661. });
  30662. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  30663. get: function () {
  30664. return false;
  30665. },
  30666. enumerable: true,
  30667. configurable: true
  30668. });
  30669. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  30670. get: function () {
  30671. return false;
  30672. },
  30673. enumerable: true,
  30674. configurable: true
  30675. });
  30676. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  30677. var engine = this.getScene().getEngine();
  30678. var indexToBind = this._geometry.getIndexBuffer();
  30679. // VBOs
  30680. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  30681. // Color
  30682. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  30683. };
  30684. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  30685. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  30686. return;
  30687. }
  30688. var engine = this.getScene().getEngine();
  30689. // Draw order
  30690. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  30691. };
  30692. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  30693. return null;
  30694. };
  30695. LinesMesh.prototype.dispose = function (doNotRecurse) {
  30696. this._colorShader.dispose();
  30697. _super.prototype.dispose.call(this, doNotRecurse);
  30698. };
  30699. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  30700. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  30701. };
  30702. return LinesMesh;
  30703. })(BABYLON.Mesh);
  30704. BABYLON.LinesMesh = LinesMesh;
  30705. })(BABYLON || (BABYLON = {}));
  30706. var BABYLON;
  30707. (function (BABYLON) {
  30708. var DebugLayer = (function () {
  30709. function DebugLayer(scene) {
  30710. var _this = this;
  30711. this._transformationMatrix = BABYLON.Matrix.Identity();
  30712. this._enabled = false;
  30713. this._labelsEnabled = false;
  30714. this._displayStatistics = true;
  30715. this._displayTree = false;
  30716. this._displayLogs = false;
  30717. this._skeletonViewers = new Array();
  30718. this._identityMatrix = BABYLON.Matrix.Identity();
  30719. this.axisRatio = 0.02;
  30720. this.accentColor = "orange";
  30721. this._scene = scene;
  30722. this._syncPositions = function () {
  30723. var engine = _this._scene.getEngine();
  30724. var canvasRect = engine.getRenderingCanvasClientRect();
  30725. if (_this._showUI) {
  30726. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30727. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30728. _this._statsDiv.style.width = "400px";
  30729. _this._statsDiv.style.height = "auto";
  30730. _this._statsSubsetDiv.style.maxHeight = "240px";
  30731. _this._optionsDiv.style.left = "0px";
  30732. _this._optionsDiv.style.top = "10px";
  30733. _this._optionsDiv.style.width = "200px";
  30734. _this._optionsDiv.style.height = "auto";
  30735. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30736. _this._logDiv.style.left = "0px";
  30737. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30738. _this._logDiv.style.width = "600px";
  30739. _this._logDiv.style.height = "160px";
  30740. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30741. _this._treeDiv.style.top = "10px";
  30742. _this._treeDiv.style.width = "300px";
  30743. _this._treeDiv.style.height = "auto";
  30744. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30745. }
  30746. _this._globalDiv.style.left = canvasRect.left + "px";
  30747. _this._globalDiv.style.top = canvasRect.top + "px";
  30748. _this._drawingCanvas.style.left = "0px";
  30749. _this._drawingCanvas.style.top = "0px";
  30750. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30751. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30752. var devicePixelRatio = window.devicePixelRatio || 1;
  30753. var context = _this._drawingContext;
  30754. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30755. context.mozBackingStorePixelRatio ||
  30756. context.msBackingStorePixelRatio ||
  30757. context.oBackingStorePixelRatio ||
  30758. context.backingStorePixelRatio || 1;
  30759. _this._ratio = devicePixelRatio / backingStoreRatio;
  30760. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30761. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30762. };
  30763. this._onCanvasClick = function (evt) {
  30764. _this._clickPosition = {
  30765. x: evt.clientX * _this._ratio,
  30766. y: evt.clientY * _this._ratio
  30767. };
  30768. };
  30769. this._syncUI = function () {
  30770. if (_this._showUI) {
  30771. if (_this._displayStatistics) {
  30772. _this._displayStats();
  30773. _this._statsDiv.style.display = "";
  30774. }
  30775. else {
  30776. _this._statsDiv.style.display = "none";
  30777. }
  30778. if (_this._displayLogs) {
  30779. _this._logDiv.style.display = "";
  30780. }
  30781. else {
  30782. _this._logDiv.style.display = "none";
  30783. }
  30784. if (_this._displayTree) {
  30785. _this._treeDiv.style.display = "";
  30786. if (_this._needToRefreshMeshesTree) {
  30787. _this._needToRefreshMeshesTree = false;
  30788. _this._refreshMeshesTreeContent();
  30789. }
  30790. }
  30791. else {
  30792. _this._treeDiv.style.display = "none";
  30793. }
  30794. }
  30795. };
  30796. this._syncData = function () {
  30797. if (_this._labelsEnabled || !_this._showUI) {
  30798. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30799. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30800. var engine = _this._scene.getEngine();
  30801. var viewport = _this._camera.viewport;
  30802. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  30803. // Meshes
  30804. var meshes = _this._camera.getActiveMeshes();
  30805. var index;
  30806. var projectedPosition;
  30807. for (index = 0; index < meshes.length; index++) {
  30808. var mesh = meshes.data[index];
  30809. var position = mesh.getBoundingInfo().boundingSphere.center;
  30810. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30811. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30812. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30813. }
  30814. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30815. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30816. }
  30817. }
  30818. // Cameras
  30819. var cameras = _this._scene.cameras;
  30820. for (index = 0; index < cameras.length; index++) {
  30821. var camera = cameras[index];
  30822. if (camera === _this._camera) {
  30823. continue;
  30824. }
  30825. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30826. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30827. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30828. _this._camera.detachControl(engine.getRenderingCanvas());
  30829. _this._camera = camera;
  30830. _this._camera.attachControl(engine.getRenderingCanvas());
  30831. }, function () { return "purple"; });
  30832. }
  30833. }
  30834. // Lights
  30835. var lights = _this._scene.lights;
  30836. for (index = 0; index < lights.length; index++) {
  30837. var light = lights[index];
  30838. if (light.position) {
  30839. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30840. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30841. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30842. light.setEnabled(!light.isEnabled());
  30843. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30844. }
  30845. }
  30846. }
  30847. }
  30848. _this._clickPosition = undefined;
  30849. };
  30850. }
  30851. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30852. while (this._treeSubsetDiv.hasChildNodes()) {
  30853. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30854. }
  30855. // Add meshes
  30856. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30857. sortedArray.sort(function (a, b) {
  30858. if (a.name === b.name) {
  30859. return 0;
  30860. }
  30861. return (a.name > b.name) ? 1 : -1;
  30862. });
  30863. for (var index = 0; index < sortedArray.length; index++) {
  30864. var mesh = sortedArray[index];
  30865. if (!mesh.isEnabled()) {
  30866. continue;
  30867. }
  30868. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30869. m.isVisible = element.checked;
  30870. }, mesh);
  30871. }
  30872. };
  30873. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30874. this._drawingContext.beginPath();
  30875. this._drawingContext.moveTo(zero.x, zero.y);
  30876. this._drawingContext.lineTo(unit.x, unit.y);
  30877. this._drawingContext.strokeStyle = color;
  30878. this._drawingContext.lineWidth = 4;
  30879. this._drawingContext.stroke();
  30880. this._drawingContext.font = "normal 14px Segoe UI";
  30881. this._drawingContext.fillStyle = color;
  30882. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30883. };
  30884. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30885. var position = mesh.getBoundingInfo().boundingSphere.center;
  30886. var worldMatrix = mesh.getWorldMatrix();
  30887. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30888. var unit = (unprojectedVector.subtract(position)).length();
  30889. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30890. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30891. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30892. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30893. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30894. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30895. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30896. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30897. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30898. };
  30899. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30900. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30901. this._drawingContext.font = "normal 12px Segoe UI";
  30902. var textMetrics = this._drawingContext.measureText(text);
  30903. var centerX = projectedPosition.x - textMetrics.width / 2;
  30904. var centerY = projectedPosition.y;
  30905. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30906. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30907. onClick();
  30908. }
  30909. this._drawingContext.beginPath();
  30910. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30911. this._drawingContext.fillStyle = getFillStyle();
  30912. this._drawingContext.globalAlpha = 0.5;
  30913. this._drawingContext.fill();
  30914. this._drawingContext.globalAlpha = 1.0;
  30915. this._drawingContext.strokeStyle = '#FFFFFF';
  30916. this._drawingContext.lineWidth = 1;
  30917. this._drawingContext.stroke();
  30918. this._drawingContext.fillStyle = "#FFFFFF";
  30919. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30920. this._drawingContext.beginPath();
  30921. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30922. this._drawingContext.fill();
  30923. }
  30924. };
  30925. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30926. if (!this._clickPosition) {
  30927. return false;
  30928. }
  30929. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30930. return false;
  30931. }
  30932. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30933. return false;
  30934. }
  30935. return true;
  30936. };
  30937. DebugLayer.prototype.isVisible = function () {
  30938. return this._enabled;
  30939. };
  30940. DebugLayer.prototype.hide = function () {
  30941. if (!this._enabled) {
  30942. return;
  30943. }
  30944. this._enabled = false;
  30945. var engine = this._scene.getEngine();
  30946. this._scene.unregisterBeforeRender(this._syncData);
  30947. this._scene.unregisterAfterRender(this._syncUI);
  30948. this._rootElement.removeChild(this._globalDiv);
  30949. this._scene.forceShowBoundingBoxes = false;
  30950. this._scene.forceWireframe = false;
  30951. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30952. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30953. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30954. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30955. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30956. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30957. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30958. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  30959. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  30960. this._scene.shadowsEnabled = true;
  30961. this._scene.particlesEnabled = true;
  30962. this._scene.postProcessesEnabled = true;
  30963. this._scene.collisionsEnabled = true;
  30964. this._scene.lightsEnabled = true;
  30965. this._scene.texturesEnabled = true;
  30966. this._scene.lensFlaresEnabled = true;
  30967. this._scene.proceduralTexturesEnabled = true;
  30968. this._scene.renderTargetsEnabled = true;
  30969. this._scene.probesEnabled = true;
  30970. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30971. this._clearSkeletonViewers();
  30972. };
  30973. DebugLayer.prototype._clearSkeletonViewers = function () {
  30974. for (var index = 0; index < this._skeletonViewers.length; index++) {
  30975. this._skeletonViewers[index].dispose();
  30976. }
  30977. this._skeletonViewers = [];
  30978. };
  30979. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  30980. if (showUI === void 0) { showUI = true; }
  30981. if (camera === void 0) { camera = null; }
  30982. if (rootElement === void 0) { rootElement = null; }
  30983. if (this._enabled) {
  30984. return;
  30985. }
  30986. this._enabled = true;
  30987. if (camera) {
  30988. this._camera = camera;
  30989. }
  30990. else {
  30991. this._camera = this._scene.activeCamera;
  30992. }
  30993. this._showUI = showUI;
  30994. var engine = this._scene.getEngine();
  30995. this._globalDiv = document.createElement("div");
  30996. this._rootElement = rootElement || document.body;
  30997. this._rootElement.appendChild(this._globalDiv);
  30998. this._generateDOMelements();
  30999. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  31000. this._syncPositions();
  31001. this._scene.registerBeforeRender(this._syncData);
  31002. this._scene.registerAfterRender(this._syncUI);
  31003. };
  31004. DebugLayer.prototype._clearLabels = function () {
  31005. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  31006. for (var index = 0; index < this._scene.meshes.length; index++) {
  31007. var mesh = this._scene.meshes[index];
  31008. mesh.renderOverlay = false;
  31009. }
  31010. };
  31011. DebugLayer.prototype._generateheader = function (root, text) {
  31012. var header = document.createElement("div");
  31013. header.innerHTML = text + "&nbsp;";
  31014. header.style.textAlign = "right";
  31015. header.style.width = "100%";
  31016. header.style.color = "white";
  31017. header.style.backgroundColor = "Black";
  31018. header.style.padding = "5px 5px 4px 0px";
  31019. header.style.marginLeft = "-5px";
  31020. header.style.fontWeight = "bold";
  31021. root.appendChild(header);
  31022. };
  31023. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  31024. var label = document.createElement("label");
  31025. label.innerHTML = title;
  31026. label.style.color = color;
  31027. root.appendChild(label);
  31028. root.appendChild(document.createElement("br"));
  31029. };
  31030. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  31031. if (tag === void 0) { tag = null; }
  31032. var label = document.createElement("label");
  31033. var boundingBoxesCheckbox = document.createElement("input");
  31034. boundingBoxesCheckbox.type = "checkbox";
  31035. boundingBoxesCheckbox.checked = initialState;
  31036. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  31037. task(evt.target, tag);
  31038. });
  31039. label.appendChild(boundingBoxesCheckbox);
  31040. var container = document.createElement("span");
  31041. var leftPart = document.createElement("span");
  31042. var rightPart = document.createElement("span");
  31043. rightPart.style.cssFloat = "right";
  31044. leftPart.innerHTML = leftTitle;
  31045. rightPart.innerHTML = rightTitle;
  31046. rightPart.style.fontSize = "12px";
  31047. rightPart.style.maxWidth = "200px";
  31048. container.appendChild(leftPart);
  31049. container.appendChild(rightPart);
  31050. label.appendChild(container);
  31051. root.appendChild(label);
  31052. root.appendChild(document.createElement("br"));
  31053. };
  31054. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  31055. if (tag === void 0) { tag = null; }
  31056. var label = document.createElement("label");
  31057. var checkBox = document.createElement("input");
  31058. checkBox.type = "checkbox";
  31059. checkBox.checked = initialState;
  31060. checkBox.addEventListener("change", function (evt) {
  31061. task(evt.target, tag);
  31062. });
  31063. label.appendChild(checkBox);
  31064. label.appendChild(document.createTextNode(title));
  31065. root.appendChild(label);
  31066. root.appendChild(document.createElement("br"));
  31067. };
  31068. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  31069. if (tag === void 0) { tag = null; }
  31070. var button = document.createElement("button");
  31071. button.innerHTML = title;
  31072. button.style.height = "24px";
  31073. button.style.width = "150px";
  31074. button.style.marginBottom = "5px";
  31075. button.style.color = "#444444";
  31076. button.style.border = "1px solid white";
  31077. button.className = "debugLayerButton";
  31078. button.addEventListener("click", function (evt) {
  31079. task(evt.target, tag);
  31080. });
  31081. root.appendChild(button);
  31082. root.appendChild(document.createElement("br"));
  31083. };
  31084. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  31085. if (tag === void 0) { tag = null; }
  31086. var label = document.createElement("label");
  31087. var boundingBoxesRadio = document.createElement("input");
  31088. boundingBoxesRadio.type = "radio";
  31089. boundingBoxesRadio.name = name;
  31090. boundingBoxesRadio.checked = initialState;
  31091. boundingBoxesRadio.addEventListener("change", function (evt) {
  31092. task(evt.target, tag);
  31093. });
  31094. label.appendChild(boundingBoxesRadio);
  31095. label.appendChild(document.createTextNode(title));
  31096. root.appendChild(label);
  31097. root.appendChild(document.createElement("br"));
  31098. };
  31099. DebugLayer.prototype._generateDOMelements = function () {
  31100. var _this = this;
  31101. this._globalDiv.id = "DebugLayer";
  31102. this._globalDiv.style.position = "absolute";
  31103. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  31104. this._globalDiv.style.fontSize = "14px";
  31105. this._globalDiv.style.color = "white";
  31106. // Drawing canvas
  31107. this._drawingCanvas = document.createElement("canvas");
  31108. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  31109. this._drawingCanvas.style.position = "absolute";
  31110. this._drawingCanvas.style.pointerEvents = "none";
  31111. this._drawingCanvas.style.backgroundColor = "transparent";
  31112. this._drawingContext = this._drawingCanvas.getContext("2d");
  31113. this._globalDiv.appendChild(this._drawingCanvas);
  31114. if (this._showUI) {
  31115. var background = "rgba(128, 128, 128, 0.4)";
  31116. var border = "rgb(180, 180, 180) solid 1px";
  31117. // Stats
  31118. this._statsDiv = document.createElement("div");
  31119. this._statsDiv.id = "DebugLayerStats";
  31120. this._statsDiv.style.border = border;
  31121. this._statsDiv.style.position = "absolute";
  31122. this._statsDiv.style.background = background;
  31123. this._statsDiv.style.padding = "0px 0px 0px 5px";
  31124. this._generateheader(this._statsDiv, "STATISTICS");
  31125. this._statsSubsetDiv = document.createElement("div");
  31126. this._statsSubsetDiv.style.paddingTop = "5px";
  31127. this._statsSubsetDiv.style.paddingBottom = "5px";
  31128. this._statsSubsetDiv.style.overflowY = "auto";
  31129. this._statsDiv.appendChild(this._statsSubsetDiv);
  31130. // Tree
  31131. this._treeDiv = document.createElement("div");
  31132. this._treeDiv.id = "DebugLayerTree";
  31133. this._treeDiv.style.border = border;
  31134. this._treeDiv.style.position = "absolute";
  31135. this._treeDiv.style.background = background;
  31136. this._treeDiv.style.padding = "0px 0px 0px 5px";
  31137. this._treeDiv.style.display = "none";
  31138. this._generateheader(this._treeDiv, "MESHES TREE");
  31139. this._treeSubsetDiv = document.createElement("div");
  31140. this._treeSubsetDiv.style.paddingTop = "5px";
  31141. this._treeSubsetDiv.style.paddingRight = "5px";
  31142. this._treeSubsetDiv.style.overflowY = "auto";
  31143. this._treeSubsetDiv.style.maxHeight = "300px";
  31144. this._treeDiv.appendChild(this._treeSubsetDiv);
  31145. this._needToRefreshMeshesTree = true;
  31146. // Logs
  31147. this._logDiv = document.createElement("div");
  31148. this._logDiv.style.border = border;
  31149. this._logDiv.id = "DebugLayerLogs";
  31150. this._logDiv.style.position = "absolute";
  31151. this._logDiv.style.background = background;
  31152. this._logDiv.style.padding = "0px 0px 0px 5px";
  31153. this._logDiv.style.display = "none";
  31154. this._generateheader(this._logDiv, "LOGS");
  31155. this._logSubsetDiv = document.createElement("div");
  31156. this._logSubsetDiv.style.height = "127px";
  31157. this._logSubsetDiv.style.paddingTop = "5px";
  31158. this._logSubsetDiv.style.overflowY = "auto";
  31159. this._logSubsetDiv.style.fontSize = "12px";
  31160. this._logSubsetDiv.style.fontFamily = "consolas";
  31161. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  31162. this._logDiv.appendChild(this._logSubsetDiv);
  31163. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  31164. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  31165. };
  31166. // Options
  31167. this._optionsDiv = document.createElement("div");
  31168. this._optionsDiv.id = "DebugLayerOptions";
  31169. this._optionsDiv.style.border = border;
  31170. this._optionsDiv.style.position = "absolute";
  31171. this._optionsDiv.style.background = background;
  31172. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  31173. this._optionsDiv.style.overflowY = "auto";
  31174. this._generateheader(this._optionsDiv, "OPTIONS");
  31175. this._optionsSubsetDiv = document.createElement("div");
  31176. this._optionsSubsetDiv.style.paddingTop = "5px";
  31177. this._optionsSubsetDiv.style.paddingBottom = "5px";
  31178. this._optionsSubsetDiv.style.overflowY = "auto";
  31179. this._optionsSubsetDiv.style.maxHeight = "200px";
  31180. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  31181. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  31182. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  31183. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  31184. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  31185. _this._displayTree = element.checked;
  31186. _this._needToRefreshMeshesTree = true;
  31187. });
  31188. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31189. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  31190. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  31191. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  31192. _this._labelsEnabled = element.checked;
  31193. if (!_this._labelsEnabled) {
  31194. _this._clearLabels();
  31195. }
  31196. });
  31197. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  31198. if (element.checked) {
  31199. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  31200. }
  31201. else {
  31202. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  31203. }
  31204. });
  31205. ;
  31206. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31207. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  31208. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  31209. if (element.checked) {
  31210. _this._scene.forceWireframe = false;
  31211. _this._scene.forcePointsCloud = false;
  31212. }
  31213. });
  31214. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  31215. if (element.checked) {
  31216. _this._scene.forceWireframe = true;
  31217. _this._scene.forcePointsCloud = false;
  31218. }
  31219. });
  31220. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  31221. if (element.checked) {
  31222. _this._scene.forceWireframe = false;
  31223. _this._scene.forcePointsCloud = true;
  31224. }
  31225. });
  31226. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31227. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  31228. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  31229. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  31230. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  31231. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  31232. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  31233. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  31234. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  31235. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  31236. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  31237. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  31238. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31239. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  31240. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  31241. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  31242. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  31243. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  31244. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  31245. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  31246. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  31247. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  31248. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  31249. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  31250. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  31251. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  31252. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  31253. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  31254. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  31255. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31256. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  31257. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  31258. if (element.checked) {
  31259. _this._scene.headphone = true;
  31260. }
  31261. });
  31262. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  31263. if (element.checked) {
  31264. _this._scene.headphone = false;
  31265. }
  31266. });
  31267. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31268. _this._scene.audioEnabled = !element.checked;
  31269. });
  31270. }
  31271. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31272. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  31273. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  31274. if (!element.checked) {
  31275. _this._clearSkeletonViewers();
  31276. return;
  31277. }
  31278. for (var index = 0; index < _this._scene.meshes.length; index++) {
  31279. var mesh = _this._scene.meshes[index];
  31280. if (mesh.skeleton) {
  31281. var found = false;
  31282. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  31283. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  31284. found = true;
  31285. break;
  31286. }
  31287. }
  31288. if (found) {
  31289. continue;
  31290. }
  31291. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  31292. viewer.isEnabled = true;
  31293. _this._skeletonViewers.push(viewer);
  31294. }
  31295. }
  31296. });
  31297. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31298. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31299. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31300. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  31301. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  31302. if (_this._camera) {
  31303. console.log(_this._camera);
  31304. }
  31305. else {
  31306. console.warn("No camera defined, or debug layer created before camera creation!");
  31307. }
  31308. });
  31309. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31310. this._globalDiv.appendChild(this._statsDiv);
  31311. this._globalDiv.appendChild(this._logDiv);
  31312. this._globalDiv.appendChild(this._optionsDiv);
  31313. this._globalDiv.appendChild(this._treeDiv);
  31314. }
  31315. };
  31316. DebugLayer.prototype._displayStats = function () {
  31317. var scene = this._scene;
  31318. var engine = scene.getEngine();
  31319. var glInfo = engine.getGlInfo();
  31320. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31321. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31322. + "<b>Count</b><br>"
  31323. + "Total meshes: " + scene.meshes.length + "<br>"
  31324. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31325. + "Total materials: " + scene.materials.length + "<br>"
  31326. + "Total textures: " + scene.textures.length + "<br>"
  31327. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31328. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31329. + "Active bones: " + scene.getActiveBones() + "<br>"
  31330. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31331. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  31332. + "<b>Duration</b><br>"
  31333. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31334. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31335. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31336. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31337. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31338. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31339. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  31340. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  31341. + "</div>"
  31342. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31343. + "<b>Extensions</b><br>"
  31344. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31345. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31346. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31347. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  31348. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31349. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  31350. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  31351. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  31352. + "</div><br>"
  31353. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31354. + "<b>Caps.</b><br>"
  31355. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31356. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31357. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  31358. + "<b>Info</b><br>"
  31359. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  31360. + glInfo.version + "<br>"
  31361. + "</div><br>"
  31362. + glInfo.renderer + "<br>";
  31363. if (this.customStatsFunction) {
  31364. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31365. }
  31366. };
  31367. return DebugLayer;
  31368. })();
  31369. BABYLON.DebugLayer = DebugLayer;
  31370. })(BABYLON || (BABYLON = {}));
  31371. var BABYLON;
  31372. (function (BABYLON) {
  31373. var DefaultLoadingScreen = (function () {
  31374. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  31375. var _this = this;
  31376. if (_loadingText === void 0) { _loadingText = ""; }
  31377. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  31378. this._renderingCanvas = _renderingCanvas;
  31379. this._loadingText = _loadingText;
  31380. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  31381. // Resize
  31382. this._resizeLoadingUI = function () {
  31383. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  31384. _this._loadingDiv.style.position = "absolute";
  31385. _this._loadingDiv.style.left = canvasRect.left + "px";
  31386. _this._loadingDiv.style.top = canvasRect.top + "px";
  31387. _this._loadingDiv.style.width = canvasRect.width + "px";
  31388. _this._loadingDiv.style.height = canvasRect.height + "px";
  31389. };
  31390. }
  31391. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  31392. var _this = this;
  31393. if (this._loadingDiv) {
  31394. // Do not add a loading screen if there is already one
  31395. return;
  31396. }
  31397. this._loadingDiv = document.createElement("div");
  31398. this._loadingDiv.id = "babylonjsLoadingDiv";
  31399. this._loadingDiv.style.opacity = "0";
  31400. this._loadingDiv.style.transition = "opacity 1.5s ease";
  31401. // Loading text
  31402. this._loadingTextDiv = document.createElement("div");
  31403. this._loadingTextDiv.style.position = "absolute";
  31404. this._loadingTextDiv.style.left = "0";
  31405. this._loadingTextDiv.style.top = "50%";
  31406. this._loadingTextDiv.style.marginTop = "80px";
  31407. this._loadingTextDiv.style.width = "100%";
  31408. this._loadingTextDiv.style.height = "20px";
  31409. this._loadingTextDiv.style.fontFamily = "Arial";
  31410. this._loadingTextDiv.style.fontSize = "14px";
  31411. this._loadingTextDiv.style.color = "white";
  31412. this._loadingTextDiv.style.textAlign = "center";
  31413. this._loadingTextDiv.innerHTML = "Loading";
  31414. this._loadingDiv.appendChild(this._loadingTextDiv);
  31415. //set the predefined text
  31416. this._loadingTextDiv.innerHTML = this._loadingText;
  31417. // Loading img
  31418. var imgBack = new Image();
  31419. 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==";
  31420. imgBack.style.position = "absolute";
  31421. imgBack.style.left = "50%";
  31422. imgBack.style.top = "50%";
  31423. imgBack.style.marginLeft = "-50px";
  31424. imgBack.style.marginTop = "-50px";
  31425. imgBack.style.transition = "transform 1.0s ease";
  31426. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  31427. var deg = 360;
  31428. var onTransitionEnd = function () {
  31429. deg += 360;
  31430. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  31431. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  31432. };
  31433. imgBack.addEventListener("transitionend", onTransitionEnd);
  31434. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  31435. this._loadingDiv.appendChild(imgBack);
  31436. // front image
  31437. var imgFront = new Image();
  31438. 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=";
  31439. imgFront.style.position = "absolute";
  31440. imgFront.style.left = "50%";
  31441. imgFront.style.top = "50%";
  31442. imgFront.style.marginLeft = "-50px";
  31443. imgFront.style.marginTop = "-50px";
  31444. this._loadingDiv.appendChild(imgFront);
  31445. this._resizeLoadingUI();
  31446. window.addEventListener("resize", this._resizeLoadingUI);
  31447. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  31448. document.body.appendChild(this._loadingDiv);
  31449. setTimeout(function () {
  31450. _this._loadingDiv.style.opacity = "1";
  31451. imgBack.style.transform = "rotateZ(360deg)";
  31452. imgBack.style.webkitTransform = "rotateZ(360deg)";
  31453. }, 0);
  31454. };
  31455. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  31456. var _this = this;
  31457. if (!this._loadingDiv) {
  31458. return;
  31459. }
  31460. var onTransitionEnd = function () {
  31461. if (!_this._loadingDiv) {
  31462. return;
  31463. }
  31464. document.body.removeChild(_this._loadingDiv);
  31465. window.removeEventListener("resize", _this._resizeLoadingUI);
  31466. _this._loadingDiv = null;
  31467. };
  31468. this._loadingDiv.style.opacity = "0";
  31469. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  31470. };
  31471. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  31472. set: function (text) {
  31473. this._loadingText = text;
  31474. if (this._loadingTextDiv) {
  31475. this._loadingTextDiv.innerHTML = this._loadingText;
  31476. }
  31477. },
  31478. enumerable: true,
  31479. configurable: true
  31480. });
  31481. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  31482. get: function () {
  31483. return this._loadingDivBackgroundColor;
  31484. },
  31485. set: function (color) {
  31486. this._loadingDivBackgroundColor = color;
  31487. if (!this._loadingDiv) {
  31488. return;
  31489. }
  31490. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  31491. },
  31492. enumerable: true,
  31493. configurable: true
  31494. });
  31495. return DefaultLoadingScreen;
  31496. })();
  31497. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  31498. })(BABYLON || (BABYLON = {}));
  31499. var BABYLON;
  31500. (function (BABYLON) {
  31501. var AudioEngine = (function () {
  31502. function AudioEngine() {
  31503. this._audioContext = null;
  31504. this._audioContextInitialized = false;
  31505. this.canUseWebAudio = false;
  31506. this.WarnedWebAudioUnsupported = false;
  31507. this.unlocked = false;
  31508. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  31509. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  31510. this.canUseWebAudio = true;
  31511. }
  31512. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  31513. this._unlockiOSaudio();
  31514. }
  31515. else {
  31516. this.unlocked = true;
  31517. }
  31518. }
  31519. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  31520. get: function () {
  31521. if (!this._audioContextInitialized) {
  31522. this._initializeAudioContext();
  31523. }
  31524. return this._audioContext;
  31525. },
  31526. enumerable: true,
  31527. configurable: true
  31528. });
  31529. AudioEngine.prototype._unlockiOSaudio = function () {
  31530. var _this = this;
  31531. var unlockaudio = function () {
  31532. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  31533. var source = _this.audioContext.createBufferSource();
  31534. source.buffer = buffer;
  31535. source.connect(_this.audioContext.destination);
  31536. source.start(0);
  31537. setTimeout(function () {
  31538. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  31539. _this.unlocked = true;
  31540. window.removeEventListener('touchend', unlockaudio, false);
  31541. if (_this.onAudioUnlocked) {
  31542. _this.onAudioUnlocked();
  31543. }
  31544. }
  31545. }, 0);
  31546. };
  31547. window.addEventListener('touchend', unlockaudio, false);
  31548. };
  31549. AudioEngine.prototype._initializeAudioContext = function () {
  31550. try {
  31551. if (this.canUseWebAudio) {
  31552. this._audioContext = new AudioContext();
  31553. // create a global volume gain node
  31554. this.masterGain = this._audioContext.createGain();
  31555. this.masterGain.gain.value = 1;
  31556. this.masterGain.connect(this._audioContext.destination);
  31557. this._audioContextInitialized = true;
  31558. }
  31559. }
  31560. catch (e) {
  31561. this.canUseWebAudio = false;
  31562. BABYLON.Tools.Error("Web Audio: " + e.message);
  31563. }
  31564. };
  31565. AudioEngine.prototype.dispose = function () {
  31566. if (this.canUseWebAudio && this._audioContextInitialized) {
  31567. if (this._connectedAnalyser) {
  31568. this._connectedAnalyser.stopDebugCanvas();
  31569. this._connectedAnalyser.dispose();
  31570. this.masterGain.disconnect();
  31571. this.masterGain.connect(this._audioContext.destination);
  31572. this._connectedAnalyser = null;
  31573. }
  31574. this.masterGain.gain.value = 1;
  31575. }
  31576. this.WarnedWebAudioUnsupported = false;
  31577. };
  31578. AudioEngine.prototype.getGlobalVolume = function () {
  31579. if (this.canUseWebAudio && this._audioContextInitialized) {
  31580. return this.masterGain.gain.value;
  31581. }
  31582. else {
  31583. return -1;
  31584. }
  31585. };
  31586. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  31587. if (this.canUseWebAudio && this._audioContextInitialized) {
  31588. this.masterGain.gain.value = newVolume;
  31589. }
  31590. };
  31591. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  31592. if (this._connectedAnalyser) {
  31593. this._connectedAnalyser.stopDebugCanvas();
  31594. }
  31595. if (this.canUseWebAudio && this._audioContextInitialized) {
  31596. this._connectedAnalyser = analyser;
  31597. this.masterGain.disconnect();
  31598. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  31599. }
  31600. };
  31601. return AudioEngine;
  31602. })();
  31603. BABYLON.AudioEngine = AudioEngine;
  31604. })(BABYLON || (BABYLON = {}));
  31605. var BABYLON;
  31606. (function (BABYLON) {
  31607. var Sound = (function () {
  31608. /**
  31609. * Create a sound and attach it to a scene
  31610. * @param name Name of your sound
  31611. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  31612. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  31613. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  31614. */
  31615. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  31616. var _this = this;
  31617. this.autoplay = false;
  31618. this.loop = false;
  31619. this.useCustomAttenuation = false;
  31620. this.spatialSound = false;
  31621. this.refDistance = 1;
  31622. this.rolloffFactor = 1;
  31623. this.maxDistance = 100;
  31624. this.distanceModel = "linear";
  31625. this._panningModel = "equalpower";
  31626. this._playbackRate = 1;
  31627. this._streaming = false;
  31628. this._startTime = 0;
  31629. this._startOffset = 0;
  31630. this._position = BABYLON.Vector3.Zero();
  31631. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  31632. this._volume = 1;
  31633. this._isLoaded = false;
  31634. this._isReadyToPlay = false;
  31635. this.isPlaying = false;
  31636. this.isPaused = false;
  31637. this._isDirectional = false;
  31638. // Used if you'd like to create a directional sound.
  31639. // If not set, the sound will be omnidirectional
  31640. this._coneInnerAngle = 360;
  31641. this._coneOuterAngle = 360;
  31642. this._coneOuterGain = 0;
  31643. this._isOutputConnected = false;
  31644. this.name = name;
  31645. this._scene = scene;
  31646. this._readyToPlayCallback = readyToPlayCallback;
  31647. // Default custom attenuation function is a linear attenuation
  31648. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  31649. if (currentDistance < maxDistance) {
  31650. return currentVolume * (1 - currentDistance / maxDistance);
  31651. }
  31652. else {
  31653. return 0;
  31654. }
  31655. };
  31656. if (options) {
  31657. this.autoplay = options.autoplay || false;
  31658. this.loop = options.loop || false;
  31659. // if volume === 0, we need another way to check this option
  31660. if (options.volume !== undefined) {
  31661. this._volume = options.volume;
  31662. }
  31663. this.spatialSound = options.spatialSound || false;
  31664. this.maxDistance = options.maxDistance || 100;
  31665. this.useCustomAttenuation = options.useCustomAttenuation || false;
  31666. this.rolloffFactor = options.rolloffFactor || 1;
  31667. this.refDistance = options.refDistance || 1;
  31668. this.distanceModel = options.distanceModel || "linear";
  31669. this._playbackRate = options.playbackRate || 1;
  31670. this._streaming = options.streaming || false;
  31671. }
  31672. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31673. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  31674. this._soundGain.gain.value = this._volume;
  31675. this._inputAudioNode = this._soundGain;
  31676. this._ouputAudioNode = this._soundGain;
  31677. if (this.spatialSound) {
  31678. this._createSpatialParameters();
  31679. }
  31680. this._scene.mainSoundTrack.AddSound(this);
  31681. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  31682. if (urlOrArrayBuffer) {
  31683. // If it's an URL
  31684. if (typeof (urlOrArrayBuffer) === "string") {
  31685. // Loading sound using XHR2
  31686. if (!this._streaming) {
  31687. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  31688. }
  31689. else {
  31690. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  31691. this._htmlAudioElement.controls = false;
  31692. this._htmlAudioElement.loop = this.loop;
  31693. this._htmlAudioElement.crossOrigin = "anonymous";
  31694. this._htmlAudioElement.preload = "auto";
  31695. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  31696. _this._isReadyToPlay = true;
  31697. if (_this.autoplay) {
  31698. _this.play();
  31699. }
  31700. if (_this._readyToPlayCallback) {
  31701. _this._readyToPlayCallback();
  31702. }
  31703. });
  31704. document.body.appendChild(this._htmlAudioElement);
  31705. }
  31706. }
  31707. else {
  31708. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  31709. if (urlOrArrayBuffer.byteLength > 0) {
  31710. this._soundLoaded(urlOrArrayBuffer);
  31711. }
  31712. }
  31713. else {
  31714. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  31715. }
  31716. }
  31717. }
  31718. }
  31719. else {
  31720. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  31721. this._scene.mainSoundTrack.AddSound(this);
  31722. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  31723. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  31724. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  31725. }
  31726. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  31727. if (this._readyToPlayCallback) {
  31728. window.setTimeout(function () {
  31729. _this._readyToPlayCallback();
  31730. }, 1000);
  31731. }
  31732. }
  31733. }
  31734. Sound.prototype.dispose = function () {
  31735. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  31736. if (this.isPlaying) {
  31737. this.stop();
  31738. }
  31739. this._isReadyToPlay = false;
  31740. if (this.soundTrackId === -1) {
  31741. this._scene.mainSoundTrack.RemoveSound(this);
  31742. }
  31743. else {
  31744. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  31745. }
  31746. if (this._soundGain) {
  31747. this._soundGain.disconnect();
  31748. this._soundGain = null;
  31749. }
  31750. if (this._soundPanner) {
  31751. this._soundPanner.disconnect();
  31752. this._soundPanner = null;
  31753. }
  31754. if (this._soundSource) {
  31755. this._soundSource.disconnect();
  31756. this._soundSource = null;
  31757. }
  31758. this._audioBuffer = null;
  31759. if (this._htmlAudioElement) {
  31760. this._htmlAudioElement.pause();
  31761. this._htmlAudioElement.src = "";
  31762. document.body.removeChild(this._htmlAudioElement);
  31763. }
  31764. if (this._connectedMesh) {
  31765. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  31766. this._connectedMesh = null;
  31767. }
  31768. }
  31769. };
  31770. Sound.prototype._soundLoaded = function (audioData) {
  31771. var _this = this;
  31772. this._isLoaded = true;
  31773. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  31774. _this._audioBuffer = buffer;
  31775. _this._isReadyToPlay = true;
  31776. if (_this.autoplay) {
  31777. _this.play();
  31778. }
  31779. if (_this._readyToPlayCallback) {
  31780. _this._readyToPlayCallback();
  31781. }
  31782. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  31783. };
  31784. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  31785. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31786. this._audioBuffer = audioBuffer;
  31787. this._isReadyToPlay = true;
  31788. }
  31789. };
  31790. Sound.prototype.updateOptions = function (options) {
  31791. if (options) {
  31792. this.loop = options.loop || this.loop;
  31793. this.maxDistance = options.maxDistance || this.maxDistance;
  31794. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  31795. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  31796. this.refDistance = options.refDistance || this.refDistance;
  31797. this.distanceModel = options.distanceModel || this.distanceModel;
  31798. this._playbackRate = options.playbackRate || this._playbackRate;
  31799. this._updateSpatialParameters();
  31800. if (this.isPlaying) {
  31801. if (this._streaming) {
  31802. this._htmlAudioElement.playbackRate = this._playbackRate;
  31803. }
  31804. else {
  31805. this._soundSource.playbackRate.value = this._playbackRate;
  31806. }
  31807. }
  31808. }
  31809. };
  31810. Sound.prototype._createSpatialParameters = function () {
  31811. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31812. if (this._scene.headphone) {
  31813. this._panningModel = "HRTF";
  31814. }
  31815. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  31816. this._updateSpatialParameters();
  31817. this._soundPanner.connect(this._ouputAudioNode);
  31818. this._inputAudioNode = this._soundPanner;
  31819. }
  31820. };
  31821. Sound.prototype._updateSpatialParameters = function () {
  31822. if (this.spatialSound) {
  31823. if (this.useCustomAttenuation) {
  31824. // Tricks to disable in a way embedded Web Audio attenuation
  31825. this._soundPanner.distanceModel = "linear";
  31826. this._soundPanner.maxDistance = Number.MAX_VALUE;
  31827. this._soundPanner.refDistance = 1;
  31828. this._soundPanner.rolloffFactor = 1;
  31829. this._soundPanner.panningModel = this._panningModel;
  31830. }
  31831. else {
  31832. this._soundPanner.distanceModel = this.distanceModel;
  31833. this._soundPanner.maxDistance = this.maxDistance;
  31834. this._soundPanner.refDistance = this.refDistance;
  31835. this._soundPanner.rolloffFactor = this.rolloffFactor;
  31836. this._soundPanner.panningModel = this._panningModel;
  31837. }
  31838. }
  31839. };
  31840. Sound.prototype.switchPanningModelToHRTF = function () {
  31841. this._panningModel = "HRTF";
  31842. this._switchPanningModel();
  31843. };
  31844. Sound.prototype.switchPanningModelToEqualPower = function () {
  31845. this._panningModel = "equalpower";
  31846. this._switchPanningModel();
  31847. };
  31848. Sound.prototype._switchPanningModel = function () {
  31849. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  31850. this._soundPanner.panningModel = this._panningModel;
  31851. }
  31852. };
  31853. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  31854. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31855. if (this._isOutputConnected) {
  31856. this._ouputAudioNode.disconnect();
  31857. }
  31858. this._ouputAudioNode.connect(soundTrackAudioNode);
  31859. this._isOutputConnected = true;
  31860. }
  31861. };
  31862. /**
  31863. * Transform this sound into a directional source
  31864. * @param coneInnerAngle Size of the inner cone in degree
  31865. * @param coneOuterAngle Size of the outer cone in degree
  31866. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  31867. */
  31868. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  31869. if (coneOuterAngle < coneInnerAngle) {
  31870. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  31871. return;
  31872. }
  31873. this._coneInnerAngle = coneInnerAngle;
  31874. this._coneOuterAngle = coneOuterAngle;
  31875. this._coneOuterGain = coneOuterGain;
  31876. this._isDirectional = true;
  31877. if (this.isPlaying && this.loop) {
  31878. this.stop();
  31879. this.play();
  31880. }
  31881. };
  31882. Sound.prototype.setPosition = function (newPosition) {
  31883. this._position = newPosition;
  31884. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  31885. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  31886. }
  31887. };
  31888. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  31889. this._localDirection = newLocalDirection;
  31890. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  31891. this._updateDirection();
  31892. }
  31893. };
  31894. Sound.prototype._updateDirection = function () {
  31895. var mat = this._connectedMesh.getWorldMatrix();
  31896. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  31897. direction.normalize();
  31898. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  31899. };
  31900. Sound.prototype.updateDistanceFromListener = function () {
  31901. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  31902. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  31903. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  31904. }
  31905. };
  31906. Sound.prototype.setAttenuationFunction = function (callback) {
  31907. this._customAttenuationFunction = callback;
  31908. };
  31909. /**
  31910. * Play the sound
  31911. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  31912. */
  31913. Sound.prototype.play = function (time) {
  31914. var _this = this;
  31915. if (this._isReadyToPlay && this._scene.audioEnabled) {
  31916. try {
  31917. if (this._startOffset < 0) {
  31918. time = -this._startOffset;
  31919. this._startOffset = 0;
  31920. }
  31921. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  31922. if (!this._soundSource || !this._streamingSource) {
  31923. if (this.spatialSound) {
  31924. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  31925. if (this._isDirectional) {
  31926. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  31927. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  31928. this._soundPanner.coneOuterGain = this._coneOuterGain;
  31929. if (this._connectedMesh) {
  31930. this._updateDirection();
  31931. }
  31932. else {
  31933. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  31934. }
  31935. }
  31936. }
  31937. }
  31938. if (this._streaming) {
  31939. if (!this._streamingSource) {
  31940. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  31941. this._htmlAudioElement.onended = function () { _this._onended(); };
  31942. this._htmlAudioElement.playbackRate = this._playbackRate;
  31943. }
  31944. this._streamingSource.disconnect();
  31945. this._streamingSource.connect(this._inputAudioNode);
  31946. this._htmlAudioElement.play();
  31947. }
  31948. else {
  31949. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  31950. this._soundSource.buffer = this._audioBuffer;
  31951. this._soundSource.connect(this._inputAudioNode);
  31952. this._soundSource.loop = this.loop;
  31953. this._soundSource.playbackRate.value = this._playbackRate;
  31954. this._soundSource.onended = function () { _this._onended(); };
  31955. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  31956. }
  31957. this._startTime = startTime;
  31958. this.isPlaying = true;
  31959. this.isPaused = false;
  31960. }
  31961. catch (ex) {
  31962. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  31963. }
  31964. }
  31965. };
  31966. Sound.prototype._onended = function () {
  31967. this.isPlaying = false;
  31968. if (this.onended) {
  31969. this.onended();
  31970. }
  31971. };
  31972. /**
  31973. * Stop the sound
  31974. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  31975. */
  31976. Sound.prototype.stop = function (time) {
  31977. if (this.isPlaying) {
  31978. if (this._streaming) {
  31979. this._htmlAudioElement.pause();
  31980. // Test needed for Firefox or it will generate an Invalid State Error
  31981. if (this._htmlAudioElement.currentTime > 0) {
  31982. this._htmlAudioElement.currentTime = 0;
  31983. }
  31984. }
  31985. else {
  31986. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  31987. this._soundSource.stop(stopTime);
  31988. if (!this.isPaused) {
  31989. this._startOffset = 0;
  31990. }
  31991. }
  31992. this.isPlaying = false;
  31993. }
  31994. };
  31995. Sound.prototype.pause = function () {
  31996. if (this.isPlaying) {
  31997. this.isPaused = true;
  31998. if (this._streaming) {
  31999. this._htmlAudioElement.pause();
  32000. }
  32001. else {
  32002. this.stop(0);
  32003. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  32004. }
  32005. }
  32006. };
  32007. Sound.prototype.setVolume = function (newVolume, time) {
  32008. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32009. if (time) {
  32010. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  32011. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  32012. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  32013. }
  32014. else {
  32015. this._soundGain.gain.value = newVolume;
  32016. }
  32017. }
  32018. this._volume = newVolume;
  32019. };
  32020. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  32021. this._playbackRate = newPlaybackRate;
  32022. if (this.isPlaying) {
  32023. if (this._streaming) {
  32024. this._htmlAudioElement.playbackRate = this._playbackRate;
  32025. }
  32026. else {
  32027. this._soundSource.playbackRate.value = this._playbackRate;
  32028. }
  32029. }
  32030. };
  32031. Sound.prototype.getVolume = function () {
  32032. return this._volume;
  32033. };
  32034. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  32035. var _this = this;
  32036. if (this._connectedMesh) {
  32037. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  32038. this._registerFunc = null;
  32039. }
  32040. this._connectedMesh = meshToConnectTo;
  32041. if (!this.spatialSound) {
  32042. this.spatialSound = true;
  32043. this._createSpatialParameters();
  32044. if (this.isPlaying && this.loop) {
  32045. this.stop();
  32046. this.play();
  32047. }
  32048. }
  32049. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  32050. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  32051. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  32052. };
  32053. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  32054. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  32055. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  32056. this._updateDirection();
  32057. }
  32058. };
  32059. Sound.prototype.clone = function () {
  32060. var _this = this;
  32061. if (!this._streaming) {
  32062. var setBufferAndRun = function () {
  32063. if (_this._isReadyToPlay) {
  32064. clonedSound._audioBuffer = _this.getAudioBuffer();
  32065. clonedSound._isReadyToPlay = true;
  32066. if (clonedSound.autoplay) {
  32067. clonedSound.play();
  32068. }
  32069. }
  32070. else {
  32071. window.setTimeout(setBufferAndRun, 300);
  32072. }
  32073. };
  32074. var currentOptions = {
  32075. autoplay: this.autoplay, loop: this.loop,
  32076. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  32077. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  32078. refDistance: this.refDistance, distanceModel: this.distanceModel
  32079. };
  32080. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  32081. if (this.useCustomAttenuation) {
  32082. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  32083. }
  32084. clonedSound.setPosition(this._position);
  32085. clonedSound.setPlaybackRate(this._playbackRate);
  32086. setBufferAndRun();
  32087. return clonedSound;
  32088. }
  32089. else {
  32090. return null;
  32091. }
  32092. };
  32093. Sound.prototype.getAudioBuffer = function () {
  32094. return this._audioBuffer;
  32095. };
  32096. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  32097. var soundName = parsedSound.name;
  32098. var soundUrl;
  32099. if (parsedSound.url) {
  32100. soundUrl = rootUrl + parsedSound.url;
  32101. }
  32102. else {
  32103. soundUrl = rootUrl + soundName;
  32104. }
  32105. var options = {
  32106. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  32107. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  32108. rolloffFactor: parsedSound.rolloffFactor,
  32109. refDistance: parsedSound.refDistance,
  32110. distanceModel: parsedSound.distanceModel,
  32111. playbackRate: parsedSound.playbackRate
  32112. };
  32113. var newSound;
  32114. if (!sourceSound) {
  32115. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  32116. scene._addPendingData(newSound);
  32117. }
  32118. else {
  32119. var setBufferAndRun = function () {
  32120. if (sourceSound._isReadyToPlay) {
  32121. newSound._audioBuffer = sourceSound.getAudioBuffer();
  32122. newSound._isReadyToPlay = true;
  32123. if (newSound.autoplay) {
  32124. newSound.play();
  32125. }
  32126. }
  32127. else {
  32128. window.setTimeout(setBufferAndRun, 300);
  32129. }
  32130. };
  32131. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  32132. setBufferAndRun();
  32133. }
  32134. if (parsedSound.position) {
  32135. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  32136. newSound.setPosition(soundPosition);
  32137. }
  32138. if (parsedSound.isDirectional) {
  32139. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  32140. if (parsedSound.localDirectionToMesh) {
  32141. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  32142. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  32143. }
  32144. }
  32145. if (parsedSound.connectedMeshId) {
  32146. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  32147. if (connectedMesh) {
  32148. newSound.attachToMesh(connectedMesh);
  32149. }
  32150. }
  32151. return newSound;
  32152. };
  32153. return Sound;
  32154. })();
  32155. BABYLON.Sound = Sound;
  32156. })(BABYLON || (BABYLON = {}));
  32157. var BABYLON;
  32158. (function (BABYLON) {
  32159. var SoundTrack = (function () {
  32160. function SoundTrack(scene, options) {
  32161. this.id = -1;
  32162. this._isMainTrack = false;
  32163. this._isInitialized = false;
  32164. this._scene = scene;
  32165. this.soundCollection = new Array();
  32166. this._options = options;
  32167. if (!this._isMainTrack) {
  32168. this._scene.soundTracks.push(this);
  32169. this.id = this._scene.soundTracks.length - 1;
  32170. }
  32171. }
  32172. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  32173. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32174. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  32175. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  32176. if (this._options) {
  32177. if (this._options.volume) {
  32178. this._outputAudioNode.gain.value = this._options.volume;
  32179. }
  32180. if (this._options.mainTrack) {
  32181. this._isMainTrack = this._options.mainTrack;
  32182. }
  32183. }
  32184. this._isInitialized = true;
  32185. }
  32186. };
  32187. SoundTrack.prototype.dispose = function () {
  32188. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32189. if (this._connectedAnalyser) {
  32190. this._connectedAnalyser.stopDebugCanvas();
  32191. }
  32192. while (this.soundCollection.length) {
  32193. this.soundCollection[0].dispose();
  32194. }
  32195. if (this._outputAudioNode) {
  32196. this._outputAudioNode.disconnect();
  32197. }
  32198. this._outputAudioNode = null;
  32199. }
  32200. };
  32201. SoundTrack.prototype.AddSound = function (sound) {
  32202. if (!this._isInitialized) {
  32203. this._initializeSoundTrackAudioGraph();
  32204. }
  32205. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32206. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  32207. }
  32208. if (sound.soundTrackId) {
  32209. if (sound.soundTrackId === -1) {
  32210. this._scene.mainSoundTrack.RemoveSound(sound);
  32211. }
  32212. else {
  32213. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  32214. }
  32215. }
  32216. this.soundCollection.push(sound);
  32217. sound.soundTrackId = this.id;
  32218. };
  32219. SoundTrack.prototype.RemoveSound = function (sound) {
  32220. var index = this.soundCollection.indexOf(sound);
  32221. if (index !== -1) {
  32222. this.soundCollection.splice(index, 1);
  32223. }
  32224. };
  32225. SoundTrack.prototype.setVolume = function (newVolume) {
  32226. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32227. this._outputAudioNode.gain.value = newVolume;
  32228. }
  32229. };
  32230. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  32231. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32232. for (var i = 0; i < this.soundCollection.length; i++) {
  32233. this.soundCollection[i].switchPanningModelToHRTF();
  32234. }
  32235. }
  32236. };
  32237. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  32238. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32239. for (var i = 0; i < this.soundCollection.length; i++) {
  32240. this.soundCollection[i].switchPanningModelToEqualPower();
  32241. }
  32242. }
  32243. };
  32244. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  32245. if (this._connectedAnalyser) {
  32246. this._connectedAnalyser.stopDebugCanvas();
  32247. }
  32248. this._connectedAnalyser = analyser;
  32249. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32250. this._outputAudioNode.disconnect();
  32251. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  32252. }
  32253. };
  32254. return SoundTrack;
  32255. })();
  32256. BABYLON.SoundTrack = SoundTrack;
  32257. })(BABYLON || (BABYLON = {}));
  32258. var BABYLON;
  32259. (function (BABYLON) {
  32260. var SIMDVector3 = (function () {
  32261. function SIMDVector3() {
  32262. }
  32263. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  32264. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  32265. var m0 = SIMD.float32x4.load(transformation.m, 0);
  32266. var m1 = SIMD.float32x4.load(transformation.m, 4);
  32267. var m2 = SIMD.float32x4.load(transformation.m, 8);
  32268. var m3 = SIMD.float32x4.load(transformation.m, 12);
  32269. 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));
  32270. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  32271. SIMD.float32x4.storeXYZ(result._data, 0, r);
  32272. };
  32273. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  32274. var v0 = SIMD.float32x4.splat(x);
  32275. var v1 = SIMD.float32x4.splat(y);
  32276. var v2 = SIMD.float32x4.splat(z);
  32277. var m0 = SIMD.float32x4.load(transformation.m, 0);
  32278. var m1 = SIMD.float32x4.load(transformation.m, 4);
  32279. var m2 = SIMD.float32x4.load(transformation.m, 8);
  32280. var m3 = SIMD.float32x4.load(transformation.m, 12);
  32281. 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));
  32282. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  32283. SIMD.float32x4.storeXYZ(result._data, 0, r);
  32284. };
  32285. return SIMDVector3;
  32286. })();
  32287. BABYLON.SIMDVector3 = SIMDVector3;
  32288. var SIMDMatrix = (function () {
  32289. function SIMDMatrix() {
  32290. }
  32291. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  32292. if (offset === void 0) { offset = 0; }
  32293. var tm = this.m;
  32294. var om = other.m;
  32295. var om0 = SIMD.float32x4.load(om, 0);
  32296. var om1 = SIMD.float32x4.load(om, 4);
  32297. var om2 = SIMD.float32x4.load(om, 8);
  32298. var om3 = SIMD.float32x4.load(om, 12);
  32299. var tm0 = SIMD.float32x4.load(tm, 0);
  32300. 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)))));
  32301. var tm1 = SIMD.float32x4.load(tm, 4);
  32302. 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)))));
  32303. var tm2 = SIMD.float32x4.load(tm, 8);
  32304. 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)))));
  32305. var tm3 = SIMD.float32x4.load(tm, 12);
  32306. 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)))));
  32307. };
  32308. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  32309. var src = this.m;
  32310. var dest = other.m;
  32311. var row0, row1, row2, row3;
  32312. var tmp1;
  32313. var minor0, minor1, minor2, minor3;
  32314. var det;
  32315. // Load the 4 rows
  32316. var src0 = SIMD.float32x4.load(src, 0);
  32317. var src1 = SIMD.float32x4.load(src, 4);
  32318. var src2 = SIMD.float32x4.load(src, 8);
  32319. var src3 = SIMD.float32x4.load(src, 12);
  32320. // Transpose the source matrix. Sort of. Not a true transpose operation
  32321. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  32322. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  32323. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  32324. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  32325. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  32326. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  32327. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  32328. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  32329. // This is a true transposition, but it will lead to an incorrect result
  32330. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  32331. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  32332. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  32333. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  32334. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  32335. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  32336. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  32337. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  32338. // ----
  32339. tmp1 = SIMD.float32x4.mul(row2, row3);
  32340. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32341. minor0 = SIMD.float32x4.mul(row1, tmp1);
  32342. minor1 = SIMD.float32x4.mul(row0, tmp1);
  32343. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32344. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  32345. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  32346. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  32347. // ----
  32348. tmp1 = SIMD.float32x4.mul(row1, row2);
  32349. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32350. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  32351. minor3 = SIMD.float32x4.mul(row0, tmp1);
  32352. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32353. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  32354. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  32355. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  32356. // ----
  32357. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  32358. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32359. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  32360. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  32361. minor2 = SIMD.float32x4.mul(row0, tmp1);
  32362. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32363. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  32364. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  32365. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  32366. // ----
  32367. tmp1 = SIMD.float32x4.mul(row0, row1);
  32368. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32369. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  32370. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  32371. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32372. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  32373. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  32374. // ----
  32375. tmp1 = SIMD.float32x4.mul(row0, row3);
  32376. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32377. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  32378. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  32379. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32380. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  32381. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  32382. // ----
  32383. tmp1 = SIMD.float32x4.mul(row0, row2);
  32384. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  32385. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  32386. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  32387. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  32388. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  32389. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  32390. // Compute determinant
  32391. det = SIMD.float32x4.mul(row0, minor0);
  32392. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  32393. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  32394. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  32395. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  32396. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  32397. // These shuffles aren't necessary if the faulty transposition is done
  32398. // up at the top of this function.
  32399. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  32400. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  32401. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  32402. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  32403. // Compute final values by multiplying with 1/det
  32404. minor0 = SIMD.float32x4.mul(det, minor0);
  32405. minor1 = SIMD.float32x4.mul(det, minor1);
  32406. minor2 = SIMD.float32x4.mul(det, minor2);
  32407. minor3 = SIMD.float32x4.mul(det, minor3);
  32408. SIMD.float32x4.store(dest, 0, minor0);
  32409. SIMD.float32x4.store(dest, 4, minor1);
  32410. SIMD.float32x4.store(dest, 8, minor2);
  32411. SIMD.float32x4.store(dest, 12, minor3);
  32412. return this;
  32413. };
  32414. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  32415. var out = result.m;
  32416. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  32417. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  32418. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  32419. // cc.kmVec3Subtract(f, pCenter, pEye);
  32420. var f = SIMD.float32x4.sub(center, eye);
  32421. // cc.kmVec3Normalize(f, f);
  32422. var tmp = SIMD.float32x4.mul(f, f);
  32423. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32424. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32425. // cc.kmVec3Assign(up, pUp);
  32426. // cc.kmVec3Normalize(up, up);
  32427. tmp = SIMD.float32x4.mul(up, up);
  32428. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32429. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32430. // cc.kmVec3Cross(s, f, up);
  32431. 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)));
  32432. // cc.kmVec3Normalize(s, s);
  32433. tmp = SIMD.float32x4.mul(s, s);
  32434. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32435. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32436. // cc.kmVec3Cross(u, s, f);
  32437. 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)));
  32438. // cc.kmVec3Normalize(s, s);
  32439. tmp = SIMD.float32x4.mul(s, s);
  32440. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  32441. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  32442. var zero = SIMD.float32x4.splat(0.0);
  32443. s = SIMD.float32x4.neg(s);
  32444. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  32445. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  32446. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  32447. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  32448. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  32449. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  32450. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  32451. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  32452. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  32453. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  32454. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  32455. var b3 = SIMD.float32x4.neg(eye);
  32456. b3 = SIMD.float32x4.withW(b3, 1.0);
  32457. 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)))));
  32458. 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)))));
  32459. 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)))));
  32460. 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)))));
  32461. };
  32462. return SIMDMatrix;
  32463. })();
  32464. BABYLON.SIMDMatrix = SIMDMatrix;
  32465. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  32466. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  32467. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  32468. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  32469. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  32470. var SIMDHelper = (function () {
  32471. function SIMDHelper() {
  32472. }
  32473. Object.defineProperty(SIMDHelper, "IsEnabled", {
  32474. get: function () {
  32475. return SIMDHelper._isEnabled;
  32476. },
  32477. enumerable: true,
  32478. configurable: true
  32479. });
  32480. SIMDHelper.DisableSIMD = function () {
  32481. // Replace functions
  32482. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  32483. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  32484. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  32485. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  32486. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  32487. SIMDHelper._isEnabled = false;
  32488. };
  32489. SIMDHelper.EnableSIMD = function () {
  32490. if (window.SIMD === undefined) {
  32491. return;
  32492. }
  32493. // Replace functions
  32494. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  32495. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  32496. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  32497. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  32498. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  32499. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  32500. get: function () { return this._data[0]; },
  32501. set: function (value) {
  32502. if (!this._data) {
  32503. this._data = new Float32Array(3);
  32504. }
  32505. this._data[0] = value;
  32506. }
  32507. });
  32508. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  32509. get: function () { return this._data[1]; },
  32510. set: function (value) {
  32511. this._data[1] = value;
  32512. }
  32513. });
  32514. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  32515. get: function () { return this._data[2]; },
  32516. set: function (value) {
  32517. this._data[2] = value;
  32518. }
  32519. });
  32520. SIMDHelper._isEnabled = true;
  32521. };
  32522. SIMDHelper._isEnabled = false;
  32523. return SIMDHelper;
  32524. })();
  32525. BABYLON.SIMDHelper = SIMDHelper;
  32526. })(BABYLON || (BABYLON = {}));
  32527. var BABYLON;
  32528. (function (BABYLON) {
  32529. var ShaderMaterial = (function (_super) {
  32530. __extends(ShaderMaterial, _super);
  32531. function ShaderMaterial(name, scene, shaderPath, options) {
  32532. _super.call(this, name, scene);
  32533. this._textures = {};
  32534. this._floats = {};
  32535. this._floatsArrays = {};
  32536. this._colors3 = {};
  32537. this._colors4 = {};
  32538. this._vectors2 = {};
  32539. this._vectors3 = {};
  32540. this._vectors4 = {};
  32541. this._matrices = {};
  32542. this._matrices3x3 = {};
  32543. this._matrices2x2 = {};
  32544. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  32545. this._shaderPath = shaderPath;
  32546. options.needAlphaBlending = options.needAlphaBlending || false;
  32547. options.needAlphaTesting = options.needAlphaTesting || false;
  32548. options.attributes = options.attributes || ["position", "normal", "uv"];
  32549. options.uniforms = options.uniforms || ["worldViewProjection"];
  32550. options.samplers = options.samplers || [];
  32551. options.defines = options.defines || [];
  32552. this._options = options;
  32553. }
  32554. ShaderMaterial.prototype.needAlphaBlending = function () {
  32555. return this._options.needAlphaBlending;
  32556. };
  32557. ShaderMaterial.prototype.needAlphaTesting = function () {
  32558. return this._options.needAlphaTesting;
  32559. };
  32560. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  32561. if (this._options.uniforms.indexOf(uniformName) === -1) {
  32562. this._options.uniforms.push(uniformName);
  32563. }
  32564. };
  32565. ShaderMaterial.prototype.setTexture = function (name, texture) {
  32566. if (this._options.samplers.indexOf(name) === -1) {
  32567. this._options.samplers.push(name);
  32568. }
  32569. this._textures[name] = texture;
  32570. return this;
  32571. };
  32572. ShaderMaterial.prototype.setFloat = function (name, value) {
  32573. this._checkUniform(name);
  32574. this._floats[name] = value;
  32575. return this;
  32576. };
  32577. ShaderMaterial.prototype.setFloats = function (name, value) {
  32578. this._checkUniform(name);
  32579. this._floatsArrays[name] = value;
  32580. return this;
  32581. };
  32582. ShaderMaterial.prototype.setColor3 = function (name, value) {
  32583. this._checkUniform(name);
  32584. this._colors3[name] = value;
  32585. return this;
  32586. };
  32587. ShaderMaterial.prototype.setColor4 = function (name, value) {
  32588. this._checkUniform(name);
  32589. this._colors4[name] = value;
  32590. return this;
  32591. };
  32592. ShaderMaterial.prototype.setVector2 = function (name, value) {
  32593. this._checkUniform(name);
  32594. this._vectors2[name] = value;
  32595. return this;
  32596. };
  32597. ShaderMaterial.prototype.setVector3 = function (name, value) {
  32598. this._checkUniform(name);
  32599. this._vectors3[name] = value;
  32600. return this;
  32601. };
  32602. ShaderMaterial.prototype.setVector4 = function (name, value) {
  32603. this._checkUniform(name);
  32604. this._vectors4[name] = value;
  32605. return this;
  32606. };
  32607. ShaderMaterial.prototype.setMatrix = function (name, value) {
  32608. this._checkUniform(name);
  32609. this._matrices[name] = value;
  32610. return this;
  32611. };
  32612. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  32613. this._checkUniform(name);
  32614. this._matrices3x3[name] = value;
  32615. return this;
  32616. };
  32617. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  32618. this._checkUniform(name);
  32619. this._matrices2x2[name] = value;
  32620. return this;
  32621. };
  32622. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  32623. var scene = this.getScene();
  32624. var engine = scene.getEngine();
  32625. if (!this.checkReadyOnEveryCall) {
  32626. if (this._renderId === scene.getRenderId()) {
  32627. return true;
  32628. }
  32629. }
  32630. // Instances
  32631. var defines = [];
  32632. var fallbacks = new BABYLON.EffectFallbacks();
  32633. if (useInstances) {
  32634. defines.push("#define INSTANCES");
  32635. }
  32636. for (var index = 0; index < this._options.defines.length; index++) {
  32637. defines.push(this._options.defines[index]);
  32638. }
  32639. // Bones
  32640. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  32641. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  32642. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32643. fallbacks.addCPUSkinningFallback(0, mesh);
  32644. }
  32645. // Alpha test
  32646. if (engine.getAlphaTesting()) {
  32647. defines.push("#define ALPHATEST");
  32648. }
  32649. var previousEffect = this._effect;
  32650. var join = defines.join("\n");
  32651. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  32652. if (!this._effect.isReady()) {
  32653. return false;
  32654. }
  32655. if (previousEffect !== this._effect) {
  32656. scene.resetCachedMaterial();
  32657. }
  32658. this._renderId = scene.getRenderId();
  32659. return true;
  32660. };
  32661. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32662. var scene = this.getScene();
  32663. if (this._options.uniforms.indexOf("world") !== -1) {
  32664. this._effect.setMatrix("world", world);
  32665. }
  32666. if (this._options.uniforms.indexOf("worldView") !== -1) {
  32667. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  32668. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  32669. }
  32670. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  32671. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  32672. }
  32673. };
  32674. ShaderMaterial.prototype.bind = function (world, mesh) {
  32675. // Std values
  32676. this.bindOnlyWorldMatrix(world);
  32677. if (this.getScene().getCachedMaterial() !== this) {
  32678. if (this._options.uniforms.indexOf("view") !== -1) {
  32679. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  32680. }
  32681. if (this._options.uniforms.indexOf("projection") !== -1) {
  32682. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  32683. }
  32684. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  32685. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  32686. }
  32687. // Bones
  32688. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  32689. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  32690. }
  32691. // Texture
  32692. for (var name in this._textures) {
  32693. this._effect.setTexture(name, this._textures[name]);
  32694. }
  32695. // Float
  32696. for (name in this._floats) {
  32697. this._effect.setFloat(name, this._floats[name]);
  32698. }
  32699. // Float s
  32700. for (name in this._floatsArrays) {
  32701. this._effect.setArray(name, this._floatsArrays[name]);
  32702. }
  32703. // Color3
  32704. for (name in this._colors3) {
  32705. this._effect.setColor3(name, this._colors3[name]);
  32706. }
  32707. // Color4
  32708. for (name in this._colors4) {
  32709. var color = this._colors4[name];
  32710. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  32711. }
  32712. // Vector2
  32713. for (name in this._vectors2) {
  32714. this._effect.setVector2(name, this._vectors2[name]);
  32715. }
  32716. // Vector3
  32717. for (name in this._vectors3) {
  32718. this._effect.setVector3(name, this._vectors3[name]);
  32719. }
  32720. // Vector4
  32721. for (name in this._vectors4) {
  32722. this._effect.setVector4(name, this._vectors4[name]);
  32723. }
  32724. // Matrix
  32725. for (name in this._matrices) {
  32726. this._effect.setMatrix(name, this._matrices[name]);
  32727. }
  32728. // Matrix 3x3
  32729. for (name in this._matrices3x3) {
  32730. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  32731. }
  32732. // Matrix 2x2
  32733. for (name in this._matrices2x2) {
  32734. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  32735. }
  32736. }
  32737. _super.prototype.bind.call(this, world, mesh);
  32738. };
  32739. ShaderMaterial.prototype.clone = function (name) {
  32740. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  32741. return newShaderMaterial;
  32742. };
  32743. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  32744. for (var name in this._textures) {
  32745. this._textures[name].dispose();
  32746. }
  32747. this._textures = {};
  32748. _super.prototype.dispose.call(this, forceDisposeEffect);
  32749. };
  32750. ShaderMaterial.prototype.serialize = function () {
  32751. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32752. serializationObject.customType = "BABYLON.ShaderMaterial";
  32753. serializationObject.options = this._options;
  32754. serializationObject.shaderPath = this._shaderPath;
  32755. // Texture
  32756. serializationObject.textures = {};
  32757. for (var name in this._textures) {
  32758. serializationObject.textures[name] = this._textures[name].serialize();
  32759. }
  32760. // Float
  32761. serializationObject.floats = {};
  32762. for (name in this._floats) {
  32763. serializationObject.floats[name] = this._floats[name];
  32764. }
  32765. // Float s
  32766. serializationObject.floatArrays = {};
  32767. for (name in this._floatsArrays) {
  32768. serializationObject.floatArrays[name] = this._floatsArrays[name];
  32769. }
  32770. // Color3
  32771. serializationObject.colors3 = {};
  32772. for (name in this._colors3) {
  32773. serializationObject.colors3[name] = this._colors3[name].asArray();
  32774. }
  32775. // Color4
  32776. serializationObject.colors4 = {};
  32777. for (name in this._colors4) {
  32778. serializationObject.colors4[name] = this._colors4[name].asArray();
  32779. }
  32780. // Vector2
  32781. serializationObject.vectors2 = {};
  32782. for (name in this._vectors2) {
  32783. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  32784. }
  32785. // Vector3
  32786. serializationObject.vectors3 = {};
  32787. for (name in this._vectors3) {
  32788. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  32789. }
  32790. // Vector4
  32791. serializationObject.vectors4 = {};
  32792. for (name in this._vectors4) {
  32793. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  32794. }
  32795. // Matrix
  32796. serializationObject.matrices = {};
  32797. for (name in this._matrices) {
  32798. serializationObject.matrices[name] = this._matrices[name].asArray();
  32799. }
  32800. // Matrix 3x3
  32801. serializationObject.matrices3x3 = {};
  32802. for (name in this._matrices3x3) {
  32803. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  32804. }
  32805. // Matrix 2x2
  32806. serializationObject.matrices2x2 = {};
  32807. for (name in this._matrices2x2) {
  32808. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  32809. }
  32810. return serializationObject;
  32811. };
  32812. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  32813. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  32814. // Texture
  32815. for (var name in source.textures) {
  32816. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  32817. }
  32818. // Float
  32819. for (name in source.floats) {
  32820. material.setFloat(name, source.floats[name]);
  32821. }
  32822. // Float s
  32823. for (name in source.floatsArrays) {
  32824. material.setFloats(name, source.floatsArrays[name]);
  32825. }
  32826. // Color3
  32827. for (name in source.colors3) {
  32828. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  32829. }
  32830. // Color4
  32831. for (name in source.colors4) {
  32832. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  32833. }
  32834. // Vector2
  32835. for (name in source.vectors2) {
  32836. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  32837. }
  32838. // Vector3
  32839. for (name in source.vectors3) {
  32840. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  32841. }
  32842. // Vector4
  32843. for (name in source.vectors4) {
  32844. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  32845. }
  32846. // Matrix
  32847. for (name in source.matrices) {
  32848. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  32849. }
  32850. // Matrix 3x3
  32851. for (name in source.matrices3x3) {
  32852. material.setMatrix3x3(name, source.matrices3x3[name]);
  32853. }
  32854. // Matrix 2x2
  32855. for (name in source.matrices2x2) {
  32856. material.setMatrix2x2(name, source.matrices2x2[name]);
  32857. }
  32858. return material;
  32859. };
  32860. return ShaderMaterial;
  32861. })(BABYLON.Material);
  32862. BABYLON.ShaderMaterial = ShaderMaterial;
  32863. })(BABYLON || (BABYLON = {}));
  32864. var BABYLON;
  32865. (function (BABYLON) {
  32866. var Internals;
  32867. (function (Internals) {
  32868. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  32869. // All values and structures referenced from:
  32870. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  32871. var DDS_MAGIC = 0x20534444;
  32872. 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;
  32873. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  32874. 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;
  32875. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  32876. function FourCCToInt32(value) {
  32877. return value.charCodeAt(0) +
  32878. (value.charCodeAt(1) << 8) +
  32879. (value.charCodeAt(2) << 16) +
  32880. (value.charCodeAt(3) << 24);
  32881. }
  32882. function Int32ToFourCC(value) {
  32883. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  32884. }
  32885. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  32886. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  32887. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  32888. var headerLengthInt = 31; // The header length in 32 bit ints
  32889. // Offsets into the header array
  32890. var off_magic = 0;
  32891. var off_size = 1;
  32892. var off_flags = 2;
  32893. var off_height = 3;
  32894. var off_width = 4;
  32895. var off_mipmapCount = 7;
  32896. var off_pfFlags = 20;
  32897. var off_pfFourCC = 21;
  32898. var off_RGBbpp = 22;
  32899. var off_RMask = 23;
  32900. var off_GMask = 24;
  32901. var off_BMask = 25;
  32902. var off_AMask = 26;
  32903. var off_caps1 = 27;
  32904. var off_caps2 = 28;
  32905. ;
  32906. var DDSTools = (function () {
  32907. function DDSTools() {
  32908. }
  32909. DDSTools.GetDDSInfo = function (arrayBuffer) {
  32910. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  32911. var mipmapCount = 1;
  32912. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  32913. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32914. }
  32915. return {
  32916. width: header[off_width],
  32917. height: header[off_height],
  32918. mipmapCount: mipmapCount,
  32919. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  32920. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  32921. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  32922. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  32923. };
  32924. };
  32925. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32926. var byteArray = new Uint8Array(dataLength);
  32927. var srcData = new Uint8Array(arrayBuffer);
  32928. var index = 0;
  32929. for (var y = height - 1; y >= 0; y--) {
  32930. for (var x = 0; x < width; x++) {
  32931. var srcPos = dataOffset + (x + y * width) * 4;
  32932. byteArray[index + 2] = srcData[srcPos];
  32933. byteArray[index + 1] = srcData[srcPos + 1];
  32934. byteArray[index] = srcData[srcPos + 2];
  32935. byteArray[index + 3] = srcData[srcPos + 3];
  32936. index += 4;
  32937. }
  32938. }
  32939. return byteArray;
  32940. };
  32941. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32942. var byteArray = new Uint8Array(dataLength);
  32943. var srcData = new Uint8Array(arrayBuffer);
  32944. var index = 0;
  32945. for (var y = height - 1; y >= 0; y--) {
  32946. for (var x = 0; x < width; x++) {
  32947. var srcPos = dataOffset + (x + y * width) * 3;
  32948. byteArray[index + 2] = srcData[srcPos];
  32949. byteArray[index + 1] = srcData[srcPos + 1];
  32950. byteArray[index] = srcData[srcPos + 2];
  32951. index += 3;
  32952. }
  32953. }
  32954. return byteArray;
  32955. };
  32956. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32957. var byteArray = new Uint8Array(dataLength);
  32958. var srcData = new Uint8Array(arrayBuffer);
  32959. var index = 0;
  32960. for (var y = height - 1; y >= 0; y--) {
  32961. for (var x = 0; x < width; x++) {
  32962. var srcPos = dataOffset + (x + y * width);
  32963. byteArray[index] = srcData[srcPos];
  32964. index++;
  32965. }
  32966. }
  32967. return byteArray;
  32968. };
  32969. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  32970. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  32971. if (header[off_magic] != DDS_MAGIC) {
  32972. BABYLON.Tools.Error("Invalid magic number in DDS header");
  32973. return;
  32974. }
  32975. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  32976. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  32977. return;
  32978. }
  32979. if (info.isFourCC) {
  32980. fourCC = header[off_pfFourCC];
  32981. switch (fourCC) {
  32982. case FOURCC_DXT1:
  32983. blockBytes = 8;
  32984. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  32985. break;
  32986. case FOURCC_DXT3:
  32987. blockBytes = 16;
  32988. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  32989. break;
  32990. case FOURCC_DXT5:
  32991. blockBytes = 16;
  32992. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  32993. break;
  32994. default:
  32995. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  32996. return;
  32997. }
  32998. }
  32999. mipmapCount = 1;
  33000. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  33001. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33002. }
  33003. var bpp = header[off_RGBbpp];
  33004. for (var face = 0; face < faces; face++) {
  33005. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  33006. width = header[off_width];
  33007. height = header[off_height];
  33008. dataOffset = header[off_size] + 4;
  33009. for (i = 0; i < mipmapCount; ++i) {
  33010. if (info.isRGB) {
  33011. if (bpp === 24) {
  33012. dataLength = width * height * 3;
  33013. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33014. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  33015. }
  33016. else {
  33017. dataLength = width * height * 4;
  33018. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33019. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  33020. }
  33021. }
  33022. else if (info.isLuminance) {
  33023. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  33024. var unpaddedRowSize = width;
  33025. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  33026. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  33027. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33028. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  33029. }
  33030. else {
  33031. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  33032. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  33033. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  33034. }
  33035. dataOffset += dataLength;
  33036. width *= 0.5;
  33037. height *= 0.5;
  33038. width = Math.max(1.0, width);
  33039. height = Math.max(1.0, height);
  33040. }
  33041. }
  33042. };
  33043. return DDSTools;
  33044. })();
  33045. Internals.DDSTools = DDSTools;
  33046. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33047. })(BABYLON || (BABYLON = {}));
  33048. var BABYLON;
  33049. (function (BABYLON) {
  33050. var CannonJSPlugin = (function () {
  33051. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  33052. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  33053. if (iterations === void 0) { iterations = 10; }
  33054. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  33055. this.name = "CannonJSPlugin";
  33056. this._physicsMaterials = [];
  33057. this._fixedTimeStep = 1 / 60;
  33058. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  33059. this._currentCollisionGroup = 2;
  33060. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  33061. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  33062. this._tmpPosition = BABYLON.Vector3.Zero();
  33063. this._tmpQuaternion = new BABYLON.Quaternion();
  33064. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  33065. this._tmpDeltaRotation = new BABYLON.Quaternion();
  33066. this._tmpUnityRotation = new BABYLON.Quaternion();
  33067. if (!this.isSupported()) {
  33068. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  33069. return;
  33070. }
  33071. this.world = new CANNON.World();
  33072. this.world.broadphase = new CANNON.NaiveBroadphase();
  33073. this.world.solver.iterations = iterations;
  33074. }
  33075. CannonJSPlugin.prototype.setGravity = function (gravity) {
  33076. this.world.gravity.copy(gravity);
  33077. };
  33078. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  33079. this._fixedTimeStep = timeStep;
  33080. };
  33081. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  33082. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  33083. };
  33084. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  33085. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  33086. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  33087. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  33088. };
  33089. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  33090. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  33091. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  33092. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  33093. };
  33094. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  33095. //parent-child relationship. Does this impostor has a parent impostor?
  33096. if (impostor.parent) {
  33097. if (impostor.physicsBody) {
  33098. this.removePhysicsBody(impostor);
  33099. //TODO is that needed?
  33100. impostor.forceUpdate();
  33101. }
  33102. return;
  33103. }
  33104. //should a new body be created for this impostor?
  33105. if (impostor.isBodyInitRequired()) {
  33106. if (!impostor.mesh.rotationQuaternion) {
  33107. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  33108. }
  33109. var shape = this._createShape(impostor);
  33110. //unregister events, if body is being changed
  33111. var oldBody = impostor.physicsBody;
  33112. if (oldBody) {
  33113. this.removePhysicsBody(impostor);
  33114. }
  33115. //create the body and material
  33116. var material = this._addMaterial("mat-" + impostor.mesh.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  33117. var bodyCreationObject = {
  33118. mass: impostor.getParam("mass"),
  33119. material: material
  33120. };
  33121. // A simple extend, in case native options were used.
  33122. var nativeOptions = impostor.getParam("nativeOptions");
  33123. for (var key in nativeOptions) {
  33124. if (nativeOptions.hasOwnProperty(key)) {
  33125. bodyCreationObject[key] = nativeOptions[key];
  33126. }
  33127. }
  33128. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  33129. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  33130. this.world.addEventListener("preStep", impostor.beforeStep);
  33131. this.world.addEventListener("postStep", impostor.afterStep);
  33132. impostor.physicsBody.addShape(shape);
  33133. this.world.add(impostor.physicsBody);
  33134. //try to keep the body moving in the right direction by taking old properties.
  33135. //Should be tested!
  33136. if (oldBody) {
  33137. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  33138. impostor.physicsBody[param].copy(oldBody[param]);
  33139. });
  33140. }
  33141. this._processChildMeshes(impostor);
  33142. }
  33143. //now update the body's transformation
  33144. this._updatePhysicsBodyTransformation(impostor);
  33145. };
  33146. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  33147. var _this = this;
  33148. var meshChildren = mainImpostor.mesh.getChildMeshes();
  33149. if (meshChildren.length) {
  33150. var processMesh = function (localPosition, mesh) {
  33151. var childImpostor = mesh.getPhysicsImpostor();
  33152. if (childImpostor) {
  33153. var parent = childImpostor.parent;
  33154. if (parent !== mainImpostor) {
  33155. var localPosition = mesh.position;
  33156. if (childImpostor.physicsBody) {
  33157. _this.removePhysicsBody(childImpostor);
  33158. childImpostor.physicsBody = null;
  33159. }
  33160. childImpostor.parent = mainImpostor;
  33161. childImpostor.resetUpdateFlags();
  33162. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  33163. //Add the mass of the children.
  33164. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  33165. }
  33166. }
  33167. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  33168. };
  33169. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  33170. }
  33171. };
  33172. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  33173. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  33174. this.world.removeEventListener("preStep", impostor.beforeStep);
  33175. this.world.removeEventListener("postStep", impostor.afterStep);
  33176. this.world.remove(impostor.physicsBody);
  33177. };
  33178. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  33179. var mainBody = impostorJoint.mainImpostor.physicsBody;
  33180. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  33181. if (!mainBody || !connectedBody) {
  33182. return;
  33183. }
  33184. var constraint;
  33185. var jointData = impostorJoint.joint.jointData;
  33186. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  33187. var constraintData = {
  33188. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  33189. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  33190. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  33191. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  33192. maxForce: jointData.nativeParams.maxForce,
  33193. collideConnected: !!jointData.collision
  33194. };
  33195. //Not needed, Cannon has a collideConnected flag
  33196. /*if (!jointData.collision) {
  33197. //add 1st body to a collision group of its own, if it is not in 1
  33198. if (mainBody.collisionFilterGroup === 1) {
  33199. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  33200. this._currentCollisionGroup <<= 1;
  33201. }
  33202. if (connectedBody.collisionFilterGroup === 1) {
  33203. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  33204. this._currentCollisionGroup <<= 1;
  33205. }
  33206. //add their mask to the collisionFilterMask of each other:
  33207. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  33208. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  33209. }*/
  33210. switch (impostorJoint.joint.type) {
  33211. case BABYLON.PhysicsJoint.HingeJoint:
  33212. case BABYLON.PhysicsJoint.Hinge2Joint:
  33213. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  33214. break;
  33215. case BABYLON.PhysicsJoint.DistanceJoint:
  33216. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  33217. break;
  33218. case BABYLON.PhysicsJoint.SpringJoint:
  33219. var springData = jointData;
  33220. constraint = new CANNON.Spring(mainBody, connectedBody, {
  33221. restLength: springData.length,
  33222. stiffness: springData.stiffness,
  33223. damping: springData.damping,
  33224. localAnchorA: constraintData.pivotA,
  33225. localAnchorB: constraintData.pivotB
  33226. });
  33227. break;
  33228. default:
  33229. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  33230. break;
  33231. }
  33232. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  33233. constraint.collideConnected = !!jointData.collision;
  33234. impostorJoint.joint.physicsJoint = constraint;
  33235. //don't add spring as constraint, as it is not one.
  33236. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  33237. this.world.addConstraint(constraint);
  33238. }
  33239. else {
  33240. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  33241. constraint.applyForce();
  33242. });
  33243. }
  33244. };
  33245. CannonJSPlugin.prototype.removeJoint = function (joint) {
  33246. //TODO
  33247. };
  33248. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  33249. var index;
  33250. var mat;
  33251. for (index = 0; index < this._physicsMaterials.length; index++) {
  33252. mat = this._physicsMaterials[index];
  33253. if (mat.friction === friction && mat.restitution === restitution) {
  33254. return mat;
  33255. }
  33256. }
  33257. var currentMat = new CANNON.Material("mat");
  33258. currentMat.friction = friction;
  33259. currentMat.restitution = restitution;
  33260. this._physicsMaterials.push(currentMat);
  33261. return currentMat;
  33262. };
  33263. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  33264. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  33265. };
  33266. CannonJSPlugin.prototype._createShape = function (impostor) {
  33267. var mesh = impostor.mesh;
  33268. //get the correct bounding box
  33269. var oldQuaternion = mesh.rotationQuaternion;
  33270. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  33271. mesh.computeWorldMatrix(true);
  33272. var returnValue;
  33273. switch (impostor.type) {
  33274. case BABYLON.PhysicsEngine.SphereImpostor:
  33275. var bbox = mesh.getBoundingInfo().boundingBox;
  33276. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  33277. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  33278. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  33279. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  33280. break;
  33281. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  33282. case BABYLON.PhysicsEngine.CylinderImpostor:
  33283. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  33284. case BABYLON.PhysicsEngine.BoxImpostor:
  33285. bbox = mesh.getBoundingInfo().boundingBox;
  33286. var min = bbox.minimumWorld;
  33287. var max = bbox.maximumWorld;
  33288. var box = max.subtract(min).scale(0.5);
  33289. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  33290. break;
  33291. case BABYLON.PhysicsEngine.PlaneImpostor:
  33292. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  33293. returnValue = new CANNON.Plane();
  33294. break;
  33295. case BABYLON.PhysicsEngine.MeshImpostor:
  33296. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33297. var rawFaces = mesh.getIndices();
  33298. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  33299. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  33300. break;
  33301. case BABYLON.PhysicsEngine.HeightmapImpostor:
  33302. returnValue = this._createHeightmap(mesh);
  33303. break;
  33304. }
  33305. mesh.rotationQuaternion = oldQuaternion;
  33306. return returnValue;
  33307. };
  33308. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  33309. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33310. var matrix = [];
  33311. //For now pointDepth will not be used and will be automatically calculated.
  33312. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  33313. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  33314. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  33315. var elementSize = dim * 2 / arraySize;
  33316. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  33317. for (var i = 0; i < pos.length; i = i + 3) {
  33318. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  33319. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  33320. var y = pos[i + 1] + minY;
  33321. if (!matrix[x]) {
  33322. matrix[x] = [];
  33323. }
  33324. if (!matrix[x][z]) {
  33325. matrix[x][z] = y;
  33326. }
  33327. matrix[x][z] = Math.max(y, matrix[x][z]);
  33328. }
  33329. for (var x = 0; x <= arraySize; ++x) {
  33330. if (!matrix[x]) {
  33331. var loc = 1;
  33332. while (!matrix[(x + loc) % arraySize]) {
  33333. loc++;
  33334. }
  33335. matrix[x] = matrix[(x + loc) % arraySize].slice();
  33336. }
  33337. for (var z = 0; z <= arraySize; ++z) {
  33338. if (!matrix[x][z]) {
  33339. var loc = 1;
  33340. var newValue;
  33341. while (newValue === undefined) {
  33342. newValue = matrix[x][(z + loc++) % arraySize];
  33343. }
  33344. matrix[x][z] = newValue;
  33345. }
  33346. }
  33347. }
  33348. var shape = new CANNON.Heightfield(matrix, {
  33349. elementSize: elementSize
  33350. });
  33351. //For future reference, needed for body transformation
  33352. shape.minY = minY;
  33353. return shape;
  33354. };
  33355. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  33356. var mesh = impostor.mesh;
  33357. //make sure it is updated...
  33358. impostor.mesh.computeWorldMatrix(true);
  33359. // The delta between the mesh position and the mesh bounding box center
  33360. var bbox = mesh.getBoundingInfo().boundingBox;
  33361. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  33362. var quaternion = mesh.rotationQuaternion;
  33363. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  33364. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  33365. if (impostor.type === BABYLON.PhysicsEngine.PlaneImpostor || impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  33366. //-90 DEG in X, precalculated
  33367. quaternion = quaternion.multiply(this._minus90X);
  33368. //Invert! (Precalculated, 90 deg in X)
  33369. //No need to clone. this will never change.
  33370. impostor.setDeltaRotation(this._plus90X);
  33371. }
  33372. //If it is a heightfield, if should be centered.
  33373. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  33374. //calculate the correct body position:
  33375. var rotationQuaternion = mesh.rotationQuaternion;
  33376. mesh.rotationQuaternion = this._tmpUnityRotation;
  33377. mesh.computeWorldMatrix(true);
  33378. //get original center with no rotation
  33379. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  33380. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  33381. //rotation is back
  33382. mesh.rotationQuaternion = rotationQuaternion;
  33383. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  33384. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  33385. mesh.setPivotMatrix(p);
  33386. mesh.computeWorldMatrix(true);
  33387. //calculate the translation
  33388. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  33389. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  33390. //add it inverted to the delta
  33391. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  33392. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  33393. mesh.setPivotMatrix(oldPivot);
  33394. mesh.computeWorldMatrix(true);
  33395. }
  33396. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  33397. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  33398. this._tmpPosition.copyFrom(mesh.position);
  33399. }
  33400. impostor.setDeltaPosition(this._tmpDeltaPosition);
  33401. //Now update the impostor object
  33402. impostor.physicsBody.position.copy(this._tmpPosition);
  33403. impostor.physicsBody.quaternion.copy(quaternion);
  33404. };
  33405. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  33406. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  33407. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  33408. };
  33409. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  33410. impostor.physicsBody.position.copy(newPosition);
  33411. impostor.physicsBody.quaternion.copy(newRotation);
  33412. };
  33413. CannonJSPlugin.prototype.isSupported = function () {
  33414. return window.CANNON !== undefined;
  33415. };
  33416. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  33417. impostor.physicsBody.velocity.copy(velocity);
  33418. };
  33419. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  33420. impostor.physicsBody.angularVelocity.copy(velocity);
  33421. };
  33422. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  33423. var v = impostor.physicsBody.velocity;
  33424. if (!v)
  33425. return null;
  33426. return new BABYLON.Vector3(v.x, v.y, v.z);
  33427. };
  33428. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  33429. var v = impostor.physicsBody.angularVelocity;
  33430. if (!v)
  33431. return null;
  33432. return new BABYLON.Vector3(v.x, v.y, v.z);
  33433. };
  33434. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  33435. impostor.physicsBody.mass = mass;
  33436. impostor.physicsBody.updateMassProperties();
  33437. };
  33438. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  33439. impostor.physicsBody.sleep();
  33440. };
  33441. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  33442. impostor.physicsBody.wakeUp();
  33443. };
  33444. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  33445. joint.physicsJoint.distance = maxDistance;
  33446. };
  33447. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  33448. if (!motorIndex) {
  33449. joint.physicsJoint.enableMotor();
  33450. }
  33451. };
  33452. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  33453. if (!motorIndex) {
  33454. joint.physicsJoint.disableMotor();
  33455. }
  33456. };
  33457. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  33458. if (!motorIndex) {
  33459. joint.physicsJoint.enableMotor();
  33460. joint.physicsJoint.setMotorSpeed(speed);
  33461. if (maxForce) {
  33462. this.setLimit(joint, maxForce);
  33463. }
  33464. }
  33465. };
  33466. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  33467. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  33468. joint.physicsJoint.motorEquation.minForce = lowerLimit || -upperLimit;
  33469. };
  33470. CannonJSPlugin.prototype.dispose = function () {
  33471. //nothing to do, actually.
  33472. };
  33473. return CannonJSPlugin;
  33474. })();
  33475. BABYLON.CannonJSPlugin = CannonJSPlugin;
  33476. })(BABYLON || (BABYLON = {}));
  33477. var BABYLON;
  33478. (function (BABYLON) {
  33479. var OimoJSPlugin = (function () {
  33480. function OimoJSPlugin(iterations) {
  33481. this.name = "OimoJSPlugin";
  33482. this._tmpImpostorsArray = [];
  33483. this._tmpPositionVector = BABYLON.Vector3.Zero();
  33484. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  33485. this.world.clear();
  33486. //making sure no stats are calculated
  33487. this.world.isNoStat = true;
  33488. }
  33489. OimoJSPlugin.prototype.setGravity = function (gravity) {
  33490. this.world.gravity.copy(gravity);
  33491. };
  33492. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  33493. this.world.timeStep = timeStep;
  33494. };
  33495. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  33496. var _this = this;
  33497. impostors.forEach(function (impostor) {
  33498. impostor.beforeStep();
  33499. });
  33500. this.world.step();
  33501. impostors.forEach(function (impostor) {
  33502. impostor.afterStep();
  33503. //update the ordered impostors array
  33504. _this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  33505. });
  33506. //check for collisions
  33507. var contact = this.world.contacts;
  33508. while (contact !== null) {
  33509. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  33510. contact = contact.next;
  33511. continue;
  33512. }
  33513. //is this body colliding with any other? get the impostor
  33514. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  33515. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  33516. if (!mainImpostor || !collidingImpostor) {
  33517. contact = contact.next;
  33518. continue;
  33519. }
  33520. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  33521. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  33522. contact = contact.next;
  33523. }
  33524. };
  33525. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  33526. var mass = impostor.physicsBody.massInfo.mass;
  33527. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  33528. };
  33529. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  33530. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  33531. this.applyImpulse(impostor, force, contactPoint);
  33532. };
  33533. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  33534. var _this = this;
  33535. //parent-child relationship. Does this impostor has a parent impostor?
  33536. if (impostor.parent) {
  33537. if (impostor.physicsBody) {
  33538. this.removePhysicsBody(impostor);
  33539. //TODO is that needed?
  33540. impostor.forceUpdate();
  33541. }
  33542. return;
  33543. }
  33544. impostor.mesh.computeWorldMatrix(true);
  33545. if (impostor.isBodyInitRequired()) {
  33546. if (!impostor.mesh.rotationQuaternion) {
  33547. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  33548. }
  33549. var bodyConfig = {
  33550. name: impostor.mesh.uniqueId,
  33551. //Oimo must have mass, also for static objects.
  33552. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  33553. size: [],
  33554. type: [],
  33555. pos: [],
  33556. rot: [],
  33557. move: impostor.getParam("mass") !== 0,
  33558. //Supporting older versions of Oimo
  33559. world: this.world
  33560. };
  33561. var impostors = [impostor];
  33562. function addToArray(parent) {
  33563. parent.getChildMeshes().forEach(function (m) {
  33564. if (m.physicsImpostor) {
  33565. impostors.push(m.physicsImpostor);
  33566. m.physicsImpostor._init();
  33567. }
  33568. });
  33569. }
  33570. addToArray(impostor.mesh);
  33571. function checkWithEpsilon(value) {
  33572. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  33573. }
  33574. impostors.forEach(function (i) {
  33575. //get the correct bounding box
  33576. var oldQuaternion = i.mesh.rotationQuaternion;
  33577. 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 });
  33578. i.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  33579. i.mesh.computeWorldMatrix(true);
  33580. var bbox = i.mesh.getBoundingInfo().boundingBox;
  33581. if (i === impostor) {
  33582. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, _this._tmpPositionVector);
  33583. //Can also use Array.prototype.push.apply
  33584. bodyConfig.pos.push(bbox.center.x);
  33585. bodyConfig.pos.push(bbox.center.y);
  33586. bodyConfig.pos.push(bbox.center.z);
  33587. //tmp solution
  33588. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  33589. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  33590. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  33591. }
  33592. else {
  33593. bodyConfig.pos.push(i.mesh.position.x);
  33594. bodyConfig.pos.push(i.mesh.position.y);
  33595. bodyConfig.pos.push(i.mesh.position.z);
  33596. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  33597. bodyConfig.rot.push(0);
  33598. bodyConfig.rot.push(0);
  33599. bodyConfig.rot.push(0);
  33600. }
  33601. // register mesh
  33602. switch (i.type) {
  33603. case BABYLON.PhysicsEngine.SphereImpostor:
  33604. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  33605. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  33606. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  33607. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  33608. bodyConfig.type.push('sphere');
  33609. //due to the way oimo works with compounds, add 3 times
  33610. bodyConfig.size.push(size);
  33611. bodyConfig.size.push(size);
  33612. bodyConfig.size.push(size);
  33613. break;
  33614. case BABYLON.PhysicsEngine.PlaneImpostor:
  33615. //TODO Oimo now supports cylinder!
  33616. case BABYLON.PhysicsEngine.CylinderImpostor:
  33617. case BABYLON.PhysicsEngine.BoxImpostor:
  33618. default:
  33619. var min = bbox.minimumWorld;
  33620. var max = bbox.maximumWorld;
  33621. var box = max.subtract(min);
  33622. var sizeX = checkWithEpsilon(box.x);
  33623. var sizeY = checkWithEpsilon(box.y);
  33624. var sizeZ = checkWithEpsilon(box.z);
  33625. bodyConfig.type.push('box');
  33626. bodyConfig.size.push(sizeX);
  33627. bodyConfig.size.push(sizeY);
  33628. bodyConfig.size.push(sizeZ);
  33629. break;
  33630. }
  33631. //actually not needed, but hey...
  33632. i.mesh.rotationQuaternion = oldQuaternion;
  33633. });
  33634. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  33635. }
  33636. else {
  33637. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  33638. }
  33639. impostor.setDeltaPosition(this._tmpPositionVector);
  33640. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  33641. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  33642. };
  33643. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  33644. //impostor.physicsBody.dispose();
  33645. //Same as : (older oimo versions)
  33646. this.world.removeRigidBody(impostor.physicsBody);
  33647. };
  33648. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  33649. var mainBody = impostorJoint.mainImpostor.physicsBody;
  33650. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  33651. if (!mainBody || !connectedBody) {
  33652. return;
  33653. }
  33654. var jointData = impostorJoint.joint.jointData;
  33655. var options = jointData.nativeParams || {};
  33656. var type;
  33657. var nativeJointData = {
  33658. body1: mainBody,
  33659. body2: connectedBody,
  33660. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  33661. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  33662. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  33663. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  33664. min: options.min,
  33665. max: options.max,
  33666. collision: options.collision || jointData.collision,
  33667. spring: options.spring,
  33668. //supporting older version of Oimo
  33669. world: this.world
  33670. };
  33671. switch (impostorJoint.joint.type) {
  33672. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  33673. type = "jointBall";
  33674. break;
  33675. case BABYLON.PhysicsJoint.SpringJoint:
  33676. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  33677. var springData = jointData;
  33678. nativeJointData.min = springData.length || nativeJointData.min;
  33679. //Max should also be set, just make sure it is at least min
  33680. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  33681. case BABYLON.PhysicsJoint.DistanceJoint:
  33682. type = "jointDistance";
  33683. nativeJointData.max = jointData.maxDistance;
  33684. break;
  33685. case BABYLON.PhysicsJoint.PrismaticJoint:
  33686. type = "jointPrisme";
  33687. break;
  33688. case BABYLON.PhysicsJoint.SliderJoint:
  33689. type = "jointSlide";
  33690. break;
  33691. case BABYLON.PhysicsJoint.WheelJoint:
  33692. type = "jointWheel";
  33693. break;
  33694. case BABYLON.PhysicsJoint.HingeJoint:
  33695. default:
  33696. type = "jointHinge";
  33697. break;
  33698. }
  33699. nativeJointData.type = type;
  33700. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  33701. };
  33702. OimoJSPlugin.prototype.removeJoint = function (joint) {
  33703. joint.joint.physicsJoint.dispose();
  33704. };
  33705. OimoJSPlugin.prototype.isSupported = function () {
  33706. return OIMO !== undefined;
  33707. };
  33708. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  33709. if (!impostor.physicsBody.sleeping) {
  33710. //TODO check that
  33711. if (impostor.physicsBody.shapes.next) {
  33712. var parentShape = this._getLastShape(impostor.physicsBody);
  33713. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  33714. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  33715. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  33716. }
  33717. else {
  33718. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  33719. }
  33720. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  33721. }
  33722. };
  33723. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  33724. var body = impostor.physicsBody;
  33725. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  33726. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  33727. body.syncShapes();
  33728. body.awake();
  33729. };
  33730. OimoJSPlugin.prototype._getLastShape = function (body) {
  33731. var lastShape = body.shapes;
  33732. while (lastShape.next) {
  33733. lastShape = lastShape.next;
  33734. }
  33735. return lastShape;
  33736. };
  33737. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  33738. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  33739. };
  33740. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  33741. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  33742. };
  33743. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  33744. var v = impostor.physicsBody.linearVelocity;
  33745. if (!v)
  33746. return null;
  33747. return new BABYLON.Vector3(v.x, v.y, v.z);
  33748. };
  33749. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  33750. var v = impostor.physicsBody.angularVelocity;
  33751. if (!v)
  33752. return null;
  33753. return new BABYLON.Vector3(v.x, v.y, v.z);
  33754. };
  33755. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  33756. var staticBody = mass === 0;
  33757. //this will actually set the body's density and not its mass.
  33758. //But this is how oimo treats the mass variable.
  33759. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  33760. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  33761. };
  33762. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  33763. impostor.physicsBody.sleep();
  33764. };
  33765. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  33766. impostor.physicsBody.awake();
  33767. };
  33768. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  33769. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  33770. if (minDistance !== void 0) {
  33771. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  33772. }
  33773. };
  33774. OimoJSPlugin.prototype.setMotor = function (joint, force, maxForce, motorIndex) {
  33775. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  33776. if (motor) {
  33777. motor.setMotor(force, maxForce);
  33778. }
  33779. };
  33780. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  33781. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  33782. if (motor) {
  33783. motor.setLimit(upperLimit, lowerLimit || -upperLimit);
  33784. }
  33785. };
  33786. OimoJSPlugin.prototype.dispose = function () {
  33787. this.world.clear();
  33788. };
  33789. return OimoJSPlugin;
  33790. })();
  33791. BABYLON.OimoJSPlugin = OimoJSPlugin;
  33792. })(BABYLON || (BABYLON = {}));
  33793. var BABYLON;
  33794. (function (BABYLON) {
  33795. var DisplayPassPostProcess = (function (_super) {
  33796. __extends(DisplayPassPostProcess, _super);
  33797. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33798. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  33799. }
  33800. return DisplayPassPostProcess;
  33801. })(BABYLON.PostProcess);
  33802. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  33803. })(BABYLON || (BABYLON = {}));
  33804. var BABYLON;
  33805. (function (BABYLON) {
  33806. var SimplificationSettings = (function () {
  33807. function SimplificationSettings(quality, distance, optimizeMesh) {
  33808. this.quality = quality;
  33809. this.distance = distance;
  33810. this.optimizeMesh = optimizeMesh;
  33811. }
  33812. return SimplificationSettings;
  33813. })();
  33814. BABYLON.SimplificationSettings = SimplificationSettings;
  33815. var SimplificationQueue = (function () {
  33816. function SimplificationQueue() {
  33817. this.running = false;
  33818. this._simplificationArray = [];
  33819. }
  33820. SimplificationQueue.prototype.addTask = function (task) {
  33821. this._simplificationArray.push(task);
  33822. };
  33823. SimplificationQueue.prototype.executeNext = function () {
  33824. var task = this._simplificationArray.pop();
  33825. if (task) {
  33826. this.running = true;
  33827. this.runSimplification(task);
  33828. }
  33829. else {
  33830. this.running = false;
  33831. }
  33832. };
  33833. SimplificationQueue.prototype.runSimplification = function (task) {
  33834. var _this = this;
  33835. if (task.parallelProcessing) {
  33836. //parallel simplifier
  33837. task.settings.forEach(function (setting) {
  33838. var simplifier = _this.getSimplifier(task);
  33839. simplifier.simplify(setting, function (newMesh) {
  33840. task.mesh.addLODLevel(setting.distance, newMesh);
  33841. newMesh.isVisible = true;
  33842. //check if it is the last
  33843. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  33844. //all done, run the success callback.
  33845. task.successCallback();
  33846. }
  33847. _this.executeNext();
  33848. });
  33849. });
  33850. }
  33851. else {
  33852. //single simplifier.
  33853. var simplifier = this.getSimplifier(task);
  33854. var runDecimation = function (setting, callback) {
  33855. simplifier.simplify(setting, function (newMesh) {
  33856. task.mesh.addLODLevel(setting.distance, newMesh);
  33857. newMesh.isVisible = true;
  33858. //run the next quality level
  33859. callback();
  33860. });
  33861. };
  33862. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  33863. runDecimation(task.settings[loop.index], function () {
  33864. loop.executeNext();
  33865. });
  33866. }, function () {
  33867. //execution ended, run the success callback.
  33868. if (task.successCallback) {
  33869. task.successCallback();
  33870. }
  33871. _this.executeNext();
  33872. });
  33873. }
  33874. };
  33875. SimplificationQueue.prototype.getSimplifier = function (task) {
  33876. switch (task.simplificationType) {
  33877. case SimplificationType.QUADRATIC:
  33878. default:
  33879. return new QuadraticErrorSimplification(task.mesh);
  33880. }
  33881. };
  33882. return SimplificationQueue;
  33883. })();
  33884. BABYLON.SimplificationQueue = SimplificationQueue;
  33885. /**
  33886. * The implemented types of simplification.
  33887. * At the moment only Quadratic Error Decimation is implemented.
  33888. */
  33889. (function (SimplificationType) {
  33890. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  33891. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  33892. var SimplificationType = BABYLON.SimplificationType;
  33893. var DecimationTriangle = (function () {
  33894. function DecimationTriangle(vertices) {
  33895. this.vertices = vertices;
  33896. this.error = new Array(4);
  33897. this.deleted = false;
  33898. this.isDirty = false;
  33899. this.deletePending = false;
  33900. this.borderFactor = 0;
  33901. }
  33902. return DecimationTriangle;
  33903. })();
  33904. BABYLON.DecimationTriangle = DecimationTriangle;
  33905. var DecimationVertex = (function () {
  33906. function DecimationVertex(position, id) {
  33907. this.position = position;
  33908. this.id = id;
  33909. this.isBorder = true;
  33910. this.q = new QuadraticMatrix();
  33911. this.triangleCount = 0;
  33912. this.triangleStart = 0;
  33913. this.originalOffsets = [];
  33914. }
  33915. DecimationVertex.prototype.updatePosition = function (newPosition) {
  33916. this.position.copyFrom(newPosition);
  33917. };
  33918. return DecimationVertex;
  33919. })();
  33920. BABYLON.DecimationVertex = DecimationVertex;
  33921. var QuadraticMatrix = (function () {
  33922. function QuadraticMatrix(data) {
  33923. this.data = new Array(10);
  33924. for (var i = 0; i < 10; ++i) {
  33925. if (data && data[i]) {
  33926. this.data[i] = data[i];
  33927. }
  33928. else {
  33929. this.data[i] = 0;
  33930. }
  33931. }
  33932. }
  33933. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  33934. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  33935. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  33936. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  33937. return det;
  33938. };
  33939. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  33940. for (var i = 0; i < 10; ++i) {
  33941. this.data[i] += matrix.data[i];
  33942. }
  33943. };
  33944. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  33945. for (var i = 0; i < 10; ++i) {
  33946. this.data[i] += data[i];
  33947. }
  33948. };
  33949. QuadraticMatrix.prototype.add = function (matrix) {
  33950. var m = new QuadraticMatrix();
  33951. for (var i = 0; i < 10; ++i) {
  33952. m.data[i] = this.data[i] + matrix.data[i];
  33953. }
  33954. return m;
  33955. };
  33956. QuadraticMatrix.FromData = function (a, b, c, d) {
  33957. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  33958. };
  33959. //returning an array to avoid garbage collection
  33960. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  33961. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  33962. };
  33963. return QuadraticMatrix;
  33964. })();
  33965. BABYLON.QuadraticMatrix = QuadraticMatrix;
  33966. var Reference = (function () {
  33967. function Reference(vertexId, triangleId) {
  33968. this.vertexId = vertexId;
  33969. this.triangleId = triangleId;
  33970. }
  33971. return Reference;
  33972. })();
  33973. BABYLON.Reference = Reference;
  33974. /**
  33975. * An implementation of the Quadratic Error simplification algorithm.
  33976. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  33977. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  33978. * @author RaananW
  33979. */
  33980. var QuadraticErrorSimplification = (function () {
  33981. function QuadraticErrorSimplification(_mesh) {
  33982. this._mesh = _mesh;
  33983. this.initialized = false;
  33984. this.syncIterations = 5000;
  33985. this.aggressiveness = 7;
  33986. this.decimationIterations = 100;
  33987. this.boundingBoxEpsilon = BABYLON.Epsilon;
  33988. }
  33989. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  33990. var _this = this;
  33991. this.initDecimatedMesh();
  33992. //iterating through the submeshes array, one after the other.
  33993. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  33994. _this.initWithMesh(loop.index, function () {
  33995. _this.runDecimation(settings, loop.index, function () {
  33996. loop.executeNext();
  33997. });
  33998. }, settings.optimizeMesh);
  33999. }, function () {
  34000. setTimeout(function () {
  34001. successCallback(_this._reconstructedMesh);
  34002. }, 0);
  34003. });
  34004. };
  34005. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  34006. var _this = this;
  34007. var gCount = 0;
  34008. triangle.vertices.forEach(function (vertex) {
  34009. var count = 0;
  34010. var vPos = vertex.position;
  34011. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  34012. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  34013. ++count;
  34014. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  34015. ++count;
  34016. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  34017. ++count;
  34018. if (count > 1) {
  34019. ++gCount;
  34020. }
  34021. ;
  34022. });
  34023. if (gCount > 1) {
  34024. console.log(triangle, gCount);
  34025. }
  34026. return gCount > 1;
  34027. };
  34028. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  34029. var _this = this;
  34030. var targetCount = ~~(this.triangles.length * settings.quality);
  34031. var deletedTriangles = 0;
  34032. var triangleCount = this.triangles.length;
  34033. var iterationFunction = function (iteration, callback) {
  34034. setTimeout(function () {
  34035. if (iteration % 5 === 0) {
  34036. _this.updateMesh(iteration === 0);
  34037. }
  34038. for (var i = 0; i < _this.triangles.length; ++i) {
  34039. _this.triangles[i].isDirty = false;
  34040. }
  34041. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  34042. var trianglesIterator = function (i) {
  34043. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  34044. var t = _this.triangles[tIdx];
  34045. if (!t)
  34046. return;
  34047. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  34048. return;
  34049. }
  34050. for (var j = 0; j < 3; ++j) {
  34051. if (t.error[j] < threshold) {
  34052. var deleted0 = [];
  34053. var deleted1 = [];
  34054. var v0 = t.vertices[j];
  34055. var v1 = t.vertices[(j + 1) % 3];
  34056. if (v0.isBorder !== v1.isBorder)
  34057. continue;
  34058. var p = BABYLON.Vector3.Zero();
  34059. var n = BABYLON.Vector3.Zero();
  34060. var uv = BABYLON.Vector2.Zero();
  34061. var color = new BABYLON.Color4(0, 0, 0, 1);
  34062. _this.calculateError(v0, v1, p, n, uv, color);
  34063. var delTr = [];
  34064. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  34065. continue;
  34066. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  34067. continue;
  34068. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  34069. continue;
  34070. var uniqueArray = [];
  34071. delTr.forEach(function (deletedT) {
  34072. if (uniqueArray.indexOf(deletedT) === -1) {
  34073. deletedT.deletePending = true;
  34074. uniqueArray.push(deletedT);
  34075. }
  34076. });
  34077. if (uniqueArray.length % 2 !== 0) {
  34078. continue;
  34079. }
  34080. v0.q = v1.q.add(v0.q);
  34081. v0.updatePosition(p);
  34082. var tStart = _this.references.length;
  34083. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  34084. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  34085. var tCount = _this.references.length - tStart;
  34086. if (tCount <= v0.triangleCount) {
  34087. if (tCount) {
  34088. for (var c = 0; c < tCount; c++) {
  34089. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  34090. }
  34091. }
  34092. }
  34093. else {
  34094. v0.triangleStart = tStart;
  34095. }
  34096. v0.triangleCount = tCount;
  34097. break;
  34098. }
  34099. }
  34100. };
  34101. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  34102. }, 0);
  34103. };
  34104. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  34105. if (triangleCount - deletedTriangles <= targetCount)
  34106. loop.breakLoop();
  34107. else {
  34108. iterationFunction(loop.index, function () {
  34109. loop.executeNext();
  34110. });
  34111. }
  34112. }, function () {
  34113. setTimeout(function () {
  34114. //reconstruct this part of the mesh
  34115. _this.reconstructMesh(submeshIndex);
  34116. successCallback();
  34117. }, 0);
  34118. });
  34119. };
  34120. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  34121. var _this = this;
  34122. this.vertices = [];
  34123. this.triangles = [];
  34124. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34125. var indices = this._mesh.getIndices();
  34126. var submesh = this._mesh.subMeshes[submeshIndex];
  34127. var findInVertices = function (positionToSearch) {
  34128. if (optimizeMesh) {
  34129. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  34130. if (_this.vertices[ii].position.equals(positionToSearch)) {
  34131. return _this.vertices[ii];
  34132. }
  34133. }
  34134. }
  34135. return null;
  34136. };
  34137. var vertexReferences = [];
  34138. var vertexInit = function (i) {
  34139. var offset = i + submesh.verticesStart;
  34140. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  34141. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  34142. vertex.originalOffsets.push(offset);
  34143. if (vertex.id === _this.vertices.length) {
  34144. _this.vertices.push(vertex);
  34145. }
  34146. vertexReferences.push(vertex.id);
  34147. };
  34148. //var totalVertices = mesh.getTotalVertices();
  34149. var totalVertices = submesh.verticesCount;
  34150. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  34151. var indicesInit = function (i) {
  34152. var offset = (submesh.indexStart / 3) + i;
  34153. var pos = (offset * 3);
  34154. var i0 = indices[pos + 0];
  34155. var i1 = indices[pos + 1];
  34156. var i2 = indices[pos + 2];
  34157. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  34158. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  34159. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  34160. var triangle = new DecimationTriangle([v0, v1, v2]);
  34161. triangle.originalOffset = pos;
  34162. _this.triangles.push(triangle);
  34163. };
  34164. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  34165. _this.init(callback);
  34166. });
  34167. });
  34168. };
  34169. QuadraticErrorSimplification.prototype.init = function (callback) {
  34170. var _this = this;
  34171. var triangleInit1 = function (i) {
  34172. var t = _this.triangles[i];
  34173. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  34174. for (var j = 0; j < 3; j++) {
  34175. 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))));
  34176. }
  34177. };
  34178. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  34179. var triangleInit2 = function (i) {
  34180. var t = _this.triangles[i];
  34181. for (var j = 0; j < 3; ++j) {
  34182. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  34183. }
  34184. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  34185. };
  34186. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  34187. _this.initialized = true;
  34188. callback();
  34189. });
  34190. });
  34191. };
  34192. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  34193. var newTriangles = [];
  34194. var i;
  34195. for (i = 0; i < this.vertices.length; ++i) {
  34196. this.vertices[i].triangleCount = 0;
  34197. }
  34198. var t;
  34199. var j;
  34200. for (i = 0; i < this.triangles.length; ++i) {
  34201. if (!this.triangles[i].deleted) {
  34202. t = this.triangles[i];
  34203. for (j = 0; j < 3; ++j) {
  34204. t.vertices[j].triangleCount = 1;
  34205. }
  34206. newTriangles.push(t);
  34207. }
  34208. }
  34209. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  34210. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  34211. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  34212. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  34213. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34214. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34215. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34216. var vertexCount = 0;
  34217. for (i = 0; i < this.vertices.length; ++i) {
  34218. var vertex = this.vertices[i];
  34219. vertex.id = vertexCount;
  34220. if (vertex.triangleCount) {
  34221. vertex.originalOffsets.forEach(function (originalOffset) {
  34222. newPositionData.push(vertex.position.x);
  34223. newPositionData.push(vertex.position.y);
  34224. newPositionData.push(vertex.position.z);
  34225. newNormalData.push(normalData[originalOffset * 3]);
  34226. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  34227. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  34228. if (uvs && uvs.length) {
  34229. newUVsData.push(uvs[(originalOffset * 2)]);
  34230. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  34231. }
  34232. else if (colorsData && colorsData.length) {
  34233. newColorsData.push(colorsData[(originalOffset * 4)]);
  34234. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  34235. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  34236. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  34237. }
  34238. ++vertexCount;
  34239. });
  34240. }
  34241. }
  34242. var startingIndex = this._reconstructedMesh.getTotalIndices();
  34243. var startingVertex = this._reconstructedMesh.getTotalVertices();
  34244. var submeshesArray = this._reconstructedMesh.subMeshes;
  34245. this._reconstructedMesh.subMeshes = [];
  34246. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  34247. var originalIndices = this._mesh.getIndices();
  34248. for (i = 0; i < newTriangles.length; ++i) {
  34249. t = newTriangles[i]; //now get the new referencing point for each vertex
  34250. [0, 1, 2].forEach(function (idx) {
  34251. var id = originalIndices[t.originalOffset + idx];
  34252. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  34253. if (offset < 0)
  34254. offset = 0;
  34255. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  34256. });
  34257. }
  34258. //overwriting the old vertex buffers and indices.
  34259. this._reconstructedMesh.setIndices(newIndicesArray);
  34260. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  34261. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  34262. if (newUVsData.length > 0)
  34263. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  34264. if (newColorsData.length > 0)
  34265. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  34266. //create submesh
  34267. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  34268. if (submeshIndex > 0) {
  34269. this._reconstructedMesh.subMeshes = [];
  34270. submeshesArray.forEach(function (submesh) {
  34271. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  34272. });
  34273. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  34274. }
  34275. };
  34276. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  34277. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  34278. this._reconstructedMesh.material = this._mesh.material;
  34279. this._reconstructedMesh.parent = this._mesh.parent;
  34280. this._reconstructedMesh.isVisible = false;
  34281. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  34282. };
  34283. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  34284. for (var i = 0; i < vertex1.triangleCount; ++i) {
  34285. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  34286. if (t.deleted)
  34287. continue;
  34288. var s = this.references[vertex1.triangleStart + i].vertexId;
  34289. var v1 = t.vertices[(s + 1) % 3];
  34290. var v2 = t.vertices[(s + 2) % 3];
  34291. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  34292. deletedArray[i] = true;
  34293. delTr.push(t);
  34294. continue;
  34295. }
  34296. var d1 = v1.position.subtract(point);
  34297. d1 = d1.normalize();
  34298. var d2 = v2.position.subtract(point);
  34299. d2 = d2.normalize();
  34300. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  34301. return true;
  34302. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  34303. deletedArray[i] = false;
  34304. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  34305. return true;
  34306. }
  34307. return false;
  34308. };
  34309. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  34310. var newDeleted = deletedTriangles;
  34311. for (var i = 0; i < vertex.triangleCount; ++i) {
  34312. var ref = this.references[vertex.triangleStart + i];
  34313. var t = this.triangles[ref.triangleId];
  34314. if (t.deleted)
  34315. continue;
  34316. if (deletedArray[i] && t.deletePending) {
  34317. t.deleted = true;
  34318. newDeleted++;
  34319. continue;
  34320. }
  34321. t.vertices[ref.vertexId] = origVertex;
  34322. t.isDirty = true;
  34323. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  34324. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  34325. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  34326. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  34327. this.references.push(ref);
  34328. }
  34329. return newDeleted;
  34330. };
  34331. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  34332. for (var i = 0; i < this.vertices.length; ++i) {
  34333. var vCount = [];
  34334. var vId = [];
  34335. var v = this.vertices[i];
  34336. var j;
  34337. for (j = 0; j < v.triangleCount; ++j) {
  34338. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  34339. for (var ii = 0; ii < 3; ii++) {
  34340. var ofs = 0;
  34341. var vv = triangle.vertices[ii];
  34342. while (ofs < vCount.length) {
  34343. if (vId[ofs] === vv.id)
  34344. break;
  34345. ++ofs;
  34346. }
  34347. if (ofs === vCount.length) {
  34348. vCount.push(1);
  34349. vId.push(vv.id);
  34350. }
  34351. else {
  34352. vCount[ofs]++;
  34353. }
  34354. }
  34355. }
  34356. for (j = 0; j < vCount.length; ++j) {
  34357. if (vCount[j] === 1) {
  34358. this.vertices[vId[j]].isBorder = true;
  34359. }
  34360. else {
  34361. this.vertices[vId[j]].isBorder = false;
  34362. }
  34363. }
  34364. }
  34365. };
  34366. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  34367. if (identifyBorders === void 0) { identifyBorders = false; }
  34368. var i;
  34369. if (!identifyBorders) {
  34370. var newTrianglesVector = [];
  34371. for (i = 0; i < this.triangles.length; ++i) {
  34372. if (!this.triangles[i].deleted) {
  34373. newTrianglesVector.push(this.triangles[i]);
  34374. }
  34375. }
  34376. this.triangles = newTrianglesVector;
  34377. }
  34378. for (i = 0; i < this.vertices.length; ++i) {
  34379. this.vertices[i].triangleCount = 0;
  34380. this.vertices[i].triangleStart = 0;
  34381. }
  34382. var t;
  34383. var j;
  34384. var v;
  34385. for (i = 0; i < this.triangles.length; ++i) {
  34386. t = this.triangles[i];
  34387. for (j = 0; j < 3; ++j) {
  34388. v = t.vertices[j];
  34389. v.triangleCount++;
  34390. }
  34391. }
  34392. var tStart = 0;
  34393. for (i = 0; i < this.vertices.length; ++i) {
  34394. this.vertices[i].triangleStart = tStart;
  34395. tStart += this.vertices[i].triangleCount;
  34396. this.vertices[i].triangleCount = 0;
  34397. }
  34398. var newReferences = new Array(this.triangles.length * 3);
  34399. for (i = 0; i < this.triangles.length; ++i) {
  34400. t = this.triangles[i];
  34401. for (j = 0; j < 3; ++j) {
  34402. v = t.vertices[j];
  34403. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  34404. v.triangleCount++;
  34405. }
  34406. }
  34407. this.references = newReferences;
  34408. if (identifyBorders) {
  34409. this.identifyBorder();
  34410. }
  34411. };
  34412. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  34413. var x = point.x;
  34414. var y = point.y;
  34415. var z = point.z;
  34416. 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
  34417. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  34418. };
  34419. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  34420. var q = vertex1.q.add(vertex2.q);
  34421. var border = vertex1.isBorder && vertex2.isBorder;
  34422. var error = 0;
  34423. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  34424. if (qDet !== 0 && !border) {
  34425. if (!pointResult) {
  34426. pointResult = BABYLON.Vector3.Zero();
  34427. }
  34428. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  34429. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  34430. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  34431. error = this.vertexError(q, pointResult);
  34432. }
  34433. else {
  34434. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  34435. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  34436. var error1 = this.vertexError(q, vertex1.position);
  34437. var error2 = this.vertexError(q, vertex2.position);
  34438. var error3 = this.vertexError(q, p3);
  34439. error = Math.min(error1, error2, error3);
  34440. if (error === error1) {
  34441. if (pointResult) {
  34442. pointResult.copyFrom(vertex1.position);
  34443. }
  34444. }
  34445. else if (error === error2) {
  34446. if (pointResult) {
  34447. pointResult.copyFrom(vertex2.position);
  34448. }
  34449. }
  34450. else {
  34451. if (pointResult) {
  34452. pointResult.copyFrom(p3);
  34453. }
  34454. }
  34455. }
  34456. return error;
  34457. };
  34458. return QuadraticErrorSimplification;
  34459. })();
  34460. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  34461. })(BABYLON || (BABYLON = {}));
  34462. var BABYLON;
  34463. (function (BABYLON) {
  34464. var serializedGeometries = [];
  34465. var serializeGeometry = function (geometry, serializationGeometries) {
  34466. if (serializedGeometries[geometry.id]) {
  34467. return;
  34468. }
  34469. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  34470. serializationGeometries.boxes.push(geometry.serialize());
  34471. }
  34472. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  34473. serializationGeometries.spheres.push(geometry.serialize());
  34474. }
  34475. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  34476. serializationGeometries.cylinders.push(geometry.serialize());
  34477. }
  34478. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  34479. serializationGeometries.toruses.push(geometry.serialize());
  34480. }
  34481. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  34482. serializationGeometries.grounds.push(geometry.serialize());
  34483. }
  34484. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  34485. serializationGeometries.planes.push(geometry.serialize());
  34486. }
  34487. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  34488. serializationGeometries.torusKnots.push(geometry.serialize());
  34489. }
  34490. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  34491. throw new Error("Unknown primitive type");
  34492. }
  34493. else {
  34494. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  34495. }
  34496. serializedGeometries[geometry.id] = true;
  34497. };
  34498. var serializeMesh = function (mesh, serializationScene) {
  34499. var serializationObject = {};
  34500. serializationObject.name = mesh.name;
  34501. serializationObject.id = mesh.id;
  34502. if (BABYLON.Tags.HasTags(mesh)) {
  34503. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  34504. }
  34505. serializationObject.position = mesh.position.asArray();
  34506. if (mesh.rotationQuaternion) {
  34507. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  34508. }
  34509. else if (mesh.rotation) {
  34510. serializationObject.rotation = mesh.rotation.asArray();
  34511. }
  34512. serializationObject.scaling = mesh.scaling.asArray();
  34513. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  34514. serializationObject.isEnabled = mesh.isEnabled();
  34515. serializationObject.isVisible = mesh.isVisible;
  34516. serializationObject.infiniteDistance = mesh.infiniteDistance;
  34517. serializationObject.pickable = mesh.isPickable;
  34518. serializationObject.receiveShadows = mesh.receiveShadows;
  34519. serializationObject.billboardMode = mesh.billboardMode;
  34520. serializationObject.visibility = mesh.visibility;
  34521. serializationObject.checkCollisions = mesh.checkCollisions;
  34522. // Parent
  34523. if (mesh.parent) {
  34524. serializationObject.parentId = mesh.parent.id;
  34525. }
  34526. // Geometry
  34527. var geometry = mesh._geometry;
  34528. if (geometry) {
  34529. var geometryId = geometry.id;
  34530. serializationObject.geometryId = geometryId;
  34531. if (!mesh.getScene().getGeometryByID(geometryId)) {
  34532. // 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
  34533. serializeGeometry(geometry, serializationScene.geometries);
  34534. }
  34535. // SubMeshes
  34536. serializationObject.subMeshes = [];
  34537. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34538. var subMesh = mesh.subMeshes[subIndex];
  34539. serializationObject.subMeshes.push({
  34540. materialIndex: subMesh.materialIndex,
  34541. verticesStart: subMesh.verticesStart,
  34542. verticesCount: subMesh.verticesCount,
  34543. indexStart: subMesh.indexStart,
  34544. indexCount: subMesh.indexCount
  34545. });
  34546. }
  34547. }
  34548. // Material
  34549. if (mesh.material) {
  34550. serializationObject.materialId = mesh.material.id;
  34551. }
  34552. else {
  34553. mesh.material = null;
  34554. }
  34555. // Skeleton
  34556. if (mesh.skeleton) {
  34557. serializationObject.skeletonId = mesh.skeleton.id;
  34558. }
  34559. // Physics
  34560. if (mesh.getPhysicsImpostor().type !== BABYLON.PhysicsEngine.NoImpostor) {
  34561. serializationObject.physicsMass = mesh.getPhysicsMass();
  34562. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  34563. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  34564. switch (mesh.getPhysicsImpostor().type) {
  34565. case BABYLON.PhysicsEngine.BoxImpostor:
  34566. serializationObject.physicsImpostor = 1;
  34567. break;
  34568. case BABYLON.PhysicsEngine.SphereImpostor:
  34569. serializationObject.physicsImpostor = 2;
  34570. break;
  34571. }
  34572. }
  34573. // Instances
  34574. serializationObject.instances = [];
  34575. for (var index = 0; index < mesh.instances.length; index++) {
  34576. var instance = mesh.instances[index];
  34577. var serializationInstance = {
  34578. name: instance.name,
  34579. position: instance.position.asArray(),
  34580. scaling: instance.scaling.asArray()
  34581. };
  34582. if (instance.rotationQuaternion) {
  34583. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34584. }
  34585. else if (instance.rotation) {
  34586. serializationInstance.rotation = instance.rotation.asArray();
  34587. }
  34588. serializationObject.instances.push(serializationInstance);
  34589. // Animations
  34590. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34591. serializationInstance.ranges = instance.serializeAnimationRanges();
  34592. }
  34593. // Animations
  34594. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  34595. serializationObject.ranges = mesh.serializeAnimationRanges();
  34596. // Layer mask
  34597. serializationObject.layerMask = mesh.layerMask;
  34598. return serializationObject;
  34599. };
  34600. var finalizeSingleMesh = function (mesh, serializationObject) {
  34601. //only works if the mesh is already loaded
  34602. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  34603. //serialize material
  34604. if (mesh.material) {
  34605. if (mesh.material instanceof BABYLON.StandardMaterial) {
  34606. serializationObject.materials = serializationObject.materials || [];
  34607. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  34608. serializationObject.materials.push(mesh.material.serialize());
  34609. }
  34610. }
  34611. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  34612. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  34613. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  34614. serializationObject.multiMaterials.push(mesh.material.serialize());
  34615. }
  34616. }
  34617. }
  34618. //serialize geometry
  34619. var geometry = mesh._geometry;
  34620. if (geometry) {
  34621. if (!serializationObject.geometries) {
  34622. serializationObject.geometries = {};
  34623. serializationObject.geometries.boxes = [];
  34624. serializationObject.geometries.spheres = [];
  34625. serializationObject.geometries.cylinders = [];
  34626. serializationObject.geometries.toruses = [];
  34627. serializationObject.geometries.grounds = [];
  34628. serializationObject.geometries.planes = [];
  34629. serializationObject.geometries.torusKnots = [];
  34630. serializationObject.geometries.vertexData = [];
  34631. }
  34632. serializeGeometry(geometry, serializationObject.geometries);
  34633. }
  34634. // Skeletons
  34635. if (mesh.skeleton) {
  34636. serializationObject.skeletons = serializationObject.skeletons || [];
  34637. serializationObject.skeletons.push(mesh.skeleton.serialize());
  34638. }
  34639. //serialize the actual mesh
  34640. serializationObject.meshes = serializationObject.meshes || [];
  34641. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  34642. }
  34643. };
  34644. var SceneSerializer = (function () {
  34645. function SceneSerializer() {
  34646. }
  34647. SceneSerializer.ClearCache = function () {
  34648. serializedGeometries = [];
  34649. };
  34650. SceneSerializer.Serialize = function (scene) {
  34651. var serializationObject = {};
  34652. // Scene
  34653. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  34654. serializationObject.autoClear = scene.autoClear;
  34655. serializationObject.clearColor = scene.clearColor.asArray();
  34656. serializationObject.ambientColor = scene.ambientColor.asArray();
  34657. serializationObject.gravity = scene.gravity.asArray();
  34658. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  34659. serializationObject.workerCollisions = scene.workerCollisions;
  34660. // Fog
  34661. if (scene.fogMode && scene.fogMode !== 0) {
  34662. serializationObject.fogMode = scene.fogMode;
  34663. serializationObject.fogColor = scene.fogColor.asArray();
  34664. serializationObject.fogStart = scene.fogStart;
  34665. serializationObject.fogEnd = scene.fogEnd;
  34666. serializationObject.fogDensity = scene.fogDensity;
  34667. }
  34668. //Physics
  34669. if (scene.isPhysicsEnabled()) {
  34670. serializationObject.physicsEnabled = true;
  34671. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  34672. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  34673. }
  34674. // Lights
  34675. serializationObject.lights = [];
  34676. var index;
  34677. var light;
  34678. for (index = 0; index < scene.lights.length; index++) {
  34679. light = scene.lights[index];
  34680. serializationObject.lights.push(light.serialize());
  34681. }
  34682. // Cameras
  34683. serializationObject.cameras = [];
  34684. for (index = 0; index < scene.cameras.length; index++) {
  34685. var camera = scene.cameras[index];
  34686. serializationObject.cameras.push(camera.serialize());
  34687. }
  34688. if (scene.activeCamera) {
  34689. serializationObject.activeCameraID = scene.activeCamera.id;
  34690. }
  34691. // Animations
  34692. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  34693. // Materials
  34694. serializationObject.materials = [];
  34695. serializationObject.multiMaterials = [];
  34696. var material;
  34697. for (index = 0; index < scene.materials.length; index++) {
  34698. material = scene.materials[index];
  34699. serializationObject.materials.push(material.serialize());
  34700. }
  34701. // MultiMaterials
  34702. serializationObject.multiMaterials = [];
  34703. for (index = 0; index < scene.multiMaterials.length; index++) {
  34704. var multiMaterial = scene.multiMaterials[index];
  34705. serializationObject.multiMaterials.push(multiMaterial.serialize());
  34706. }
  34707. // Skeletons
  34708. serializationObject.skeletons = [];
  34709. for (index = 0; index < scene.skeletons.length; index++) {
  34710. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  34711. }
  34712. // Geometries
  34713. serializationObject.geometries = {};
  34714. serializationObject.geometries.boxes = [];
  34715. serializationObject.geometries.spheres = [];
  34716. serializationObject.geometries.cylinders = [];
  34717. serializationObject.geometries.toruses = [];
  34718. serializationObject.geometries.grounds = [];
  34719. serializationObject.geometries.planes = [];
  34720. serializationObject.geometries.torusKnots = [];
  34721. serializationObject.geometries.vertexData = [];
  34722. serializedGeometries = [];
  34723. var geometries = scene.getGeometries();
  34724. for (index = 0; index < geometries.length; index++) {
  34725. var geometry = geometries[index];
  34726. if (geometry.isReady()) {
  34727. serializeGeometry(geometry, serializationObject.geometries);
  34728. }
  34729. }
  34730. // Meshes
  34731. serializationObject.meshes = [];
  34732. for (index = 0; index < scene.meshes.length; index++) {
  34733. var abstractMesh = scene.meshes[index];
  34734. if (abstractMesh instanceof BABYLON.Mesh) {
  34735. var mesh = abstractMesh;
  34736. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  34737. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  34738. }
  34739. }
  34740. }
  34741. // Particles Systems
  34742. serializationObject.particleSystems = [];
  34743. for (index = 0; index < scene.particleSystems.length; index++) {
  34744. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  34745. }
  34746. // Lens flares
  34747. serializationObject.lensFlareSystems = [];
  34748. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  34749. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  34750. }
  34751. // Shadows
  34752. serializationObject.shadowGenerators = [];
  34753. for (index = 0; index < scene.lights.length; index++) {
  34754. light = scene.lights[index];
  34755. if (light.getShadowGenerator()) {
  34756. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  34757. }
  34758. }
  34759. return serializationObject;
  34760. };
  34761. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  34762. if (withParents === void 0) { withParents = false; }
  34763. if (withChildren === void 0) { withChildren = false; }
  34764. var serializationObject = {};
  34765. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  34766. if (withParents || withChildren) {
  34767. //deliberate for loop! not for each, appended should be processed as well.
  34768. for (var i = 0; i < toSerialize.length; ++i) {
  34769. if (withChildren) {
  34770. toSerialize[i].getDescendants().forEach(function (node) {
  34771. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  34772. toSerialize.push(node);
  34773. }
  34774. });
  34775. }
  34776. //make sure the array doesn't contain the object already
  34777. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  34778. toSerialize.push(toSerialize[i].parent);
  34779. }
  34780. }
  34781. }
  34782. toSerialize.forEach(function (mesh) {
  34783. finalizeSingleMesh(mesh, serializationObject);
  34784. });
  34785. return serializationObject;
  34786. };
  34787. return SceneSerializer;
  34788. })();
  34789. BABYLON.SceneSerializer = SceneSerializer;
  34790. })(BABYLON || (BABYLON = {}));
  34791. var BABYLON;
  34792. (function (BABYLON) {
  34793. // Unique ID when we import meshes from Babylon to CSG
  34794. var currentCSGMeshId = 0;
  34795. // # class Vertex
  34796. // Represents a vertex of a polygon. Use your own vertex class instead of this
  34797. // one to provide additional features like texture coordinates and vertex
  34798. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  34799. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  34800. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  34801. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  34802. // is not used anywhere else.
  34803. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  34804. var Vertex = (function () {
  34805. function Vertex(pos, normal, uv) {
  34806. this.pos = pos;
  34807. this.normal = normal;
  34808. this.uv = uv;
  34809. }
  34810. Vertex.prototype.clone = function () {
  34811. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  34812. };
  34813. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  34814. // orientation of a polygon is flipped.
  34815. Vertex.prototype.flip = function () {
  34816. this.normal = this.normal.scale(-1);
  34817. };
  34818. // Create a new vertex between this vertex and `other` by linearly
  34819. // interpolating all properties using a parameter of `t`. Subclasses should
  34820. // override this to interpolate additional properties.
  34821. Vertex.prototype.interpolate = function (other, t) {
  34822. 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));
  34823. };
  34824. return Vertex;
  34825. })();
  34826. // # class Plane
  34827. // Represents a plane in 3D space.
  34828. var Plane = (function () {
  34829. function Plane(normal, w) {
  34830. this.normal = normal;
  34831. this.w = w;
  34832. }
  34833. Plane.FromPoints = function (a, b, c) {
  34834. var v0 = c.subtract(a);
  34835. var v1 = b.subtract(a);
  34836. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  34837. return null;
  34838. }
  34839. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  34840. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  34841. };
  34842. Plane.prototype.clone = function () {
  34843. return new Plane(this.normal.clone(), this.w);
  34844. };
  34845. Plane.prototype.flip = function () {
  34846. this.normal.scaleInPlace(-1);
  34847. this.w = -this.w;
  34848. };
  34849. // Split `polygon` by this plane if needed, then put the polygon or polygon
  34850. // fragments in the appropriate lists. Coplanar polygons go into either
  34851. // `coplanarFront` or `coplanarBack` depending on their orientation with
  34852. // respect to this plane. Polygons in front or in back of this plane go into
  34853. // either `front` or `back`.
  34854. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  34855. var COPLANAR = 0;
  34856. var FRONT = 1;
  34857. var BACK = 2;
  34858. var SPANNING = 3;
  34859. // Classify each point as well as the entire polygon into one of the above
  34860. // four classes.
  34861. var polygonType = 0;
  34862. var types = [];
  34863. var i;
  34864. var t;
  34865. for (i = 0; i < polygon.vertices.length; i++) {
  34866. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  34867. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  34868. polygonType |= type;
  34869. types.push(type);
  34870. }
  34871. // Put the polygon in the correct list, splitting it when necessary.
  34872. switch (polygonType) {
  34873. case COPLANAR:
  34874. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  34875. break;
  34876. case FRONT:
  34877. front.push(polygon);
  34878. break;
  34879. case BACK:
  34880. back.push(polygon);
  34881. break;
  34882. case SPANNING:
  34883. var f = [], b = [];
  34884. for (i = 0; i < polygon.vertices.length; i++) {
  34885. var j = (i + 1) % polygon.vertices.length;
  34886. var ti = types[i], tj = types[j];
  34887. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  34888. if (ti !== BACK)
  34889. f.push(vi);
  34890. if (ti !== FRONT)
  34891. b.push(ti !== BACK ? vi.clone() : vi);
  34892. if ((ti | tj) === SPANNING) {
  34893. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  34894. var v = vi.interpolate(vj, t);
  34895. f.push(v);
  34896. b.push(v.clone());
  34897. }
  34898. }
  34899. var poly;
  34900. if (f.length >= 3) {
  34901. poly = new Polygon(f, polygon.shared);
  34902. if (poly.plane)
  34903. front.push(poly);
  34904. }
  34905. if (b.length >= 3) {
  34906. poly = new Polygon(b, polygon.shared);
  34907. if (poly.plane)
  34908. back.push(poly);
  34909. }
  34910. break;
  34911. }
  34912. };
  34913. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  34914. // point is on the plane.
  34915. Plane.EPSILON = 1e-5;
  34916. return Plane;
  34917. })();
  34918. // # class Polygon
  34919. // Represents a convex polygon. The vertices used to initialize a polygon must
  34920. // be coplanar and form a convex loop.
  34921. //
  34922. // Each convex polygon has a `shared` property, which is shared between all
  34923. // polygons that are clones of each other or were split from the same polygon.
  34924. // This can be used to define per-polygon properties (such as surface color).
  34925. var Polygon = (function () {
  34926. function Polygon(vertices, shared) {
  34927. this.vertices = vertices;
  34928. this.shared = shared;
  34929. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  34930. }
  34931. Polygon.prototype.clone = function () {
  34932. var vertices = this.vertices.map(function (v) { return v.clone(); });
  34933. return new Polygon(vertices, this.shared);
  34934. };
  34935. Polygon.prototype.flip = function () {
  34936. this.vertices.reverse().map(function (v) { v.flip(); });
  34937. this.plane.flip();
  34938. };
  34939. return Polygon;
  34940. })();
  34941. // # class Node
  34942. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  34943. // by picking a polygon to split along. That polygon (and all other coplanar
  34944. // polygons) are added directly to that node and the other polygons are added to
  34945. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  34946. // no distinction between internal and leaf nodes.
  34947. var Node = (function () {
  34948. function Node(polygons) {
  34949. this.plane = null;
  34950. this.front = null;
  34951. this.back = null;
  34952. this.polygons = [];
  34953. if (polygons) {
  34954. this.build(polygons);
  34955. }
  34956. }
  34957. Node.prototype.clone = function () {
  34958. var node = new Node();
  34959. node.plane = this.plane && this.plane.clone();
  34960. node.front = this.front && this.front.clone();
  34961. node.back = this.back && this.back.clone();
  34962. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  34963. return node;
  34964. };
  34965. // Convert solid space to empty space and empty space to solid space.
  34966. Node.prototype.invert = function () {
  34967. for (var i = 0; i < this.polygons.length; i++) {
  34968. this.polygons[i].flip();
  34969. }
  34970. if (this.plane) {
  34971. this.plane.flip();
  34972. }
  34973. if (this.front) {
  34974. this.front.invert();
  34975. }
  34976. if (this.back) {
  34977. this.back.invert();
  34978. }
  34979. var temp = this.front;
  34980. this.front = this.back;
  34981. this.back = temp;
  34982. };
  34983. // Recursively remove all polygons in `polygons` that are inside this BSP
  34984. // tree.
  34985. Node.prototype.clipPolygons = function (polygons) {
  34986. if (!this.plane)
  34987. return polygons.slice();
  34988. var front = [], back = [];
  34989. for (var i = 0; i < polygons.length; i++) {
  34990. this.plane.splitPolygon(polygons[i], front, back, front, back);
  34991. }
  34992. if (this.front) {
  34993. front = this.front.clipPolygons(front);
  34994. }
  34995. if (this.back) {
  34996. back = this.back.clipPolygons(back);
  34997. }
  34998. else {
  34999. back = [];
  35000. }
  35001. return front.concat(back);
  35002. };
  35003. // Remove all polygons in this BSP tree that are inside the other BSP tree
  35004. // `bsp`.
  35005. Node.prototype.clipTo = function (bsp) {
  35006. this.polygons = bsp.clipPolygons(this.polygons);
  35007. if (this.front)
  35008. this.front.clipTo(bsp);
  35009. if (this.back)
  35010. this.back.clipTo(bsp);
  35011. };
  35012. // Return a list of all polygons in this BSP tree.
  35013. Node.prototype.allPolygons = function () {
  35014. var polygons = this.polygons.slice();
  35015. if (this.front)
  35016. polygons = polygons.concat(this.front.allPolygons());
  35017. if (this.back)
  35018. polygons = polygons.concat(this.back.allPolygons());
  35019. return polygons;
  35020. };
  35021. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  35022. // new polygons are filtered down to the bottom of the tree and become new
  35023. // nodes there. Each set of polygons is partitioned using the first polygon
  35024. // (no heuristic is used to pick a good split).
  35025. Node.prototype.build = function (polygons) {
  35026. if (!polygons.length)
  35027. return;
  35028. if (!this.plane)
  35029. this.plane = polygons[0].plane.clone();
  35030. var front = [], back = [];
  35031. for (var i = 0; i < polygons.length; i++) {
  35032. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  35033. }
  35034. if (front.length) {
  35035. if (!this.front)
  35036. this.front = new Node();
  35037. this.front.build(front);
  35038. }
  35039. if (back.length) {
  35040. if (!this.back)
  35041. this.back = new Node();
  35042. this.back.build(back);
  35043. }
  35044. };
  35045. return Node;
  35046. })();
  35047. var CSG = (function () {
  35048. function CSG() {
  35049. this.polygons = new Array();
  35050. }
  35051. // Convert BABYLON.Mesh to BABYLON.CSG
  35052. CSG.FromMesh = function (mesh) {
  35053. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  35054. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  35055. if (mesh instanceof BABYLON.Mesh) {
  35056. mesh.computeWorldMatrix(true);
  35057. matrix = mesh.getWorldMatrix();
  35058. meshPosition = mesh.position.clone();
  35059. meshRotation = mesh.rotation.clone();
  35060. if (mesh.rotationQuaternion) {
  35061. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  35062. }
  35063. meshScaling = mesh.scaling.clone();
  35064. }
  35065. else {
  35066. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  35067. }
  35068. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35069. var subMeshes = mesh.subMeshes;
  35070. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  35071. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  35072. vertices = [];
  35073. for (var j = 0; j < 3; j++) {
  35074. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  35075. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  35076. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  35077. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  35078. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  35079. vertex = new Vertex(position, normal, uv);
  35080. vertices.push(vertex);
  35081. }
  35082. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  35083. // To handle the case of degenerated triangle
  35084. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  35085. if (polygon.plane)
  35086. polygons.push(polygon);
  35087. }
  35088. }
  35089. var csg = CSG.FromPolygons(polygons);
  35090. csg.matrix = matrix;
  35091. csg.position = meshPosition;
  35092. csg.rotation = meshRotation;
  35093. csg.scaling = meshScaling;
  35094. csg.rotationQuaternion = meshRotationQuaternion;
  35095. currentCSGMeshId++;
  35096. return csg;
  35097. };
  35098. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  35099. CSG.FromPolygons = function (polygons) {
  35100. var csg = new CSG();
  35101. csg.polygons = polygons;
  35102. return csg;
  35103. };
  35104. CSG.prototype.clone = function () {
  35105. var csg = new CSG();
  35106. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  35107. csg.copyTransformAttributes(this);
  35108. return csg;
  35109. };
  35110. CSG.prototype.toPolygons = function () {
  35111. return this.polygons;
  35112. };
  35113. CSG.prototype.union = function (csg) {
  35114. var a = new Node(this.clone().polygons);
  35115. var b = new Node(csg.clone().polygons);
  35116. a.clipTo(b);
  35117. b.clipTo(a);
  35118. b.invert();
  35119. b.clipTo(a);
  35120. b.invert();
  35121. a.build(b.allPolygons());
  35122. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  35123. };
  35124. CSG.prototype.unionInPlace = function (csg) {
  35125. var a = new Node(this.polygons);
  35126. var b = new Node(csg.polygons);
  35127. a.clipTo(b);
  35128. b.clipTo(a);
  35129. b.invert();
  35130. b.clipTo(a);
  35131. b.invert();
  35132. a.build(b.allPolygons());
  35133. this.polygons = a.allPolygons();
  35134. };
  35135. CSG.prototype.subtract = function (csg) {
  35136. var a = new Node(this.clone().polygons);
  35137. var b = new Node(csg.clone().polygons);
  35138. a.invert();
  35139. a.clipTo(b);
  35140. b.clipTo(a);
  35141. b.invert();
  35142. b.clipTo(a);
  35143. b.invert();
  35144. a.build(b.allPolygons());
  35145. a.invert();
  35146. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  35147. };
  35148. CSG.prototype.subtractInPlace = function (csg) {
  35149. var a = new Node(this.polygons);
  35150. var b = new Node(csg.polygons);
  35151. a.invert();
  35152. a.clipTo(b);
  35153. b.clipTo(a);
  35154. b.invert();
  35155. b.clipTo(a);
  35156. b.invert();
  35157. a.build(b.allPolygons());
  35158. a.invert();
  35159. this.polygons = a.allPolygons();
  35160. };
  35161. CSG.prototype.intersect = function (csg) {
  35162. var a = new Node(this.clone().polygons);
  35163. var b = new Node(csg.clone().polygons);
  35164. a.invert();
  35165. b.clipTo(a);
  35166. b.invert();
  35167. a.clipTo(b);
  35168. b.clipTo(a);
  35169. a.build(b.allPolygons());
  35170. a.invert();
  35171. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  35172. };
  35173. CSG.prototype.intersectInPlace = function (csg) {
  35174. var a = new Node(this.polygons);
  35175. var b = new Node(csg.polygons);
  35176. a.invert();
  35177. b.clipTo(a);
  35178. b.invert();
  35179. a.clipTo(b);
  35180. b.clipTo(a);
  35181. a.build(b.allPolygons());
  35182. a.invert();
  35183. this.polygons = a.allPolygons();
  35184. };
  35185. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  35186. // not modified.
  35187. CSG.prototype.inverse = function () {
  35188. var csg = this.clone();
  35189. csg.inverseInPlace();
  35190. return csg;
  35191. };
  35192. CSG.prototype.inverseInPlace = function () {
  35193. this.polygons.map(function (p) { p.flip(); });
  35194. };
  35195. // This is used to keep meshes transformations so they can be restored
  35196. // when we build back a Babylon Mesh
  35197. // NB : All CSG operations are performed in world coordinates
  35198. CSG.prototype.copyTransformAttributes = function (csg) {
  35199. this.matrix = csg.matrix;
  35200. this.position = csg.position;
  35201. this.rotation = csg.rotation;
  35202. this.scaling = csg.scaling;
  35203. this.rotationQuaternion = csg.rotationQuaternion;
  35204. return this;
  35205. };
  35206. // Build Raw mesh from CSG
  35207. // Coordinates here are in world space
  35208. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  35209. var matrix = this.matrix.clone();
  35210. matrix.invert();
  35211. 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;
  35212. if (keepSubMeshes) {
  35213. // Sort Polygons, since subMeshes are indices range
  35214. polygons.sort(function (a, b) {
  35215. if (a.shared.meshId === b.shared.meshId) {
  35216. return a.shared.subMeshId - b.shared.subMeshId;
  35217. }
  35218. else {
  35219. return a.shared.meshId - b.shared.meshId;
  35220. }
  35221. });
  35222. }
  35223. for (var i = 0, il = polygons.length; i < il; i++) {
  35224. polygon = polygons[i];
  35225. // Building SubMeshes
  35226. if (!subMesh_dict[polygon.shared.meshId]) {
  35227. subMesh_dict[polygon.shared.meshId] = {};
  35228. }
  35229. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  35230. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  35231. indexStart: +Infinity,
  35232. indexEnd: -Infinity,
  35233. materialIndex: polygon.shared.materialIndex
  35234. };
  35235. }
  35236. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  35237. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  35238. polygonIndices[0] = 0;
  35239. polygonIndices[1] = j - 1;
  35240. polygonIndices[2] = j;
  35241. for (var k = 0; k < 3; k++) {
  35242. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  35243. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  35244. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  35245. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  35246. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  35247. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  35248. // Check if 2 points can be merged
  35249. if (!(typeof vertex_idx !== 'undefined' &&
  35250. normals[vertex_idx * 3] === localNormal.x &&
  35251. normals[vertex_idx * 3 + 1] === localNormal.y &&
  35252. normals[vertex_idx * 3 + 2] === localNormal.z &&
  35253. uvs[vertex_idx * 2] === uv.x &&
  35254. uvs[vertex_idx * 2 + 1] === uv.y)) {
  35255. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  35256. uvs.push(uv.x, uv.y);
  35257. normals.push(normal.x, normal.y, normal.z);
  35258. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  35259. }
  35260. indices.push(vertex_idx);
  35261. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  35262. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  35263. currentIndex++;
  35264. }
  35265. }
  35266. }
  35267. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  35268. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  35269. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  35270. mesh.setIndices(indices);
  35271. if (keepSubMeshes) {
  35272. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  35273. var materialIndexOffset = 0, materialMaxIndex;
  35274. mesh.subMeshes = new Array();
  35275. for (var m in subMesh_dict) {
  35276. materialMaxIndex = -1;
  35277. for (var sm in subMesh_dict[m]) {
  35278. subMesh_obj = subMesh_dict[m][sm];
  35279. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  35280. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  35281. }
  35282. materialIndexOffset += ++materialMaxIndex;
  35283. }
  35284. }
  35285. return mesh;
  35286. };
  35287. // Build Mesh from CSG taking material and transforms into account
  35288. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  35289. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  35290. mesh.material = material;
  35291. mesh.position.copyFrom(this.position);
  35292. mesh.rotation.copyFrom(this.rotation);
  35293. if (this.rotationQuaternion) {
  35294. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  35295. }
  35296. mesh.scaling.copyFrom(this.scaling);
  35297. mesh.computeWorldMatrix(true);
  35298. return mesh;
  35299. };
  35300. return CSG;
  35301. })();
  35302. BABYLON.CSG = CSG;
  35303. })(BABYLON || (BABYLON = {}));
  35304. var BABYLON;
  35305. (function (BABYLON) {
  35306. var VRDistortionCorrectionPostProcess = (function (_super) {
  35307. __extends(VRDistortionCorrectionPostProcess, _super);
  35308. //ANY
  35309. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  35310. var _this = this;
  35311. _super.call(this, name, "vrDistortionCorrection", [
  35312. 'LensCenter',
  35313. 'Scale',
  35314. 'ScaleIn',
  35315. 'HmdWarpParam'
  35316. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  35317. this._isRightEye = isRightEye;
  35318. this._distortionFactors = vrMetrics.distortionK;
  35319. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  35320. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  35321. this.onSizeChanged = function () {
  35322. _this.aspectRatio = _this.width * .5 / _this.height;
  35323. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  35324. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  35325. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  35326. };
  35327. this.onApply = function (effect) {
  35328. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  35329. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  35330. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  35331. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  35332. };
  35333. }
  35334. return VRDistortionCorrectionPostProcess;
  35335. })(BABYLON.PostProcess);
  35336. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  35337. })(BABYLON || (BABYLON = {}));
  35338. // Mainly based on these 2 articles :
  35339. // 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
  35340. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  35341. var BABYLON;
  35342. (function (BABYLON) {
  35343. (function (JoystickAxis) {
  35344. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  35345. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  35346. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  35347. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  35348. var JoystickAxis = BABYLON.JoystickAxis;
  35349. var VirtualJoystick = (function () {
  35350. function VirtualJoystick(leftJoystick) {
  35351. var _this = this;
  35352. if (leftJoystick) {
  35353. this._leftJoystick = true;
  35354. }
  35355. else {
  35356. this._leftJoystick = false;
  35357. }
  35358. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  35359. VirtualJoystick._globalJoystickIndex++;
  35360. // By default left & right arrow keys are moving the X
  35361. // and up & down keys are moving the Y
  35362. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  35363. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  35364. this.reverseLeftRight = false;
  35365. this.reverseUpDown = false;
  35366. // collections of pointers
  35367. this._touches = new BABYLON.SmartCollection();
  35368. this.deltaPosition = BABYLON.Vector3.Zero();
  35369. this._joystickSensibility = 25;
  35370. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  35371. this._rotationSpeed = 25;
  35372. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  35373. this._rotateOnAxisRelativeToMesh = false;
  35374. this._onResize = function (evt) {
  35375. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  35376. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  35377. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  35378. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  35379. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  35380. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  35381. };
  35382. // injecting a canvas element on top of the canvas 3D game
  35383. if (!VirtualJoystick.vjCanvas) {
  35384. window.addEventListener("resize", this._onResize, false);
  35385. VirtualJoystick.vjCanvas = document.createElement("canvas");
  35386. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  35387. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  35388. VirtualJoystick.vjCanvas.width = window.innerWidth;
  35389. VirtualJoystick.vjCanvas.height = window.innerHeight;
  35390. VirtualJoystick.vjCanvas.style.width = "100%";
  35391. VirtualJoystick.vjCanvas.style.height = "100%";
  35392. VirtualJoystick.vjCanvas.style.position = "absolute";
  35393. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  35394. VirtualJoystick.vjCanvas.style.top = "0px";
  35395. VirtualJoystick.vjCanvas.style.left = "0px";
  35396. VirtualJoystick.vjCanvas.style.zIndex = "5";
  35397. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  35398. // Support for jQuery PEP polyfill
  35399. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  35400. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  35401. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  35402. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  35403. document.body.appendChild(VirtualJoystick.vjCanvas);
  35404. }
  35405. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  35406. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  35407. this.pressed = false;
  35408. // default joystick color
  35409. this._joystickColor = "cyan";
  35410. this._joystickPointerID = -1;
  35411. // current joystick position
  35412. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  35413. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  35414. // origin joystick position
  35415. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  35416. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  35417. this._onPointerDownHandlerRef = function (evt) {
  35418. _this._onPointerDown(evt);
  35419. };
  35420. this._onPointerMoveHandlerRef = function (evt) {
  35421. _this._onPointerMove(evt);
  35422. };
  35423. this._onPointerOutHandlerRef = function (evt) {
  35424. _this._onPointerUp(evt);
  35425. };
  35426. this._onPointerUpHandlerRef = function (evt) {
  35427. _this._onPointerUp(evt);
  35428. };
  35429. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  35430. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  35431. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  35432. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  35433. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  35434. evt.preventDefault(); // Disables system menu
  35435. }, false);
  35436. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  35437. }
  35438. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  35439. this._joystickSensibility = newJoystickSensibility;
  35440. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  35441. };
  35442. VirtualJoystick.prototype._onPointerDown = function (e) {
  35443. var positionOnScreenCondition;
  35444. e.preventDefault();
  35445. if (this._leftJoystick === true) {
  35446. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  35447. }
  35448. else {
  35449. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  35450. }
  35451. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  35452. // First contact will be dedicated to the virtual joystick
  35453. this._joystickPointerID = e.pointerId;
  35454. this._joystickPointerStartPos.x = e.clientX;
  35455. this._joystickPointerStartPos.y = e.clientY;
  35456. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  35457. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  35458. this._deltaJoystickVector.x = 0;
  35459. this._deltaJoystickVector.y = 0;
  35460. this.pressed = true;
  35461. this._touches.add(e.pointerId.toString(), e);
  35462. }
  35463. else {
  35464. // You can only trigger the action buttons with a joystick declared
  35465. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  35466. this._action();
  35467. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  35468. }
  35469. }
  35470. };
  35471. VirtualJoystick.prototype._onPointerMove = function (e) {
  35472. // If the current pointer is the one associated to the joystick (first touch contact)
  35473. if (this._joystickPointerID == e.pointerId) {
  35474. this._joystickPointerPos.x = e.clientX;
  35475. this._joystickPointerPos.y = e.clientY;
  35476. this._deltaJoystickVector = this._joystickPointerPos.clone();
  35477. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  35478. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  35479. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  35480. switch (this._axisTargetedByLeftAndRight) {
  35481. case JoystickAxis.X:
  35482. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  35483. break;
  35484. case JoystickAxis.Y:
  35485. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  35486. break;
  35487. case JoystickAxis.Z:
  35488. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  35489. break;
  35490. }
  35491. var directionUpDown = this.reverseUpDown ? 1 : -1;
  35492. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  35493. switch (this._axisTargetedByUpAndDown) {
  35494. case JoystickAxis.X:
  35495. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  35496. break;
  35497. case JoystickAxis.Y:
  35498. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  35499. break;
  35500. case JoystickAxis.Z:
  35501. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  35502. break;
  35503. }
  35504. }
  35505. else {
  35506. if (this._touches.item(e.pointerId.toString())) {
  35507. this._touches.item(e.pointerId.toString()).x = e.clientX;
  35508. this._touches.item(e.pointerId.toString()).y = e.clientY;
  35509. }
  35510. }
  35511. };
  35512. VirtualJoystick.prototype._onPointerUp = function (e) {
  35513. if (this._joystickPointerID == e.pointerId) {
  35514. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  35515. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  35516. this._joystickPointerID = -1;
  35517. this.pressed = false;
  35518. }
  35519. else {
  35520. var touch = this._touches.item(e.pointerId.toString());
  35521. if (touch) {
  35522. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  35523. }
  35524. }
  35525. this._deltaJoystickVector.x = 0;
  35526. this._deltaJoystickVector.y = 0;
  35527. this._touches.remove(e.pointerId.toString());
  35528. };
  35529. /**
  35530. * Change the color of the virtual joystick
  35531. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  35532. */
  35533. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  35534. this._joystickColor = newColor;
  35535. };
  35536. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  35537. this._action = action;
  35538. };
  35539. // Define which axis you'd like to control for left & right
  35540. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  35541. switch (axis) {
  35542. case JoystickAxis.X:
  35543. case JoystickAxis.Y:
  35544. case JoystickAxis.Z:
  35545. this._axisTargetedByLeftAndRight = axis;
  35546. break;
  35547. default:
  35548. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  35549. break;
  35550. }
  35551. };
  35552. // Define which axis you'd like to control for up & down
  35553. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  35554. switch (axis) {
  35555. case JoystickAxis.X:
  35556. case JoystickAxis.Y:
  35557. case JoystickAxis.Z:
  35558. this._axisTargetedByUpAndDown = axis;
  35559. break;
  35560. default:
  35561. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  35562. break;
  35563. }
  35564. };
  35565. VirtualJoystick.prototype._clearCanvas = function () {
  35566. if (this._leftJoystick) {
  35567. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  35568. }
  35569. else {
  35570. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  35571. }
  35572. };
  35573. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  35574. var _this = this;
  35575. if (this.pressed) {
  35576. this._touches.forEach(function (touch) {
  35577. if (touch.pointerId === _this._joystickPointerID) {
  35578. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  35579. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  35580. VirtualJoystick.vjCanvasContext.beginPath();
  35581. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  35582. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  35583. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  35584. VirtualJoystick.vjCanvasContext.stroke();
  35585. VirtualJoystick.vjCanvasContext.closePath();
  35586. VirtualJoystick.vjCanvasContext.beginPath();
  35587. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  35588. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  35589. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  35590. VirtualJoystick.vjCanvasContext.stroke();
  35591. VirtualJoystick.vjCanvasContext.closePath();
  35592. VirtualJoystick.vjCanvasContext.beginPath();
  35593. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  35594. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  35595. VirtualJoystick.vjCanvasContext.stroke();
  35596. VirtualJoystick.vjCanvasContext.closePath();
  35597. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  35598. }
  35599. else {
  35600. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  35601. VirtualJoystick.vjCanvasContext.beginPath();
  35602. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  35603. VirtualJoystick.vjCanvasContext.beginPath();
  35604. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  35605. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  35606. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  35607. VirtualJoystick.vjCanvasContext.stroke();
  35608. VirtualJoystick.vjCanvasContext.closePath();
  35609. touch.prevX = touch.x;
  35610. touch.prevY = touch.y;
  35611. }
  35612. ;
  35613. });
  35614. }
  35615. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  35616. };
  35617. VirtualJoystick.prototype.releaseCanvas = function () {
  35618. if (VirtualJoystick.vjCanvas) {
  35619. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  35620. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  35621. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  35622. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  35623. window.removeEventListener("resize", this._onResize);
  35624. document.body.removeChild(VirtualJoystick.vjCanvas);
  35625. VirtualJoystick.vjCanvas = null;
  35626. }
  35627. };
  35628. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  35629. VirtualJoystick._globalJoystickIndex = 0;
  35630. return VirtualJoystick;
  35631. })();
  35632. BABYLON.VirtualJoystick = VirtualJoystick;
  35633. })(BABYLON || (BABYLON = {}));
  35634. var BABYLON;
  35635. (function (BABYLON) {
  35636. // We're mainly based on the logic defined into the FreeCamera code
  35637. var VirtualJoysticksCamera = (function (_super) {
  35638. __extends(VirtualJoysticksCamera, _super);
  35639. function VirtualJoysticksCamera(name, position, scene) {
  35640. _super.call(this, name, position, scene);
  35641. this.inputs.addVirtualJoystick();
  35642. }
  35643. return VirtualJoysticksCamera;
  35644. })(BABYLON.FreeCamera);
  35645. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  35646. })(BABYLON || (BABYLON = {}));
  35647. var BABYLON;
  35648. (function (BABYLON) {
  35649. var AnaglyphPostProcess = (function (_super) {
  35650. __extends(AnaglyphPostProcess, _super);
  35651. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35652. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  35653. }
  35654. return AnaglyphPostProcess;
  35655. })(BABYLON.PostProcess);
  35656. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  35657. })(BABYLON || (BABYLON = {}));
  35658. var BABYLON;
  35659. (function (BABYLON) {
  35660. var OutlineRenderer = (function () {
  35661. function OutlineRenderer(scene) {
  35662. this._scene = scene;
  35663. }
  35664. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  35665. var _this = this;
  35666. if (useOverlay === void 0) { useOverlay = false; }
  35667. var scene = this._scene;
  35668. var engine = this._scene.getEngine();
  35669. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  35670. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  35671. return;
  35672. }
  35673. var mesh = subMesh.getRenderingMesh();
  35674. var material = subMesh.getMaterial();
  35675. engine.enableEffect(this._effect);
  35676. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  35677. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  35678. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35679. // Bones
  35680. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35681. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35682. }
  35683. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  35684. // Alpha test
  35685. if (material && material.needAlphaTesting()) {
  35686. var alphaTexture = material.getAlphaTestTexture();
  35687. this._effect.setTexture("diffuseSampler", alphaTexture);
  35688. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35689. }
  35690. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  35691. };
  35692. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  35693. var defines = [];
  35694. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  35695. var mesh = subMesh.getMesh();
  35696. var material = subMesh.getMaterial();
  35697. // Alpha test
  35698. if (material && material.needAlphaTesting()) {
  35699. defines.push("#define ALPHATEST");
  35700. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35701. attribs.push(BABYLON.VertexBuffer.UVKind);
  35702. defines.push("#define UV1");
  35703. }
  35704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35705. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35706. defines.push("#define UV2");
  35707. }
  35708. }
  35709. // Bones
  35710. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35711. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35712. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35713. if (mesh.numBoneInfluencers > 4) {
  35714. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35715. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35716. }
  35717. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35718. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35719. }
  35720. else {
  35721. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35722. }
  35723. // Instances
  35724. if (useInstances) {
  35725. defines.push("#define INSTANCES");
  35726. attribs.push("world0");
  35727. attribs.push("world1");
  35728. attribs.push("world2");
  35729. attribs.push("world3");
  35730. }
  35731. // Get correct effect
  35732. var join = defines.join("\n");
  35733. if (this._cachedDefines !== join) {
  35734. this._cachedDefines = join;
  35735. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  35736. }
  35737. return this._effect.isReady();
  35738. };
  35739. return OutlineRenderer;
  35740. })();
  35741. BABYLON.OutlineRenderer = OutlineRenderer;
  35742. })(BABYLON || (BABYLON = {}));
  35743. var BABYLON;
  35744. (function (BABYLON) {
  35745. var MeshAssetTask = (function () {
  35746. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  35747. this.name = name;
  35748. this.meshesNames = meshesNames;
  35749. this.rootUrl = rootUrl;
  35750. this.sceneFilename = sceneFilename;
  35751. this.isCompleted = false;
  35752. }
  35753. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35754. var _this = this;
  35755. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  35756. _this.loadedMeshes = meshes;
  35757. _this.loadedParticleSystems = particleSystems;
  35758. _this.loadedSkeletons = skeletons;
  35759. _this.isCompleted = true;
  35760. if (_this.onSuccess) {
  35761. _this.onSuccess(_this);
  35762. }
  35763. onSuccess();
  35764. }, null, function () {
  35765. if (_this.onError) {
  35766. _this.onError(_this);
  35767. }
  35768. onError();
  35769. });
  35770. };
  35771. return MeshAssetTask;
  35772. })();
  35773. BABYLON.MeshAssetTask = MeshAssetTask;
  35774. var TextFileAssetTask = (function () {
  35775. function TextFileAssetTask(name, url) {
  35776. this.name = name;
  35777. this.url = url;
  35778. this.isCompleted = false;
  35779. }
  35780. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35781. var _this = this;
  35782. BABYLON.Tools.LoadFile(this.url, function (data) {
  35783. _this.text = data;
  35784. _this.isCompleted = true;
  35785. if (_this.onSuccess) {
  35786. _this.onSuccess(_this);
  35787. }
  35788. onSuccess();
  35789. }, null, scene.database, false, function () {
  35790. if (_this.onError) {
  35791. _this.onError(_this);
  35792. }
  35793. onError();
  35794. });
  35795. };
  35796. return TextFileAssetTask;
  35797. })();
  35798. BABYLON.TextFileAssetTask = TextFileAssetTask;
  35799. var BinaryFileAssetTask = (function () {
  35800. function BinaryFileAssetTask(name, url) {
  35801. this.name = name;
  35802. this.url = url;
  35803. this.isCompleted = false;
  35804. }
  35805. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35806. var _this = this;
  35807. BABYLON.Tools.LoadFile(this.url, function (data) {
  35808. _this.data = data;
  35809. _this.isCompleted = true;
  35810. if (_this.onSuccess) {
  35811. _this.onSuccess(_this);
  35812. }
  35813. onSuccess();
  35814. }, null, scene.database, true, function () {
  35815. if (_this.onError) {
  35816. _this.onError(_this);
  35817. }
  35818. onError();
  35819. });
  35820. };
  35821. return BinaryFileAssetTask;
  35822. })();
  35823. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  35824. var ImageAssetTask = (function () {
  35825. function ImageAssetTask(name, url) {
  35826. this.name = name;
  35827. this.url = url;
  35828. this.isCompleted = false;
  35829. }
  35830. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35831. var _this = this;
  35832. var img = new Image();
  35833. img.onload = function () {
  35834. _this.image = img;
  35835. _this.isCompleted = true;
  35836. if (_this.onSuccess) {
  35837. _this.onSuccess(_this);
  35838. }
  35839. onSuccess();
  35840. };
  35841. img.onerror = function () {
  35842. if (_this.onError) {
  35843. _this.onError(_this);
  35844. }
  35845. onError();
  35846. };
  35847. img.src = this.url;
  35848. };
  35849. return ImageAssetTask;
  35850. })();
  35851. BABYLON.ImageAssetTask = ImageAssetTask;
  35852. var TextureAssetTask = (function () {
  35853. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  35854. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35855. this.name = name;
  35856. this.url = url;
  35857. this.noMipmap = noMipmap;
  35858. this.invertY = invertY;
  35859. this.samplingMode = samplingMode;
  35860. this.isCompleted = false;
  35861. }
  35862. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  35863. var _this = this;
  35864. var onload = function () {
  35865. _this.isCompleted = true;
  35866. if (_this.onSuccess) {
  35867. _this.onSuccess(_this);
  35868. }
  35869. onSuccess();
  35870. };
  35871. var onerror = function () {
  35872. if (_this.onError) {
  35873. _this.onError(_this);
  35874. }
  35875. onError();
  35876. };
  35877. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  35878. };
  35879. return TextureAssetTask;
  35880. })();
  35881. BABYLON.TextureAssetTask = TextureAssetTask;
  35882. var AssetsManager = (function () {
  35883. function AssetsManager(scene) {
  35884. this._tasks = new Array();
  35885. this._waitingTasksCount = 0;
  35886. this.useDefaultLoadingScreen = true;
  35887. this._scene = scene;
  35888. }
  35889. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  35890. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  35891. this._tasks.push(task);
  35892. return task;
  35893. };
  35894. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  35895. var task = new TextFileAssetTask(taskName, url);
  35896. this._tasks.push(task);
  35897. return task;
  35898. };
  35899. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  35900. var task = new BinaryFileAssetTask(taskName, url);
  35901. this._tasks.push(task);
  35902. return task;
  35903. };
  35904. AssetsManager.prototype.addImageTask = function (taskName, url) {
  35905. var task = new ImageAssetTask(taskName, url);
  35906. this._tasks.push(task);
  35907. return task;
  35908. };
  35909. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  35910. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35911. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  35912. this._tasks.push(task);
  35913. return task;
  35914. };
  35915. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  35916. this._waitingTasksCount--;
  35917. if (this._waitingTasksCount === 0) {
  35918. if (this.onFinish) {
  35919. this.onFinish(this._tasks);
  35920. }
  35921. this._scene.getEngine().hideLoadingUI();
  35922. }
  35923. };
  35924. AssetsManager.prototype._runTask = function (task) {
  35925. var _this = this;
  35926. task.run(this._scene, function () {
  35927. if (_this.onTaskSuccess) {
  35928. _this.onTaskSuccess(task);
  35929. }
  35930. _this._decreaseWaitingTasksCount();
  35931. }, function () {
  35932. if (_this.onTaskError) {
  35933. _this.onTaskError(task);
  35934. }
  35935. _this._decreaseWaitingTasksCount();
  35936. });
  35937. };
  35938. AssetsManager.prototype.reset = function () {
  35939. this._tasks = new Array();
  35940. return this;
  35941. };
  35942. AssetsManager.prototype.load = function () {
  35943. this._waitingTasksCount = this._tasks.length;
  35944. if (this._waitingTasksCount === 0) {
  35945. if (this.onFinish) {
  35946. this.onFinish(this._tasks);
  35947. }
  35948. return this;
  35949. }
  35950. if (this.useDefaultLoadingScreen) {
  35951. this._scene.getEngine().displayLoadingUI();
  35952. }
  35953. for (var index = 0; index < this._tasks.length; index++) {
  35954. var task = this._tasks[index];
  35955. this._runTask(task);
  35956. }
  35957. return this;
  35958. };
  35959. return AssetsManager;
  35960. })();
  35961. BABYLON.AssetsManager = AssetsManager;
  35962. })(BABYLON || (BABYLON = {}));
  35963. var BABYLON;
  35964. (function (BABYLON) {
  35965. var VRCameraMetrics = (function () {
  35966. function VRCameraMetrics() {
  35967. this.compensateDistortion = true;
  35968. }
  35969. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  35970. get: function () {
  35971. return this.hResolution / (2 * this.vResolution);
  35972. },
  35973. enumerable: true,
  35974. configurable: true
  35975. });
  35976. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  35977. get: function () {
  35978. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  35979. },
  35980. enumerable: true,
  35981. configurable: true
  35982. });
  35983. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  35984. get: function () {
  35985. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  35986. var h = (4 * meters) / this.hScreenSize;
  35987. return BABYLON.Matrix.Translation(h, 0, 0);
  35988. },
  35989. enumerable: true,
  35990. configurable: true
  35991. });
  35992. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  35993. get: function () {
  35994. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  35995. var h = (4 * meters) / this.hScreenSize;
  35996. return BABYLON.Matrix.Translation(-h, 0, 0);
  35997. },
  35998. enumerable: true,
  35999. configurable: true
  36000. });
  36001. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  36002. get: function () {
  36003. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  36004. },
  36005. enumerable: true,
  36006. configurable: true
  36007. });
  36008. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  36009. get: function () {
  36010. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  36011. },
  36012. enumerable: true,
  36013. configurable: true
  36014. });
  36015. VRCameraMetrics.GetDefault = function () {
  36016. var result = new VRCameraMetrics();
  36017. result.hResolution = 1280;
  36018. result.vResolution = 800;
  36019. result.hScreenSize = 0.149759993;
  36020. result.vScreenSize = 0.0935999975;
  36021. result.vScreenCenter = 0.0467999987,
  36022. result.eyeToScreenDistance = 0.0410000011;
  36023. result.lensSeparationDistance = 0.0635000020;
  36024. result.interpupillaryDistance = 0.0640000030;
  36025. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  36026. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  36027. result.postProcessScaleFactor = 1.714605507808412;
  36028. result.lensCenterOffset = 0.151976421;
  36029. return result;
  36030. };
  36031. return VRCameraMetrics;
  36032. })();
  36033. BABYLON.VRCameraMetrics = VRCameraMetrics;
  36034. })(BABYLON || (BABYLON = {}));
  36035. var BABYLON;
  36036. (function (BABYLON) {
  36037. var VRDeviceOrientationFreeCamera = (function (_super) {
  36038. __extends(VRDeviceOrientationFreeCamera, _super);
  36039. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  36040. if (compensateDistortion === void 0) { compensateDistortion = true; }
  36041. _super.call(this, name, position, scene);
  36042. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  36043. metrics.compensateDistortion = compensateDistortion;
  36044. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  36045. this.inputs.addVRDeviceOrientation();
  36046. }
  36047. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  36048. return "VRDeviceOrientationFreeCamera";
  36049. };
  36050. return VRDeviceOrientationFreeCamera;
  36051. })(BABYLON.FreeCamera);
  36052. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  36053. })(BABYLON || (BABYLON = {}));
  36054. var BABYLON;
  36055. (function (BABYLON) {
  36056. var WebVRFreeCamera = (function (_super) {
  36057. __extends(WebVRFreeCamera, _super);
  36058. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  36059. if (compensateDistortion === void 0) { compensateDistortion = true; }
  36060. _super.call(this, name, position, scene);
  36061. this._hmdDevice = null;
  36062. this._sensorDevice = null;
  36063. this._cacheState = null;
  36064. this._cacheQuaternion = new BABYLON.Quaternion();
  36065. this._cacheRotation = BABYLON.Vector3.Zero();
  36066. this._vrEnabled = false;
  36067. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  36068. metrics.compensateDistortion = compensateDistortion;
  36069. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  36070. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  36071. }
  36072. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  36073. var size = devices.length;
  36074. var i = 0;
  36075. // Reset devices.
  36076. this._sensorDevice = null;
  36077. this._hmdDevice = null;
  36078. // Search for a HmdDevice.
  36079. while (i < size && this._hmdDevice === null) {
  36080. if (devices[i] instanceof HMDVRDevice) {
  36081. this._hmdDevice = devices[i];
  36082. }
  36083. i++;
  36084. }
  36085. i = 0;
  36086. while (i < size && this._sensorDevice === null) {
  36087. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  36088. this._sensorDevice = devices[i];
  36089. }
  36090. i++;
  36091. }
  36092. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  36093. };
  36094. WebVRFreeCamera.prototype._checkInputs = function () {
  36095. if (this._vrEnabled) {
  36096. this._cacheState = this._sensorDevice.getState();
  36097. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  36098. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  36099. this.rotation.x = -this._cacheRotation.x;
  36100. this.rotation.y = -this._cacheRotation.y;
  36101. this.rotation.z = this._cacheRotation.z;
  36102. }
  36103. _super.prototype._checkInputs.call(this);
  36104. };
  36105. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  36106. _super.prototype.attachControl.call(this, element, noPreventDefault);
  36107. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  36108. if (navigator.getVRDevices) {
  36109. navigator.getVRDevices().then(this._getWebVRDevices);
  36110. }
  36111. else if (navigator.mozGetVRDevices) {
  36112. navigator.mozGetVRDevices(this._getWebVRDevices);
  36113. }
  36114. };
  36115. WebVRFreeCamera.prototype.detachControl = function (element) {
  36116. _super.prototype.detachControl.call(this, element);
  36117. this._vrEnabled = false;
  36118. };
  36119. WebVRFreeCamera.prototype.getTypeName = function () {
  36120. return "WebVRFreeCamera";
  36121. };
  36122. return WebVRFreeCamera;
  36123. })(BABYLON.FreeCamera);
  36124. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  36125. })(BABYLON || (BABYLON = {}));
  36126. var BABYLON;
  36127. (function (BABYLON) {
  36128. // Standard optimizations
  36129. var SceneOptimization = (function () {
  36130. function SceneOptimization(priority) {
  36131. if (priority === void 0) { priority = 0; }
  36132. this.priority = priority;
  36133. this.apply = function (scene) {
  36134. return true; // Return true if everything that can be done was applied
  36135. };
  36136. }
  36137. return SceneOptimization;
  36138. })();
  36139. BABYLON.SceneOptimization = SceneOptimization;
  36140. var TextureOptimization = (function (_super) {
  36141. __extends(TextureOptimization, _super);
  36142. function TextureOptimization(priority, maximumSize) {
  36143. var _this = this;
  36144. if (priority === void 0) { priority = 0; }
  36145. if (maximumSize === void 0) { maximumSize = 1024; }
  36146. _super.call(this, priority);
  36147. this.priority = priority;
  36148. this.maximumSize = maximumSize;
  36149. this.apply = function (scene) {
  36150. var allDone = true;
  36151. for (var index = 0; index < scene.textures.length; index++) {
  36152. var texture = scene.textures[index];
  36153. if (!texture.canRescale) {
  36154. continue;
  36155. }
  36156. var currentSize = texture.getSize();
  36157. var maxDimension = Math.max(currentSize.width, currentSize.height);
  36158. if (maxDimension > _this.maximumSize) {
  36159. texture.scale(0.5);
  36160. allDone = false;
  36161. }
  36162. }
  36163. return allDone;
  36164. };
  36165. }
  36166. return TextureOptimization;
  36167. })(SceneOptimization);
  36168. BABYLON.TextureOptimization = TextureOptimization;
  36169. var HardwareScalingOptimization = (function (_super) {
  36170. __extends(HardwareScalingOptimization, _super);
  36171. function HardwareScalingOptimization(priority, maximumScale) {
  36172. var _this = this;
  36173. if (priority === void 0) { priority = 0; }
  36174. if (maximumScale === void 0) { maximumScale = 2; }
  36175. _super.call(this, priority);
  36176. this.priority = priority;
  36177. this.maximumScale = maximumScale;
  36178. this._currentScale = 1;
  36179. this.apply = function (scene) {
  36180. _this._currentScale++;
  36181. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  36182. return _this._currentScale >= _this.maximumScale;
  36183. };
  36184. }
  36185. return HardwareScalingOptimization;
  36186. })(SceneOptimization);
  36187. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  36188. var ShadowsOptimization = (function (_super) {
  36189. __extends(ShadowsOptimization, _super);
  36190. function ShadowsOptimization() {
  36191. _super.apply(this, arguments);
  36192. this.apply = function (scene) {
  36193. scene.shadowsEnabled = false;
  36194. return true;
  36195. };
  36196. }
  36197. return ShadowsOptimization;
  36198. })(SceneOptimization);
  36199. BABYLON.ShadowsOptimization = ShadowsOptimization;
  36200. var PostProcessesOptimization = (function (_super) {
  36201. __extends(PostProcessesOptimization, _super);
  36202. function PostProcessesOptimization() {
  36203. _super.apply(this, arguments);
  36204. this.apply = function (scene) {
  36205. scene.postProcessesEnabled = false;
  36206. return true;
  36207. };
  36208. }
  36209. return PostProcessesOptimization;
  36210. })(SceneOptimization);
  36211. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  36212. var LensFlaresOptimization = (function (_super) {
  36213. __extends(LensFlaresOptimization, _super);
  36214. function LensFlaresOptimization() {
  36215. _super.apply(this, arguments);
  36216. this.apply = function (scene) {
  36217. scene.lensFlaresEnabled = false;
  36218. return true;
  36219. };
  36220. }
  36221. return LensFlaresOptimization;
  36222. })(SceneOptimization);
  36223. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  36224. var ParticlesOptimization = (function (_super) {
  36225. __extends(ParticlesOptimization, _super);
  36226. function ParticlesOptimization() {
  36227. _super.apply(this, arguments);
  36228. this.apply = function (scene) {
  36229. scene.particlesEnabled = false;
  36230. return true;
  36231. };
  36232. }
  36233. return ParticlesOptimization;
  36234. })(SceneOptimization);
  36235. BABYLON.ParticlesOptimization = ParticlesOptimization;
  36236. var RenderTargetsOptimization = (function (_super) {
  36237. __extends(RenderTargetsOptimization, _super);
  36238. function RenderTargetsOptimization() {
  36239. _super.apply(this, arguments);
  36240. this.apply = function (scene) {
  36241. scene.renderTargetsEnabled = false;
  36242. return true;
  36243. };
  36244. }
  36245. return RenderTargetsOptimization;
  36246. })(SceneOptimization);
  36247. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  36248. var MergeMeshesOptimization = (function (_super) {
  36249. __extends(MergeMeshesOptimization, _super);
  36250. function MergeMeshesOptimization() {
  36251. var _this = this;
  36252. _super.apply(this, arguments);
  36253. this._canBeMerged = function (abstractMesh) {
  36254. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  36255. return false;
  36256. }
  36257. var mesh = abstractMesh;
  36258. if (!mesh.isVisible || !mesh.isEnabled()) {
  36259. return false;
  36260. }
  36261. if (mesh.instances.length > 0) {
  36262. return false;
  36263. }
  36264. if (mesh.skeleton || mesh.hasLODLevels) {
  36265. return false;
  36266. }
  36267. if (mesh.parent) {
  36268. return false;
  36269. }
  36270. return true;
  36271. };
  36272. this.apply = function (scene, updateSelectionTree) {
  36273. var globalPool = scene.meshes.slice(0);
  36274. var globalLength = globalPool.length;
  36275. for (var index = 0; index < globalLength; index++) {
  36276. var currentPool = new Array();
  36277. var current = globalPool[index];
  36278. // Checks
  36279. if (!_this._canBeMerged(current)) {
  36280. continue;
  36281. }
  36282. currentPool.push(current);
  36283. // Find compatible meshes
  36284. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  36285. var otherMesh = globalPool[subIndex];
  36286. if (!_this._canBeMerged(otherMesh)) {
  36287. continue;
  36288. }
  36289. if (otherMesh.material !== current.material) {
  36290. continue;
  36291. }
  36292. if (otherMesh.checkCollisions !== current.checkCollisions) {
  36293. continue;
  36294. }
  36295. currentPool.push(otherMesh);
  36296. globalLength--;
  36297. globalPool.splice(subIndex, 1);
  36298. subIndex--;
  36299. }
  36300. if (currentPool.length < 2) {
  36301. continue;
  36302. }
  36303. // Merge meshes
  36304. BABYLON.Mesh.MergeMeshes(currentPool);
  36305. }
  36306. if (updateSelectionTree != undefined) {
  36307. if (updateSelectionTree) {
  36308. scene.createOrUpdateSelectionOctree();
  36309. }
  36310. }
  36311. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  36312. scene.createOrUpdateSelectionOctree();
  36313. }
  36314. return true;
  36315. };
  36316. }
  36317. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  36318. get: function () {
  36319. return MergeMeshesOptimization._UpdateSelectionTree;
  36320. },
  36321. set: function (value) {
  36322. MergeMeshesOptimization._UpdateSelectionTree = value;
  36323. },
  36324. enumerable: true,
  36325. configurable: true
  36326. });
  36327. MergeMeshesOptimization._UpdateSelectionTree = false;
  36328. return MergeMeshesOptimization;
  36329. })(SceneOptimization);
  36330. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  36331. // Options
  36332. var SceneOptimizerOptions = (function () {
  36333. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  36334. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  36335. if (trackerDuration === void 0) { trackerDuration = 2000; }
  36336. this.targetFrameRate = targetFrameRate;
  36337. this.trackerDuration = trackerDuration;
  36338. this.optimizations = new Array();
  36339. }
  36340. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  36341. var result = new SceneOptimizerOptions(targetFrameRate);
  36342. var priority = 0;
  36343. result.optimizations.push(new MergeMeshesOptimization(priority));
  36344. result.optimizations.push(new ShadowsOptimization(priority));
  36345. result.optimizations.push(new LensFlaresOptimization(priority));
  36346. // Next priority
  36347. priority++;
  36348. result.optimizations.push(new PostProcessesOptimization(priority));
  36349. result.optimizations.push(new ParticlesOptimization(priority));
  36350. // Next priority
  36351. priority++;
  36352. result.optimizations.push(new TextureOptimization(priority, 1024));
  36353. return result;
  36354. };
  36355. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  36356. var result = new SceneOptimizerOptions(targetFrameRate);
  36357. var priority = 0;
  36358. result.optimizations.push(new MergeMeshesOptimization(priority));
  36359. result.optimizations.push(new ShadowsOptimization(priority));
  36360. result.optimizations.push(new LensFlaresOptimization(priority));
  36361. // Next priority
  36362. priority++;
  36363. result.optimizations.push(new PostProcessesOptimization(priority));
  36364. result.optimizations.push(new ParticlesOptimization(priority));
  36365. // Next priority
  36366. priority++;
  36367. result.optimizations.push(new TextureOptimization(priority, 512));
  36368. // Next priority
  36369. priority++;
  36370. result.optimizations.push(new RenderTargetsOptimization(priority));
  36371. // Next priority
  36372. priority++;
  36373. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  36374. return result;
  36375. };
  36376. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  36377. var result = new SceneOptimizerOptions(targetFrameRate);
  36378. var priority = 0;
  36379. result.optimizations.push(new MergeMeshesOptimization(priority));
  36380. result.optimizations.push(new ShadowsOptimization(priority));
  36381. result.optimizations.push(new LensFlaresOptimization(priority));
  36382. // Next priority
  36383. priority++;
  36384. result.optimizations.push(new PostProcessesOptimization(priority));
  36385. result.optimizations.push(new ParticlesOptimization(priority));
  36386. // Next priority
  36387. priority++;
  36388. result.optimizations.push(new TextureOptimization(priority, 256));
  36389. // Next priority
  36390. priority++;
  36391. result.optimizations.push(new RenderTargetsOptimization(priority));
  36392. // Next priority
  36393. priority++;
  36394. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  36395. return result;
  36396. };
  36397. return SceneOptimizerOptions;
  36398. })();
  36399. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  36400. // Scene optimizer tool
  36401. var SceneOptimizer = (function () {
  36402. function SceneOptimizer() {
  36403. }
  36404. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  36405. // TODO: add an epsilon
  36406. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  36407. if (onSuccess) {
  36408. onSuccess();
  36409. }
  36410. return;
  36411. }
  36412. // Apply current level of optimizations
  36413. var allDone = true;
  36414. var noOptimizationApplied = true;
  36415. for (var index = 0; index < options.optimizations.length; index++) {
  36416. var optimization = options.optimizations[index];
  36417. if (optimization.priority === currentPriorityLevel) {
  36418. noOptimizationApplied = false;
  36419. allDone = allDone && optimization.apply(scene);
  36420. }
  36421. }
  36422. // If no optimization was applied, this is a failure :(
  36423. if (noOptimizationApplied) {
  36424. if (onFailure) {
  36425. onFailure();
  36426. }
  36427. return;
  36428. }
  36429. // If all optimizations were done, move to next level
  36430. if (allDone) {
  36431. currentPriorityLevel++;
  36432. }
  36433. // Let's the system running for a specific amount of time before checking FPS
  36434. scene.executeWhenReady(function () {
  36435. setTimeout(function () {
  36436. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  36437. }, options.trackerDuration);
  36438. });
  36439. };
  36440. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  36441. if (!options) {
  36442. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  36443. }
  36444. // Let's the system running for a specific amount of time before checking FPS
  36445. scene.executeWhenReady(function () {
  36446. setTimeout(function () {
  36447. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  36448. }, options.trackerDuration);
  36449. });
  36450. };
  36451. return SceneOptimizer;
  36452. })();
  36453. BABYLON.SceneOptimizer = SceneOptimizer;
  36454. })(BABYLON || (BABYLON = {}));
  36455. var BABYLON;
  36456. (function (BABYLON) {
  36457. var Internals;
  36458. (function (Internals) {
  36459. var MeshLODLevel = (function () {
  36460. function MeshLODLevel(distance, mesh) {
  36461. this.distance = distance;
  36462. this.mesh = mesh;
  36463. }
  36464. return MeshLODLevel;
  36465. })();
  36466. Internals.MeshLODLevel = MeshLODLevel;
  36467. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36468. })(BABYLON || (BABYLON = {}));
  36469. var BABYLON;
  36470. (function (BABYLON) {
  36471. var RawTexture = (function (_super) {
  36472. __extends(RawTexture, _super);
  36473. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  36474. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36475. if (invertY === void 0) { invertY = false; }
  36476. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36477. _super.call(this, null, scene, !generateMipMaps, invertY);
  36478. this.format = format;
  36479. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  36480. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36481. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36482. }
  36483. RawTexture.prototype.update = function (data) {
  36484. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  36485. };
  36486. // Statics
  36487. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36488. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36489. if (invertY === void 0) { invertY = false; }
  36490. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36491. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  36492. };
  36493. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36494. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36495. if (invertY === void 0) { invertY = false; }
  36496. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36497. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  36498. };
  36499. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36500. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36501. if (invertY === void 0) { invertY = false; }
  36502. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36503. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  36504. };
  36505. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36506. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36507. if (invertY === void 0) { invertY = false; }
  36508. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36509. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  36510. };
  36511. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  36512. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36513. if (invertY === void 0) { invertY = false; }
  36514. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36515. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  36516. };
  36517. return RawTexture;
  36518. })(BABYLON.Texture);
  36519. BABYLON.RawTexture = RawTexture;
  36520. })(BABYLON || (BABYLON = {}));
  36521. var BABYLON;
  36522. (function (BABYLON) {
  36523. var IndexedVector2 = (function (_super) {
  36524. __extends(IndexedVector2, _super);
  36525. function IndexedVector2(original, index) {
  36526. _super.call(this, original.x, original.y);
  36527. this.index = index;
  36528. }
  36529. return IndexedVector2;
  36530. })(BABYLON.Vector2);
  36531. var PolygonPoints = (function () {
  36532. function PolygonPoints() {
  36533. this.elements = new Array();
  36534. }
  36535. PolygonPoints.prototype.add = function (originalPoints) {
  36536. var _this = this;
  36537. var result = new Array();
  36538. originalPoints.forEach(function (point) {
  36539. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  36540. var newPoint = new IndexedVector2(point, _this.elements.length);
  36541. result.push(newPoint);
  36542. _this.elements.push(newPoint);
  36543. }
  36544. });
  36545. return result;
  36546. };
  36547. PolygonPoints.prototype.computeBounds = function () {
  36548. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  36549. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  36550. this.elements.forEach(function (point) {
  36551. // x
  36552. if (point.x < lmin.x) {
  36553. lmin.x = point.x;
  36554. }
  36555. else if (point.x > lmax.x) {
  36556. lmax.x = point.x;
  36557. }
  36558. // y
  36559. if (point.y < lmin.y) {
  36560. lmin.y = point.y;
  36561. }
  36562. else if (point.y > lmax.y) {
  36563. lmax.y = point.y;
  36564. }
  36565. });
  36566. return {
  36567. min: lmin,
  36568. max: lmax,
  36569. width: lmax.x - lmin.x,
  36570. height: lmax.y - lmin.y
  36571. };
  36572. };
  36573. return PolygonPoints;
  36574. })();
  36575. var Polygon = (function () {
  36576. function Polygon() {
  36577. }
  36578. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  36579. return [
  36580. new BABYLON.Vector2(xmin, ymin),
  36581. new BABYLON.Vector2(xmax, ymin),
  36582. new BABYLON.Vector2(xmax, ymax),
  36583. new BABYLON.Vector2(xmin, ymax)
  36584. ];
  36585. };
  36586. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  36587. if (cx === void 0) { cx = 0; }
  36588. if (cy === void 0) { cy = 0; }
  36589. if (numberOfSides === void 0) { numberOfSides = 32; }
  36590. var result = new Array();
  36591. var angle = 0;
  36592. var increment = (Math.PI * 2) / numberOfSides;
  36593. for (var i = 0; i < numberOfSides; i++) {
  36594. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  36595. angle -= increment;
  36596. }
  36597. return result;
  36598. };
  36599. Polygon.Parse = function (input) {
  36600. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  36601. var i, result = [];
  36602. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  36603. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  36604. }
  36605. return result;
  36606. };
  36607. Polygon.StartingAt = function (x, y) {
  36608. return BABYLON.Path2.StartingAt(x, y);
  36609. };
  36610. return Polygon;
  36611. })();
  36612. BABYLON.Polygon = Polygon;
  36613. var PolygonMeshBuilder = (function () {
  36614. function PolygonMeshBuilder(name, contours, scene) {
  36615. this._points = new PolygonPoints();
  36616. this._outlinepoints = new PolygonPoints();
  36617. this._holes = [];
  36618. if (!("poly2tri" in window)) {
  36619. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  36620. }
  36621. this._name = name;
  36622. this._scene = scene;
  36623. var points;
  36624. if (contours instanceof BABYLON.Path2) {
  36625. points = contours.getPoints();
  36626. }
  36627. else {
  36628. points = contours;
  36629. }
  36630. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  36631. this._outlinepoints.add(points);
  36632. }
  36633. PolygonMeshBuilder.prototype.addHole = function (hole) {
  36634. this._swctx.addHole(this._points.add(hole));
  36635. var holepoints = new PolygonPoints();
  36636. holepoints.add(hole);
  36637. this._holes.push(holepoints);
  36638. return this;
  36639. };
  36640. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  36641. var _this = this;
  36642. if (updatable === void 0) { updatable = false; }
  36643. var result = new BABYLON.Mesh(this._name, this._scene);
  36644. var normals = [];
  36645. var positions = [];
  36646. var uvs = [];
  36647. var bounds = this._points.computeBounds();
  36648. this._points.elements.forEach(function (p) {
  36649. normals.push(0, 1.0, 0);
  36650. positions.push(p.x, 0, p.y);
  36651. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  36652. });
  36653. var indices = [];
  36654. this._swctx.triangulate();
  36655. this._swctx.getTriangles().forEach(function (triangle) {
  36656. triangle.getPoints().forEach(function (point) {
  36657. indices.push(point.index);
  36658. });
  36659. });
  36660. if (depth > 0) {
  36661. var positionscount = (positions.length / 3); //get the current pointcount
  36662. this._points.elements.forEach(function (p) {
  36663. normals.push(0, -1.0, 0);
  36664. positions.push(p.x, -depth, p.y);
  36665. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  36666. });
  36667. var p1; //we need to change order of point so the triangles are made in the rigth way.
  36668. var p2;
  36669. var poscounter = 0;
  36670. this._swctx.getTriangles().forEach(function (triangle) {
  36671. triangle.getPoints().forEach(function (point) {
  36672. switch (poscounter) {
  36673. case 0:
  36674. p1 = point;
  36675. break;
  36676. case 1:
  36677. p2 = point;
  36678. break;
  36679. case 2:
  36680. indices.push(point.index + positionscount);
  36681. indices.push(p2.index + positionscount);
  36682. indices.push(p1.index + positionscount);
  36683. poscounter = -1;
  36684. break;
  36685. }
  36686. poscounter++;
  36687. //indices.push((<IndexedVector2>point).index + positionscount);
  36688. });
  36689. });
  36690. //Add the sides
  36691. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  36692. this._holes.forEach(function (hole) {
  36693. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  36694. });
  36695. }
  36696. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  36697. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  36698. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  36699. result.setIndices(indices);
  36700. return result;
  36701. };
  36702. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  36703. var StartIndex = positions.length / 3;
  36704. var ulength = 0;
  36705. for (var i = 0; i < points.elements.length; i++) {
  36706. var p = points.elements[i];
  36707. var p1;
  36708. if ((i + 1) > points.elements.length - 1) {
  36709. p1 = points.elements[0];
  36710. }
  36711. else {
  36712. p1 = points.elements[i + 1];
  36713. }
  36714. positions.push(p.x, 0, p.y);
  36715. positions.push(p.x, -depth, p.y);
  36716. positions.push(p1.x, 0, p1.y);
  36717. positions.push(p1.x, -depth, p1.y);
  36718. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  36719. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  36720. var v3 = v2.subtract(v1);
  36721. var v4 = new BABYLON.Vector3(0, 1, 0);
  36722. var vn = BABYLON.Vector3.Cross(v3, v4);
  36723. vn = vn.normalize();
  36724. uvs.push(ulength / bounds.width, 0);
  36725. uvs.push(ulength / bounds.width, 1);
  36726. ulength += v3.length();
  36727. uvs.push((ulength / bounds.width), 0);
  36728. uvs.push((ulength / bounds.width), 1);
  36729. if (!flip) {
  36730. normals.push(-vn.x, -vn.y, -vn.z);
  36731. normals.push(-vn.x, -vn.y, -vn.z);
  36732. normals.push(-vn.x, -vn.y, -vn.z);
  36733. normals.push(-vn.x, -vn.y, -vn.z);
  36734. indices.push(StartIndex);
  36735. indices.push(StartIndex + 1);
  36736. indices.push(StartIndex + 2);
  36737. indices.push(StartIndex + 1);
  36738. indices.push(StartIndex + 3);
  36739. indices.push(StartIndex + 2);
  36740. }
  36741. else {
  36742. normals.push(vn.x, vn.y, vn.z);
  36743. normals.push(vn.x, vn.y, vn.z);
  36744. normals.push(vn.x, vn.y, vn.z);
  36745. normals.push(vn.x, vn.y, vn.z);
  36746. indices.push(StartIndex);
  36747. indices.push(StartIndex + 2);
  36748. indices.push(StartIndex + 1);
  36749. indices.push(StartIndex + 1);
  36750. indices.push(StartIndex + 2);
  36751. indices.push(StartIndex + 3);
  36752. }
  36753. StartIndex += 4;
  36754. }
  36755. ;
  36756. };
  36757. return PolygonMeshBuilder;
  36758. })();
  36759. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  36760. })(BABYLON || (BABYLON = {}));
  36761. var BABYLON;
  36762. (function (BABYLON) {
  36763. var Octree = (function () {
  36764. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  36765. if (maxDepth === void 0) { maxDepth = 2; }
  36766. this.maxDepth = maxDepth;
  36767. this.dynamicContent = new Array();
  36768. this._maxBlockCapacity = maxBlockCapacity || 64;
  36769. this._selectionContent = new BABYLON.SmartArray(1024);
  36770. this._creationFunc = creationFunc;
  36771. }
  36772. // Methods
  36773. Octree.prototype.update = function (worldMin, worldMax, entries) {
  36774. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  36775. };
  36776. Octree.prototype.addMesh = function (entry) {
  36777. for (var index = 0; index < this.blocks.length; index++) {
  36778. var block = this.blocks[index];
  36779. block.addEntry(entry);
  36780. }
  36781. };
  36782. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  36783. this._selectionContent.reset();
  36784. for (var index = 0; index < this.blocks.length; index++) {
  36785. var block = this.blocks[index];
  36786. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  36787. }
  36788. if (allowDuplicate) {
  36789. this._selectionContent.concat(this.dynamicContent);
  36790. }
  36791. else {
  36792. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  36793. }
  36794. return this._selectionContent;
  36795. };
  36796. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  36797. this._selectionContent.reset();
  36798. for (var index = 0; index < this.blocks.length; index++) {
  36799. var block = this.blocks[index];
  36800. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  36801. }
  36802. if (allowDuplicate) {
  36803. this._selectionContent.concat(this.dynamicContent);
  36804. }
  36805. else {
  36806. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  36807. }
  36808. return this._selectionContent;
  36809. };
  36810. Octree.prototype.intersectsRay = function (ray) {
  36811. this._selectionContent.reset();
  36812. for (var index = 0; index < this.blocks.length; index++) {
  36813. var block = this.blocks[index];
  36814. block.intersectsRay(ray, this._selectionContent);
  36815. }
  36816. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  36817. return this._selectionContent;
  36818. };
  36819. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  36820. target.blocks = new Array();
  36821. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  36822. // Segmenting space
  36823. for (var x = 0; x < 2; x++) {
  36824. for (var y = 0; y < 2; y++) {
  36825. for (var z = 0; z < 2; z++) {
  36826. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  36827. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  36828. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  36829. block.addEntries(entries);
  36830. target.blocks.push(block);
  36831. }
  36832. }
  36833. }
  36834. };
  36835. Octree.CreationFuncForMeshes = function (entry, block) {
  36836. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  36837. block.entries.push(entry);
  36838. }
  36839. };
  36840. Octree.CreationFuncForSubMeshes = function (entry, block) {
  36841. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  36842. block.entries.push(entry);
  36843. }
  36844. };
  36845. return Octree;
  36846. })();
  36847. BABYLON.Octree = Octree;
  36848. })(BABYLON || (BABYLON = {}));
  36849. var BABYLON;
  36850. (function (BABYLON) {
  36851. var OctreeBlock = (function () {
  36852. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  36853. this.entries = new Array();
  36854. this._boundingVectors = new Array();
  36855. this._capacity = capacity;
  36856. this._depth = depth;
  36857. this._maxDepth = maxDepth;
  36858. this._creationFunc = creationFunc;
  36859. this._minPoint = minPoint;
  36860. this._maxPoint = maxPoint;
  36861. this._boundingVectors.push(minPoint.clone());
  36862. this._boundingVectors.push(maxPoint.clone());
  36863. this._boundingVectors.push(minPoint.clone());
  36864. this._boundingVectors[2].x = maxPoint.x;
  36865. this._boundingVectors.push(minPoint.clone());
  36866. this._boundingVectors[3].y = maxPoint.y;
  36867. this._boundingVectors.push(minPoint.clone());
  36868. this._boundingVectors[4].z = maxPoint.z;
  36869. this._boundingVectors.push(maxPoint.clone());
  36870. this._boundingVectors[5].z = minPoint.z;
  36871. this._boundingVectors.push(maxPoint.clone());
  36872. this._boundingVectors[6].x = minPoint.x;
  36873. this._boundingVectors.push(maxPoint.clone());
  36874. this._boundingVectors[7].y = minPoint.y;
  36875. }
  36876. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  36877. // Property
  36878. get: function () {
  36879. return this._capacity;
  36880. },
  36881. enumerable: true,
  36882. configurable: true
  36883. });
  36884. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  36885. get: function () {
  36886. return this._minPoint;
  36887. },
  36888. enumerable: true,
  36889. configurable: true
  36890. });
  36891. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  36892. get: function () {
  36893. return this._maxPoint;
  36894. },
  36895. enumerable: true,
  36896. configurable: true
  36897. });
  36898. // Methods
  36899. OctreeBlock.prototype.addEntry = function (entry) {
  36900. if (this.blocks) {
  36901. for (var index = 0; index < this.blocks.length; index++) {
  36902. var block = this.blocks[index];
  36903. block.addEntry(entry);
  36904. }
  36905. return;
  36906. }
  36907. this._creationFunc(entry, this);
  36908. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  36909. this.createInnerBlocks();
  36910. }
  36911. };
  36912. OctreeBlock.prototype.addEntries = function (entries) {
  36913. for (var index = 0; index < entries.length; index++) {
  36914. var mesh = entries[index];
  36915. this.addEntry(mesh);
  36916. }
  36917. };
  36918. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  36919. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  36920. if (this.blocks) {
  36921. for (var index = 0; index < this.blocks.length; index++) {
  36922. var block = this.blocks[index];
  36923. block.select(frustumPlanes, selection, allowDuplicate);
  36924. }
  36925. return;
  36926. }
  36927. if (allowDuplicate) {
  36928. selection.concat(this.entries);
  36929. }
  36930. else {
  36931. selection.concatWithNoDuplicate(this.entries);
  36932. }
  36933. }
  36934. };
  36935. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  36936. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  36937. if (this.blocks) {
  36938. for (var index = 0; index < this.blocks.length; index++) {
  36939. var block = this.blocks[index];
  36940. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  36941. }
  36942. return;
  36943. }
  36944. if (allowDuplicate) {
  36945. selection.concat(this.entries);
  36946. }
  36947. else {
  36948. selection.concatWithNoDuplicate(this.entries);
  36949. }
  36950. }
  36951. };
  36952. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  36953. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  36954. if (this.blocks) {
  36955. for (var index = 0; index < this.blocks.length; index++) {
  36956. var block = this.blocks[index];
  36957. block.intersectsRay(ray, selection);
  36958. }
  36959. return;
  36960. }
  36961. selection.concatWithNoDuplicate(this.entries);
  36962. }
  36963. };
  36964. OctreeBlock.prototype.createInnerBlocks = function () {
  36965. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  36966. };
  36967. return OctreeBlock;
  36968. })();
  36969. BABYLON.OctreeBlock = OctreeBlock;
  36970. })(BABYLON || (BABYLON = {}));
  36971. var BABYLON;
  36972. (function (BABYLON) {
  36973. var BlurPostProcess = (function (_super) {
  36974. __extends(BlurPostProcess, _super);
  36975. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  36976. var _this = this;
  36977. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36978. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  36979. this.direction = direction;
  36980. this.blurWidth = blurWidth;
  36981. this.onApply = function (effect) {
  36982. effect.setFloat2("screenSize", _this.width, _this.height);
  36983. effect.setVector2("direction", _this.direction);
  36984. effect.setFloat("blurWidth", _this.blurWidth);
  36985. };
  36986. }
  36987. return BlurPostProcess;
  36988. })(BABYLON.PostProcess);
  36989. BABYLON.BlurPostProcess = BlurPostProcess;
  36990. })(BABYLON || (BABYLON = {}));
  36991. var BABYLON;
  36992. (function (BABYLON) {
  36993. var RefractionPostProcess = (function (_super) {
  36994. __extends(RefractionPostProcess, _super);
  36995. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  36996. var _this = this;
  36997. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  36998. this.color = color;
  36999. this.depth = depth;
  37000. this.colorLevel = colorLevel;
  37001. this.onActivate = function (cam) {
  37002. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  37003. };
  37004. this.onApply = function (effect) {
  37005. effect.setColor3("baseColor", _this.color);
  37006. effect.setFloat("depth", _this.depth);
  37007. effect.setFloat("colorLevel", _this.colorLevel);
  37008. effect.setTexture("refractionSampler", _this._refRexture);
  37009. };
  37010. }
  37011. // Methods
  37012. RefractionPostProcess.prototype.dispose = function (camera) {
  37013. if (this._refRexture) {
  37014. this._refRexture.dispose();
  37015. }
  37016. _super.prototype.dispose.call(this, camera);
  37017. };
  37018. return RefractionPostProcess;
  37019. })(BABYLON.PostProcess);
  37020. BABYLON.RefractionPostProcess = RefractionPostProcess;
  37021. })(BABYLON || (BABYLON = {}));
  37022. var BABYLON;
  37023. (function (BABYLON) {
  37024. var BlackAndWhitePostProcess = (function (_super) {
  37025. __extends(BlackAndWhitePostProcess, _super);
  37026. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37027. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  37028. }
  37029. return BlackAndWhitePostProcess;
  37030. })(BABYLON.PostProcess);
  37031. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  37032. })(BABYLON || (BABYLON = {}));
  37033. var BABYLON;
  37034. (function (BABYLON) {
  37035. var ConvolutionPostProcess = (function (_super) {
  37036. __extends(ConvolutionPostProcess, _super);
  37037. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  37038. var _this = this;
  37039. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  37040. this.kernel = kernel;
  37041. this.onApply = function (effect) {
  37042. effect.setFloat2("screenSize", _this.width, _this.height);
  37043. effect.setArray("kernel", _this.kernel);
  37044. };
  37045. }
  37046. // Statics
  37047. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  37048. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  37049. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  37050. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  37051. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  37052. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  37053. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  37054. return ConvolutionPostProcess;
  37055. })(BABYLON.PostProcess);
  37056. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  37057. })(BABYLON || (BABYLON = {}));
  37058. var BABYLON;
  37059. (function (BABYLON) {
  37060. var FilterPostProcess = (function (_super) {
  37061. __extends(FilterPostProcess, _super);
  37062. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  37063. var _this = this;
  37064. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  37065. this.kernelMatrix = kernelMatrix;
  37066. this.onApply = function (effect) {
  37067. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  37068. };
  37069. }
  37070. return FilterPostProcess;
  37071. })(BABYLON.PostProcess);
  37072. BABYLON.FilterPostProcess = FilterPostProcess;
  37073. })(BABYLON || (BABYLON = {}));
  37074. var BABYLON;
  37075. (function (BABYLON) {
  37076. var FxaaPostProcess = (function (_super) {
  37077. __extends(FxaaPostProcess, _super);
  37078. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37079. var _this = this;
  37080. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  37081. this.onSizeChanged = function () {
  37082. _this.texelWidth = 1.0 / _this.width;
  37083. _this.texelHeight = 1.0 / _this.height;
  37084. };
  37085. this.onApply = function (effect) {
  37086. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  37087. };
  37088. }
  37089. return FxaaPostProcess;
  37090. })(BABYLON.PostProcess);
  37091. BABYLON.FxaaPostProcess = FxaaPostProcess;
  37092. })(BABYLON || (BABYLON = {}));
  37093. var BABYLON;
  37094. (function (BABYLON) {
  37095. var StereoscopicInterlacePostProcess = (function (_super) {
  37096. __extends(StereoscopicInterlacePostProcess, _super);
  37097. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  37098. var _this = this;
  37099. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  37100. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  37101. this.onSizeChanged = function () {
  37102. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  37103. };
  37104. this.onApply = function (effect) {
  37105. effect.setTextureFromPostProcess("camASampler", postProcessA);
  37106. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  37107. };
  37108. }
  37109. return StereoscopicInterlacePostProcess;
  37110. })(BABYLON.PostProcess);
  37111. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  37112. })(BABYLON || (BABYLON = {}));
  37113. var BABYLON;
  37114. (function (BABYLON) {
  37115. var LensFlare = (function () {
  37116. function LensFlare(size, position, color, imgUrl, system) {
  37117. this.size = size;
  37118. this.position = position;
  37119. this.dispose = function () {
  37120. if (this.texture) {
  37121. this.texture.dispose();
  37122. }
  37123. // Remove from scene
  37124. var index = this._system.lensFlares.indexOf(this);
  37125. this._system.lensFlares.splice(index, 1);
  37126. };
  37127. this.color = color || new BABYLON.Color3(1, 1, 1);
  37128. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  37129. this._system = system;
  37130. system.lensFlares.push(this);
  37131. }
  37132. return LensFlare;
  37133. })();
  37134. BABYLON.LensFlare = LensFlare;
  37135. })(BABYLON || (BABYLON = {}));
  37136. var BABYLON;
  37137. (function (BABYLON) {
  37138. var LensFlareSystem = (function () {
  37139. function LensFlareSystem(name, emitter, scene) {
  37140. this.name = name;
  37141. this.lensFlares = new Array();
  37142. this.borderLimit = 300;
  37143. this.layerMask = 0x0FFFFFFF;
  37144. this._vertexDeclaration = [2];
  37145. this._vertexStrideSize = 2 * 4;
  37146. this._isEnabled = true;
  37147. this._scene = scene;
  37148. this._emitter = emitter;
  37149. scene.lensFlareSystems.push(this);
  37150. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  37151. // VBO
  37152. var vertices = [];
  37153. vertices.push(1, 1);
  37154. vertices.push(-1, 1);
  37155. vertices.push(-1, -1);
  37156. vertices.push(1, -1);
  37157. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  37158. // Indices
  37159. var indices = [];
  37160. indices.push(0);
  37161. indices.push(1);
  37162. indices.push(2);
  37163. indices.push(0);
  37164. indices.push(2);
  37165. indices.push(3);
  37166. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  37167. // Effects
  37168. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  37169. }
  37170. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  37171. get: function () {
  37172. return this._isEnabled;
  37173. },
  37174. set: function (value) {
  37175. this._isEnabled = value;
  37176. },
  37177. enumerable: true,
  37178. configurable: true
  37179. });
  37180. LensFlareSystem.prototype.getScene = function () {
  37181. return this._scene;
  37182. };
  37183. LensFlareSystem.prototype.getEmitter = function () {
  37184. return this._emitter;
  37185. };
  37186. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  37187. this._emitter = newEmitter;
  37188. };
  37189. LensFlareSystem.prototype.getEmitterPosition = function () {
  37190. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  37191. };
  37192. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  37193. var position = this.getEmitterPosition();
  37194. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  37195. this._positionX = position.x;
  37196. this._positionY = position.y;
  37197. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  37198. if (position.z > 0) {
  37199. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  37200. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  37201. return true;
  37202. }
  37203. }
  37204. return false;
  37205. };
  37206. LensFlareSystem.prototype._isVisible = function () {
  37207. if (!this._isEnabled) {
  37208. return false;
  37209. }
  37210. var emitterPosition = this.getEmitterPosition();
  37211. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  37212. var distance = direction.length();
  37213. direction.normalize();
  37214. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  37215. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  37216. return !pickInfo.hit || pickInfo.distance > distance;
  37217. };
  37218. LensFlareSystem.prototype.render = function () {
  37219. if (!this._effect.isReady())
  37220. return false;
  37221. var engine = this._scene.getEngine();
  37222. var viewport = this._scene.activeCamera.viewport;
  37223. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  37224. // Position
  37225. if (!this.computeEffectivePosition(globalViewport)) {
  37226. return false;
  37227. }
  37228. // Visibility
  37229. if (!this._isVisible()) {
  37230. return false;
  37231. }
  37232. // Intensity
  37233. var awayX;
  37234. var awayY;
  37235. if (this._positionX < this.borderLimit + globalViewport.x) {
  37236. awayX = this.borderLimit + globalViewport.x - this._positionX;
  37237. }
  37238. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  37239. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  37240. }
  37241. else {
  37242. awayX = 0;
  37243. }
  37244. if (this._positionY < this.borderLimit + globalViewport.y) {
  37245. awayY = this.borderLimit + globalViewport.y - this._positionY;
  37246. }
  37247. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  37248. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  37249. }
  37250. else {
  37251. awayY = 0;
  37252. }
  37253. var away = (awayX > awayY) ? awayX : awayY;
  37254. if (away > this.borderLimit) {
  37255. away = this.borderLimit;
  37256. }
  37257. var intensity = 1.0 - (away / this.borderLimit);
  37258. if (intensity < 0) {
  37259. return false;
  37260. }
  37261. if (intensity > 1.0) {
  37262. intensity = 1.0;
  37263. }
  37264. // Position
  37265. var centerX = globalViewport.x + globalViewport.width / 2;
  37266. var centerY = globalViewport.y + globalViewport.height / 2;
  37267. var distX = centerX - this._positionX;
  37268. var distY = centerY - this._positionY;
  37269. // Effects
  37270. engine.enableEffect(this._effect);
  37271. engine.setState(false);
  37272. engine.setDepthBuffer(false);
  37273. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  37274. // VBOs
  37275. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  37276. // Flares
  37277. for (var index = 0; index < this.lensFlares.length; index++) {
  37278. var flare = this.lensFlares[index];
  37279. var x = centerX - (distX * flare.position);
  37280. var y = centerY - (distY * flare.position);
  37281. var cw = flare.size;
  37282. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  37283. var cx = 2 * (x / globalViewport.width) - 1.0;
  37284. var cy = 1.0 - 2 * (y / globalViewport.height);
  37285. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  37286. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  37287. // Texture
  37288. this._effect.setTexture("textureSampler", flare.texture);
  37289. // Color
  37290. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  37291. // Draw order
  37292. engine.draw(true, 0, 6);
  37293. }
  37294. engine.setDepthBuffer(true);
  37295. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37296. return true;
  37297. };
  37298. LensFlareSystem.prototype.dispose = function () {
  37299. if (this._vertexBuffer) {
  37300. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  37301. this._vertexBuffer = null;
  37302. }
  37303. if (this._indexBuffer) {
  37304. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37305. this._indexBuffer = null;
  37306. }
  37307. while (this.lensFlares.length) {
  37308. this.lensFlares[0].dispose();
  37309. }
  37310. // Remove from scene
  37311. var index = this._scene.lensFlareSystems.indexOf(this);
  37312. this._scene.lensFlareSystems.splice(index, 1);
  37313. };
  37314. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  37315. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  37316. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  37317. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  37318. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  37319. var parsedFlare = parsedLensFlareSystem.flares[index];
  37320. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  37321. }
  37322. return lensFlareSystem;
  37323. };
  37324. LensFlareSystem.prototype.serialize = function () {
  37325. var serializationObject = {};
  37326. serializationObject.emitterId = this.getEmitter().id;
  37327. serializationObject.borderLimit = this.borderLimit;
  37328. serializationObject.flares = [];
  37329. for (var index = 0; index < this.lensFlares.length; index++) {
  37330. var flare = this.lensFlares[index];
  37331. serializationObject.flares.push({
  37332. size: flare.size,
  37333. position: flare.position,
  37334. color: flare.color.asArray(),
  37335. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  37336. });
  37337. }
  37338. return serializationObject;
  37339. };
  37340. return LensFlareSystem;
  37341. })();
  37342. BABYLON.LensFlareSystem = LensFlareSystem;
  37343. })(BABYLON || (BABYLON = {}));
  37344. var BABYLON;
  37345. (function (BABYLON) {
  37346. // We're mainly based on the logic defined into the FreeCamera code
  37347. var DeviceOrientationCamera = (function (_super) {
  37348. __extends(DeviceOrientationCamera, _super);
  37349. //-- end properties for backward compatibility for inputs
  37350. function DeviceOrientationCamera(name, position, scene) {
  37351. _super.call(this, name, position, scene);
  37352. this.inputs.addDeviceOrientation();
  37353. }
  37354. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  37355. //-- Begin properties for backward compatibility for inputs
  37356. get: function () {
  37357. var gamepad = this.inputs.attached["deviceOrientation"];
  37358. if (gamepad)
  37359. return gamepad.angularSensibility;
  37360. },
  37361. set: function (value) {
  37362. var gamepad = this.inputs.attached["deviceOrientation"];
  37363. if (gamepad)
  37364. gamepad.angularSensibility = value;
  37365. },
  37366. enumerable: true,
  37367. configurable: true
  37368. });
  37369. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  37370. get: function () {
  37371. var gamepad = this.inputs.attached["deviceOrientation"];
  37372. if (gamepad)
  37373. return gamepad.moveSensibility;
  37374. },
  37375. set: function (value) {
  37376. var gamepad = this.inputs.attached["deviceOrientation"];
  37377. if (gamepad)
  37378. gamepad.moveSensibility = value;
  37379. },
  37380. enumerable: true,
  37381. configurable: true
  37382. });
  37383. DeviceOrientationCamera.prototype.getTypeName = function () {
  37384. return "DeviceOrientationCamera";
  37385. };
  37386. return DeviceOrientationCamera;
  37387. })(BABYLON.FreeCamera);
  37388. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  37389. })(BABYLON || (BABYLON = {}));
  37390. var BABYLON;
  37391. (function (BABYLON) {
  37392. // We're mainly based on the logic defined into the FreeCamera code
  37393. var UniversalCamera = (function (_super) {
  37394. __extends(UniversalCamera, _super);
  37395. //-- end properties for backward compatibility for inputs
  37396. function UniversalCamera(name, position, scene) {
  37397. _super.call(this, name, position, scene);
  37398. this.inputs.addGamepad();
  37399. }
  37400. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  37401. //-- Begin properties for backward compatibility for inputs
  37402. get: function () {
  37403. var gamepad = this.inputs.attached["gamepad"];
  37404. if (gamepad)
  37405. return gamepad.gamepadAngularSensibility;
  37406. },
  37407. set: function (value) {
  37408. var gamepad = this.inputs.attached["gamepad"];
  37409. if (gamepad)
  37410. gamepad.gamepadAngularSensibility = value;
  37411. },
  37412. enumerable: true,
  37413. configurable: true
  37414. });
  37415. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  37416. get: function () {
  37417. var gamepad = this.inputs.attached["gamepad"];
  37418. if (gamepad)
  37419. return gamepad.gamepadMoveSensibility;
  37420. },
  37421. set: function (value) {
  37422. var gamepad = this.inputs.attached["gamepad"];
  37423. if (gamepad)
  37424. gamepad.gamepadMoveSensibility = value;
  37425. },
  37426. enumerable: true,
  37427. configurable: true
  37428. });
  37429. UniversalCamera.prototype.getTypeName = function () {
  37430. return "UniversalCamera";
  37431. };
  37432. return UniversalCamera;
  37433. })(BABYLON.TouchCamera);
  37434. BABYLON.UniversalCamera = UniversalCamera;
  37435. })(BABYLON || (BABYLON = {}));
  37436. var BABYLON;
  37437. (function (BABYLON) {
  37438. var Gamepads = (function () {
  37439. function Gamepads(ongamedpadconnected) {
  37440. var _this = this;
  37441. this.babylonGamepads = [];
  37442. this.oneGamepadConnected = false;
  37443. this.isMonitoring = false;
  37444. this.gamepadEventSupported = 'GamepadEvent' in window;
  37445. this.gamepadSupportAvailable = (navigator.getGamepads ||
  37446. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  37447. this._callbackGamepadConnected = ongamedpadconnected;
  37448. if (this.gamepadSupportAvailable) {
  37449. // Checking if the gamepad connected event is supported (like in Firefox)
  37450. if (this.gamepadEventSupported) {
  37451. this._onGamepadConnectedEvent = function (evt) {
  37452. _this._onGamepadConnected(evt);
  37453. };
  37454. this._onGamepadDisonnectedEvent = function (evt) {
  37455. _this._onGamepadDisconnected(evt);
  37456. };
  37457. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  37458. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  37459. }
  37460. else {
  37461. this._startMonitoringGamepads();
  37462. }
  37463. }
  37464. }
  37465. Gamepads.prototype.dispose = function () {
  37466. if (Gamepads.gamepadDOMInfo) {
  37467. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37468. }
  37469. if (this._onGamepadConnectedEvent) {
  37470. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  37471. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  37472. this._onGamepadConnectedEvent = null;
  37473. this._onGamepadDisonnectedEvent = null;
  37474. }
  37475. };
  37476. Gamepads.prototype._onGamepadConnected = function (evt) {
  37477. var newGamepad = this._addNewGamepad(evt.gamepad);
  37478. if (this._callbackGamepadConnected)
  37479. this._callbackGamepadConnected(newGamepad);
  37480. this._startMonitoringGamepads();
  37481. };
  37482. Gamepads.prototype._addNewGamepad = function (gamepad) {
  37483. if (!this.oneGamepadConnected) {
  37484. this.oneGamepadConnected = true;
  37485. if (Gamepads.gamepadDOMInfo) {
  37486. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37487. Gamepads.gamepadDOMInfo = null;
  37488. }
  37489. }
  37490. var newGamepad;
  37491. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  37492. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  37493. }
  37494. else {
  37495. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  37496. }
  37497. this.babylonGamepads.push(newGamepad);
  37498. return newGamepad;
  37499. };
  37500. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  37501. // Remove the gamepad from the list of gamepads to monitor.
  37502. for (var i in this.babylonGamepads) {
  37503. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  37504. this.babylonGamepads.splice(+i, 1);
  37505. break;
  37506. }
  37507. }
  37508. // If no gamepads are left, stop the polling loop.
  37509. if (this.babylonGamepads.length == 0) {
  37510. this._stopMonitoringGamepads();
  37511. }
  37512. };
  37513. Gamepads.prototype._startMonitoringGamepads = function () {
  37514. if (!this.isMonitoring) {
  37515. this.isMonitoring = true;
  37516. this._checkGamepadsStatus();
  37517. }
  37518. };
  37519. Gamepads.prototype._stopMonitoringGamepads = function () {
  37520. this.isMonitoring = false;
  37521. };
  37522. Gamepads.prototype._checkGamepadsStatus = function () {
  37523. var _this = this;
  37524. // updating gamepad objects
  37525. this._updateGamepadObjects();
  37526. for (var i in this.babylonGamepads) {
  37527. this.babylonGamepads[i].update();
  37528. }
  37529. if (this.isMonitoring) {
  37530. if (window.requestAnimationFrame) {
  37531. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37532. }
  37533. else if (window.mozRequestAnimationFrame) {
  37534. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37535. }
  37536. else if (window.webkitRequestAnimationFrame) {
  37537. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37538. }
  37539. }
  37540. };
  37541. // This function is called only on Chrome, which does not yet support
  37542. // connection/disconnection events, but requires you to monitor
  37543. // an array for changes.
  37544. Gamepads.prototype._updateGamepadObjects = function () {
  37545. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  37546. for (var i = 0; i < gamepads.length; i++) {
  37547. if (gamepads[i]) {
  37548. if (!(gamepads[i].index in this.babylonGamepads)) {
  37549. var newGamepad = this._addNewGamepad(gamepads[i]);
  37550. if (this._callbackGamepadConnected) {
  37551. this._callbackGamepadConnected(newGamepad);
  37552. }
  37553. }
  37554. else {
  37555. this.babylonGamepads[i].browserGamepad = gamepads[i];
  37556. }
  37557. }
  37558. }
  37559. };
  37560. return Gamepads;
  37561. })();
  37562. BABYLON.Gamepads = Gamepads;
  37563. var StickValues = (function () {
  37564. function StickValues(x, y) {
  37565. this.x = x;
  37566. this.y = y;
  37567. }
  37568. return StickValues;
  37569. })();
  37570. BABYLON.StickValues = StickValues;
  37571. var Gamepad = (function () {
  37572. function Gamepad(id, index, browserGamepad) {
  37573. this.id = id;
  37574. this.index = index;
  37575. this.browserGamepad = browserGamepad;
  37576. if (this.browserGamepad.axes.length >= 2) {
  37577. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37578. }
  37579. if (this.browserGamepad.axes.length >= 4) {
  37580. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37581. }
  37582. }
  37583. Gamepad.prototype.onleftstickchanged = function (callback) {
  37584. this._onleftstickchanged = callback;
  37585. };
  37586. Gamepad.prototype.onrightstickchanged = function (callback) {
  37587. this._onrightstickchanged = callback;
  37588. };
  37589. Object.defineProperty(Gamepad.prototype, "leftStick", {
  37590. get: function () {
  37591. return this._leftStick;
  37592. },
  37593. set: function (newValues) {
  37594. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  37595. this._onleftstickchanged(newValues);
  37596. }
  37597. this._leftStick = newValues;
  37598. },
  37599. enumerable: true,
  37600. configurable: true
  37601. });
  37602. Object.defineProperty(Gamepad.prototype, "rightStick", {
  37603. get: function () {
  37604. return this._rightStick;
  37605. },
  37606. set: function (newValues) {
  37607. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  37608. this._onrightstickchanged(newValues);
  37609. }
  37610. this._rightStick = newValues;
  37611. },
  37612. enumerable: true,
  37613. configurable: true
  37614. });
  37615. Gamepad.prototype.update = function () {
  37616. if (this._leftStick) {
  37617. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37618. }
  37619. if (this._rightStick) {
  37620. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37621. }
  37622. };
  37623. return Gamepad;
  37624. })();
  37625. BABYLON.Gamepad = Gamepad;
  37626. var GenericPad = (function (_super) {
  37627. __extends(GenericPad, _super);
  37628. function GenericPad(id, index, gamepad) {
  37629. _super.call(this, id, index, gamepad);
  37630. this.id = id;
  37631. this.index = index;
  37632. this.gamepad = gamepad;
  37633. this._buttons = new Array(gamepad.buttons.length);
  37634. }
  37635. GenericPad.prototype.onbuttondown = function (callback) {
  37636. this._onbuttondown = callback;
  37637. };
  37638. GenericPad.prototype.onbuttonup = function (callback) {
  37639. this._onbuttonup = callback;
  37640. };
  37641. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  37642. if (newValue !== currentValue) {
  37643. if (this._onbuttondown && newValue === 1) {
  37644. this._onbuttondown(buttonIndex);
  37645. }
  37646. if (this._onbuttonup && newValue === 0) {
  37647. this._onbuttonup(buttonIndex);
  37648. }
  37649. }
  37650. return newValue;
  37651. };
  37652. GenericPad.prototype.update = function () {
  37653. _super.prototype.update.call(this);
  37654. for (var index = 0; index < this._buttons.length; index++) {
  37655. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  37656. }
  37657. };
  37658. return GenericPad;
  37659. })(Gamepad);
  37660. BABYLON.GenericPad = GenericPad;
  37661. (function (Xbox360Button) {
  37662. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  37663. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  37664. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  37665. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  37666. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  37667. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  37668. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  37669. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  37670. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  37671. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  37672. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  37673. var Xbox360Button = BABYLON.Xbox360Button;
  37674. (function (Xbox360Dpad) {
  37675. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  37676. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  37677. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  37678. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  37679. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  37680. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  37681. var Xbox360Pad = (function (_super) {
  37682. __extends(Xbox360Pad, _super);
  37683. function Xbox360Pad() {
  37684. _super.apply(this, arguments);
  37685. this._leftTrigger = 0;
  37686. this._rightTrigger = 0;
  37687. this._buttonA = 0;
  37688. this._buttonB = 0;
  37689. this._buttonX = 0;
  37690. this._buttonY = 0;
  37691. this._buttonBack = 0;
  37692. this._buttonStart = 0;
  37693. this._buttonLB = 0;
  37694. this._buttonRB = 0;
  37695. this._buttonLeftStick = 0;
  37696. this._buttonRightStick = 0;
  37697. this._dPadUp = 0;
  37698. this._dPadDown = 0;
  37699. this._dPadLeft = 0;
  37700. this._dPadRight = 0;
  37701. }
  37702. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  37703. this._onlefttriggerchanged = callback;
  37704. };
  37705. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  37706. this._onrighttriggerchanged = callback;
  37707. };
  37708. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  37709. get: function () {
  37710. return this._leftTrigger;
  37711. },
  37712. set: function (newValue) {
  37713. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  37714. this._onlefttriggerchanged(newValue);
  37715. }
  37716. this._leftTrigger = newValue;
  37717. },
  37718. enumerable: true,
  37719. configurable: true
  37720. });
  37721. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  37722. get: function () {
  37723. return this._rightTrigger;
  37724. },
  37725. set: function (newValue) {
  37726. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  37727. this._onrighttriggerchanged(newValue);
  37728. }
  37729. this._rightTrigger = newValue;
  37730. },
  37731. enumerable: true,
  37732. configurable: true
  37733. });
  37734. Xbox360Pad.prototype.onbuttondown = function (callback) {
  37735. this._onbuttondown = callback;
  37736. };
  37737. Xbox360Pad.prototype.onbuttonup = function (callback) {
  37738. this._onbuttonup = callback;
  37739. };
  37740. Xbox360Pad.prototype.ondpaddown = function (callback) {
  37741. this._ondpaddown = callback;
  37742. };
  37743. Xbox360Pad.prototype.ondpadup = function (callback) {
  37744. this._ondpadup = callback;
  37745. };
  37746. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  37747. if (newValue !== currentValue) {
  37748. if (this._onbuttondown && newValue === 1) {
  37749. this._onbuttondown(buttonType);
  37750. }
  37751. if (this._onbuttonup && newValue === 0) {
  37752. this._onbuttonup(buttonType);
  37753. }
  37754. }
  37755. return newValue;
  37756. };
  37757. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  37758. if (newValue !== currentValue) {
  37759. if (this._ondpaddown && newValue === 1) {
  37760. this._ondpaddown(buttonType);
  37761. }
  37762. if (this._ondpadup && newValue === 0) {
  37763. this._ondpadup(buttonType);
  37764. }
  37765. }
  37766. return newValue;
  37767. };
  37768. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  37769. get: function () {
  37770. return this._buttonA;
  37771. },
  37772. set: function (value) {
  37773. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  37774. },
  37775. enumerable: true,
  37776. configurable: true
  37777. });
  37778. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  37779. get: function () {
  37780. return this._buttonB;
  37781. },
  37782. set: function (value) {
  37783. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  37784. },
  37785. enumerable: true,
  37786. configurable: true
  37787. });
  37788. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  37789. get: function () {
  37790. return this._buttonX;
  37791. },
  37792. set: function (value) {
  37793. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  37794. },
  37795. enumerable: true,
  37796. configurable: true
  37797. });
  37798. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  37799. get: function () {
  37800. return this._buttonY;
  37801. },
  37802. set: function (value) {
  37803. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  37804. },
  37805. enumerable: true,
  37806. configurable: true
  37807. });
  37808. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  37809. get: function () {
  37810. return this._buttonStart;
  37811. },
  37812. set: function (value) {
  37813. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  37814. },
  37815. enumerable: true,
  37816. configurable: true
  37817. });
  37818. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  37819. get: function () {
  37820. return this._buttonBack;
  37821. },
  37822. set: function (value) {
  37823. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  37824. },
  37825. enumerable: true,
  37826. configurable: true
  37827. });
  37828. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  37829. get: function () {
  37830. return this._buttonLB;
  37831. },
  37832. set: function (value) {
  37833. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  37834. },
  37835. enumerable: true,
  37836. configurable: true
  37837. });
  37838. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  37839. get: function () {
  37840. return this._buttonRB;
  37841. },
  37842. set: function (value) {
  37843. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  37844. },
  37845. enumerable: true,
  37846. configurable: true
  37847. });
  37848. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  37849. get: function () {
  37850. return this._buttonLeftStick;
  37851. },
  37852. set: function (value) {
  37853. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  37854. },
  37855. enumerable: true,
  37856. configurable: true
  37857. });
  37858. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  37859. get: function () {
  37860. return this._buttonRightStick;
  37861. },
  37862. set: function (value) {
  37863. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  37864. },
  37865. enumerable: true,
  37866. configurable: true
  37867. });
  37868. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  37869. get: function () {
  37870. return this._dPadUp;
  37871. },
  37872. set: function (value) {
  37873. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  37874. },
  37875. enumerable: true,
  37876. configurable: true
  37877. });
  37878. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  37879. get: function () {
  37880. return this._dPadDown;
  37881. },
  37882. set: function (value) {
  37883. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  37884. },
  37885. enumerable: true,
  37886. configurable: true
  37887. });
  37888. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  37889. get: function () {
  37890. return this._dPadLeft;
  37891. },
  37892. set: function (value) {
  37893. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  37894. },
  37895. enumerable: true,
  37896. configurable: true
  37897. });
  37898. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  37899. get: function () {
  37900. return this._dPadRight;
  37901. },
  37902. set: function (value) {
  37903. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  37904. },
  37905. enumerable: true,
  37906. configurable: true
  37907. });
  37908. Xbox360Pad.prototype.update = function () {
  37909. _super.prototype.update.call(this);
  37910. this.buttonA = this.browserGamepad.buttons[0].value;
  37911. this.buttonB = this.browserGamepad.buttons[1].value;
  37912. this.buttonX = this.browserGamepad.buttons[2].value;
  37913. this.buttonY = this.browserGamepad.buttons[3].value;
  37914. this.buttonLB = this.browserGamepad.buttons[4].value;
  37915. this.buttonRB = this.browserGamepad.buttons[5].value;
  37916. this.leftTrigger = this.browserGamepad.buttons[6].value;
  37917. this.rightTrigger = this.browserGamepad.buttons[7].value;
  37918. this.buttonBack = this.browserGamepad.buttons[8].value;
  37919. this.buttonStart = this.browserGamepad.buttons[9].value;
  37920. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  37921. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  37922. this.dPadUp = this.browserGamepad.buttons[12].value;
  37923. this.dPadDown = this.browserGamepad.buttons[13].value;
  37924. this.dPadLeft = this.browserGamepad.buttons[14].value;
  37925. this.dPadRight = this.browserGamepad.buttons[15].value;
  37926. };
  37927. return Xbox360Pad;
  37928. })(Gamepad);
  37929. BABYLON.Xbox360Pad = Xbox360Pad;
  37930. })(BABYLON || (BABYLON = {}));
  37931. var BABYLON;
  37932. (function (BABYLON) {
  37933. // We're mainly based on the logic defined into the FreeCamera code
  37934. var GamepadCamera = (function (_super) {
  37935. __extends(GamepadCamera, _super);
  37936. //-- end properties for backward compatibility for inputs
  37937. function GamepadCamera(name, position, scene) {
  37938. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  37939. _super.call(this, name, position, scene);
  37940. }
  37941. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  37942. //-- Begin properties for backward compatibility for inputs
  37943. get: function () {
  37944. var gamepad = this.inputs.attached["gamepad"];
  37945. if (gamepad)
  37946. return gamepad.gamepadAngularSensibility;
  37947. },
  37948. set: function (value) {
  37949. var gamepad = this.inputs.attached["gamepad"];
  37950. if (gamepad)
  37951. gamepad.gamepadAngularSensibility = value;
  37952. },
  37953. enumerable: true,
  37954. configurable: true
  37955. });
  37956. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  37957. get: function () {
  37958. var gamepad = this.inputs.attached["gamepad"];
  37959. if (gamepad)
  37960. return gamepad.gamepadMoveSensibility;
  37961. },
  37962. set: function (value) {
  37963. var gamepad = this.inputs.attached["gamepad"];
  37964. if (gamepad)
  37965. gamepad.gamepadMoveSensibility = value;
  37966. },
  37967. enumerable: true,
  37968. configurable: true
  37969. });
  37970. GamepadCamera.prototype.getTypeName = function () {
  37971. return "GamepadCamera";
  37972. };
  37973. return GamepadCamera;
  37974. })(BABYLON.UniversalCamera);
  37975. BABYLON.GamepadCamera = GamepadCamera;
  37976. })(BABYLON || (BABYLON = {}));
  37977. var BABYLON;
  37978. (function (BABYLON) {
  37979. var Analyser = (function () {
  37980. function Analyser(scene) {
  37981. this.SMOOTHING = 0.75;
  37982. this.FFT_SIZE = 512;
  37983. this.BARGRAPHAMPLITUDE = 256;
  37984. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  37985. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  37986. this._scene = scene;
  37987. this._audioEngine = BABYLON.Engine.audioEngine;
  37988. if (this._audioEngine.canUseWebAudio) {
  37989. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  37990. this._webAudioAnalyser.minDecibels = -140;
  37991. this._webAudioAnalyser.maxDecibels = 0;
  37992. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  37993. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  37994. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  37995. }
  37996. }
  37997. Analyser.prototype.getFrequencyBinCount = function () {
  37998. if (this._audioEngine.canUseWebAudio) {
  37999. return this._webAudioAnalyser.frequencyBinCount;
  38000. }
  38001. else {
  38002. return 0;
  38003. }
  38004. };
  38005. Analyser.prototype.getByteFrequencyData = function () {
  38006. if (this._audioEngine.canUseWebAudio) {
  38007. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  38008. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  38009. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  38010. }
  38011. return this._byteFreqs;
  38012. };
  38013. Analyser.prototype.getByteTimeDomainData = function () {
  38014. if (this._audioEngine.canUseWebAudio) {
  38015. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  38016. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  38017. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  38018. }
  38019. return this._byteTime;
  38020. };
  38021. Analyser.prototype.getFloatFrequencyData = function () {
  38022. if (this._audioEngine.canUseWebAudio) {
  38023. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  38024. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  38025. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  38026. }
  38027. return this._floatFreqs;
  38028. };
  38029. Analyser.prototype.drawDebugCanvas = function () {
  38030. var _this = this;
  38031. if (this._audioEngine.canUseWebAudio) {
  38032. if (!this._debugCanvas) {
  38033. this._debugCanvas = document.createElement("canvas");
  38034. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  38035. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  38036. this._debugCanvas.style.position = "absolute";
  38037. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  38038. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  38039. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  38040. document.body.appendChild(this._debugCanvas);
  38041. this._registerFunc = function () {
  38042. _this.drawDebugCanvas();
  38043. };
  38044. this._scene.registerBeforeRender(this._registerFunc);
  38045. }
  38046. if (this._registerFunc) {
  38047. var workingArray = this.getByteFrequencyData();
  38048. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  38049. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  38050. // Draw the frequency domain chart.
  38051. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  38052. var value = workingArray[i];
  38053. var percent = value / this.BARGRAPHAMPLITUDE;
  38054. var height = this.DEBUGCANVASSIZE.height * percent;
  38055. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  38056. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  38057. var hue = i / this.getFrequencyBinCount() * 360;
  38058. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  38059. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  38060. }
  38061. }
  38062. }
  38063. };
  38064. Analyser.prototype.stopDebugCanvas = function () {
  38065. if (this._debugCanvas) {
  38066. this._scene.unregisterBeforeRender(this._registerFunc);
  38067. this._registerFunc = null;
  38068. document.body.removeChild(this._debugCanvas);
  38069. this._debugCanvas = null;
  38070. this._debugCanvasContext = null;
  38071. }
  38072. };
  38073. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  38074. if (this._audioEngine.canUseWebAudio) {
  38075. inputAudioNode.connect(this._webAudioAnalyser);
  38076. this._webAudioAnalyser.connect(outputAudioNode);
  38077. }
  38078. };
  38079. Analyser.prototype.dispose = function () {
  38080. if (this._audioEngine.canUseWebAudio) {
  38081. this._webAudioAnalyser.disconnect();
  38082. }
  38083. };
  38084. return Analyser;
  38085. })();
  38086. BABYLON.Analyser = Analyser;
  38087. })(BABYLON || (BABYLON = {}));
  38088. var BABYLON;
  38089. (function (BABYLON) {
  38090. var DepthRenderer = (function () {
  38091. function DepthRenderer(scene, type) {
  38092. var _this = this;
  38093. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  38094. this._viewMatrix = BABYLON.Matrix.Zero();
  38095. this._projectionMatrix = BABYLON.Matrix.Zero();
  38096. this._transformMatrix = BABYLON.Matrix.Zero();
  38097. this._worldViewProjection = BABYLON.Matrix.Zero();
  38098. this._scene = scene;
  38099. var engine = scene.getEngine();
  38100. // Render target
  38101. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  38102. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38103. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38104. this._depthMap.refreshRate = 1;
  38105. this._depthMap.renderParticles = false;
  38106. this._depthMap.renderList = null;
  38107. // set default depth value to 1.0 (far away)
  38108. this._depthMap.onClear = function (engine) {
  38109. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  38110. };
  38111. // Custom render function
  38112. var renderSubMesh = function (subMesh) {
  38113. var mesh = subMesh.getRenderingMesh();
  38114. var scene = _this._scene;
  38115. var engine = scene.getEngine();
  38116. // Culling
  38117. engine.setState(subMesh.getMaterial().backFaceCulling);
  38118. // Managing instances
  38119. var batch = mesh._getInstancesRenderList(subMesh._id);
  38120. if (batch.mustReturn) {
  38121. return;
  38122. }
  38123. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  38124. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  38125. engine.enableEffect(_this._effect);
  38126. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  38127. var material = subMesh.getMaterial();
  38128. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  38129. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  38130. // Alpha test
  38131. if (material && material.needAlphaTesting()) {
  38132. var alphaTexture = material.getAlphaTestTexture();
  38133. _this._effect.setTexture("diffuseSampler", alphaTexture);
  38134. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38135. }
  38136. // Bones
  38137. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38138. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38139. }
  38140. // Draw
  38141. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  38142. }
  38143. };
  38144. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  38145. var index;
  38146. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38147. renderSubMesh(opaqueSubMeshes.data[index]);
  38148. }
  38149. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38150. renderSubMesh(alphaTestSubMeshes.data[index]);
  38151. }
  38152. };
  38153. }
  38154. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  38155. var defines = [];
  38156. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38157. var mesh = subMesh.getMesh();
  38158. var scene = mesh.getScene();
  38159. var material = subMesh.getMaterial();
  38160. // Alpha test
  38161. if (material && material.needAlphaTesting()) {
  38162. defines.push("#define ALPHATEST");
  38163. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38164. attribs.push(BABYLON.VertexBuffer.UVKind);
  38165. defines.push("#define UV1");
  38166. }
  38167. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38168. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38169. defines.push("#define UV2");
  38170. }
  38171. }
  38172. // Bones
  38173. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38174. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38175. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38176. if (mesh.numBoneInfluencers > 4) {
  38177. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38178. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38179. }
  38180. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38181. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38182. }
  38183. else {
  38184. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38185. }
  38186. // Instances
  38187. if (useInstances) {
  38188. defines.push("#define INSTANCES");
  38189. attribs.push("world0");
  38190. attribs.push("world1");
  38191. attribs.push("world2");
  38192. attribs.push("world3");
  38193. }
  38194. // Get correct effect
  38195. var join = defines.join("\n");
  38196. if (this._cachedDefines !== join) {
  38197. this._cachedDefines = join;
  38198. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  38199. }
  38200. return this._effect.isReady();
  38201. };
  38202. DepthRenderer.prototype.getDepthMap = function () {
  38203. return this._depthMap;
  38204. };
  38205. // Methods
  38206. DepthRenderer.prototype.dispose = function () {
  38207. this._depthMap.dispose();
  38208. };
  38209. return DepthRenderer;
  38210. })();
  38211. BABYLON.DepthRenderer = DepthRenderer;
  38212. })(BABYLON || (BABYLON = {}));
  38213. var BABYLON;
  38214. (function (BABYLON) {
  38215. var SSAORenderingPipeline = (function (_super) {
  38216. __extends(SSAORenderingPipeline, _super);
  38217. /**
  38218. * @constructor
  38219. * @param {string} name - The rendering pipeline name
  38220. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  38221. * @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 }
  38222. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  38223. */
  38224. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  38225. var _this = this;
  38226. _super.call(this, scene.getEngine(), name);
  38227. // Members
  38228. /**
  38229. * The PassPostProcess id in the pipeline that contains the original scene color
  38230. * @type {string}
  38231. */
  38232. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  38233. /**
  38234. * The SSAO PostProcess id in the pipeline
  38235. * @type {string}
  38236. */
  38237. this.SSAORenderEffect = "SSAORenderEffect";
  38238. /**
  38239. * The horizontal blur PostProcess id in the pipeline
  38240. * @type {string}
  38241. */
  38242. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  38243. /**
  38244. * The vertical blur PostProcess id in the pipeline
  38245. * @type {string}
  38246. */
  38247. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  38248. /**
  38249. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  38250. * @type {string}
  38251. */
  38252. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  38253. /**
  38254. * The output strength of the SSAO post-process. Default value is 1.0.
  38255. * @type {number}
  38256. */
  38257. this.totalStrength = 1.0;
  38258. /**
  38259. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  38260. * @type {number}
  38261. */
  38262. this.radius = 0.0001;
  38263. /**
  38264. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  38265. * Must not be equal to fallOff and superior to fallOff.
  38266. * Default value is 0.975
  38267. * @type {number}
  38268. */
  38269. this.area = 0.0075;
  38270. /**
  38271. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  38272. * Must not be equal to area and inferior to area.
  38273. * Default value is 0.0
  38274. * @type {number}
  38275. */
  38276. this.fallOff = 0.000001;
  38277. /**
  38278. * The base color of the SSAO post-process
  38279. * The final result is "base + ssao" between [0, 1]
  38280. * @type {number}
  38281. */
  38282. this.base = 0.5;
  38283. this._firstUpdate = true;
  38284. this._scene = scene;
  38285. // Set up assets
  38286. this._createRandomTexture();
  38287. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  38288. var ssaoRatio = ratio.ssaoRatio || ratio;
  38289. var combineRatio = ratio.combineRatio || ratio;
  38290. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38291. this._createSSAOPostProcess(ssaoRatio);
  38292. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38293. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  38294. this._createSSAOCombinePostProcess(combineRatio);
  38295. // Set up pipeline
  38296. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  38297. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  38298. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  38299. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  38300. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  38301. // Finish
  38302. scene.postProcessRenderPipelineManager.addPipeline(this);
  38303. if (cameras)
  38304. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  38305. }
  38306. // Public Methods
  38307. /**
  38308. * Returns the horizontal blur PostProcess
  38309. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  38310. */
  38311. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  38312. return this._blurHPostProcess;
  38313. };
  38314. /**
  38315. * Returns the vertical blur PostProcess
  38316. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  38317. */
  38318. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  38319. return this._blurVPostProcess;
  38320. };
  38321. /**
  38322. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  38323. */
  38324. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  38325. if (disableDepthRender === void 0) { disableDepthRender = false; }
  38326. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  38327. this._originalColorPostProcess = undefined;
  38328. this._ssaoPostProcess = undefined;
  38329. this._blurHPostProcess = undefined;
  38330. this._blurVPostProcess = undefined;
  38331. this._ssaoCombinePostProcess = undefined;
  38332. this._randomTexture.dispose();
  38333. if (disableDepthRender)
  38334. this._scene.disableDepthRenderer();
  38335. };
  38336. // Private Methods
  38337. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  38338. var _this = this;
  38339. var numSamples = 16;
  38340. var sampleSphere = [
  38341. 0.5381, 0.1856, -0.4319,
  38342. 0.1379, 0.2486, 0.4430,
  38343. 0.3371, 0.5679, -0.0057,
  38344. -0.6999, -0.0451, -0.0019,
  38345. 0.0689, -0.1598, -0.8547,
  38346. 0.0560, 0.0069, -0.1843,
  38347. -0.0146, 0.1402, 0.0762,
  38348. 0.0100, -0.1924, -0.0344,
  38349. -0.3577, -0.5301, -0.4358,
  38350. -0.3169, 0.1063, 0.0158,
  38351. 0.0103, -0.5869, 0.0046,
  38352. -0.0897, -0.4940, 0.3287,
  38353. 0.7119, -0.0154, -0.0918,
  38354. -0.0533, 0.0596, -0.5411,
  38355. 0.0352, -0.0631, 0.5460,
  38356. -0.4776, 0.2847, -0.0271
  38357. ];
  38358. var samplesFactor = 1.0 / numSamples;
  38359. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  38360. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  38361. "area", "fallOff", "base"
  38362. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  38363. this._ssaoPostProcess.onApply = function (effect) {
  38364. if (_this._firstUpdate) {
  38365. effect.setArray3("sampleSphere", sampleSphere);
  38366. effect.setFloat("samplesFactor", samplesFactor);
  38367. effect.setFloat("randTextureTiles", 4.0);
  38368. _this._firstUpdate = false;
  38369. }
  38370. effect.setFloat("totalStrength", _this.totalStrength);
  38371. effect.setFloat("radius", _this.radius);
  38372. effect.setFloat("area", _this.area);
  38373. effect.setFloat("fallOff", _this.fallOff);
  38374. effect.setFloat("base", _this.base);
  38375. effect.setTexture("textureSampler", _this._depthTexture);
  38376. effect.setTexture("randomSampler", _this._randomTexture);
  38377. };
  38378. };
  38379. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  38380. var _this = this;
  38381. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  38382. this._ssaoCombinePostProcess.onApply = function (effect) {
  38383. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  38384. };
  38385. };
  38386. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  38387. var size = 512;
  38388. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38389. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  38390. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  38391. var context = this._randomTexture.getContext();
  38392. var rand = function (min, max) {
  38393. return Math.random() * (max - min) + min;
  38394. };
  38395. var randVector = BABYLON.Vector3.Zero();
  38396. for (var x = 0; x < size; x++) {
  38397. for (var y = 0; y < size; y++) {
  38398. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  38399. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  38400. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  38401. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  38402. context.fillRect(x, y, 1, 1);
  38403. }
  38404. }
  38405. this._randomTexture.update(false);
  38406. };
  38407. return SSAORenderingPipeline;
  38408. })(BABYLON.PostProcessRenderPipeline);
  38409. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  38410. })(BABYLON || (BABYLON = {}));
  38411. var BABYLON;
  38412. (function (BABYLON) {
  38413. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  38414. var VolumetricLightScatteringPostProcess = (function (_super) {
  38415. __extends(VolumetricLightScatteringPostProcess, _super);
  38416. /**
  38417. * @constructor
  38418. * @param {string} name - The post-process name
  38419. * @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)
  38420. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  38421. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  38422. * @param {number} samples - The post-process quality, default 100
  38423. * @param {number} samplingMode - The post-process filtering mode
  38424. * @param {BABYLON.Engine} engine - The babylon engine
  38425. * @param {boolean} reusable - If the post-process is reusable
  38426. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  38427. */
  38428. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  38429. var _this = this;
  38430. if (samples === void 0) { samples = 100; }
  38431. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38432. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  38433. this._screenCoordinates = BABYLON.Vector2.Zero();
  38434. /**
  38435. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  38436. * @type {boolean}
  38437. */
  38438. this.useCustomMeshPosition = false;
  38439. /**
  38440. * If the post-process should inverse the light scattering direction
  38441. * @type {boolean}
  38442. */
  38443. this.invert = true;
  38444. /**
  38445. * Set to true to use the diffuseColor instead of the diffuseTexture
  38446. * @type {boolean}
  38447. */
  38448. this.useDiffuseColor = false;
  38449. /**
  38450. * Array containing the excluded meshes not rendered in the internal pass
  38451. */
  38452. this.excludedMeshes = new Array();
  38453. /**
  38454. * Controls the overall intensity of the post-process
  38455. * @type {number}
  38456. */
  38457. this.exposure = 0.3;
  38458. /**
  38459. * Dissipates each sample's contribution in range [0, 1]
  38460. * @type {number}
  38461. */
  38462. this.decay = 0.96815;
  38463. /**
  38464. * Controls the overall intensity of each sample
  38465. * @type {number}
  38466. */
  38467. this.weight = 0.58767;
  38468. /**
  38469. * Controls the density of each sample
  38470. * @type {number}
  38471. */
  38472. this.density = 0.926;
  38473. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  38474. var engine = scene.getEngine();
  38475. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  38476. // Configure mesh
  38477. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  38478. // Configure
  38479. this._createPass(scene, ratio.passRatio || ratio);
  38480. this.onActivate = function (camera) {
  38481. if (!_this.isSupported) {
  38482. _this.dispose(camera);
  38483. }
  38484. _this.onActivate = null;
  38485. };
  38486. this.onApply = function (effect) {
  38487. _this._updateMeshScreenCoordinates(scene);
  38488. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  38489. effect.setFloat("exposure", _this.exposure);
  38490. effect.setFloat("decay", _this.decay);
  38491. effect.setFloat("weight", _this.weight);
  38492. effect.setFloat("density", _this.density);
  38493. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  38494. };
  38495. }
  38496. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  38497. var mesh = subMesh.getMesh();
  38498. var defines = [];
  38499. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38500. var material = subMesh.getMaterial();
  38501. var needUV = false;
  38502. // Render this.mesh as default
  38503. if (mesh === this.mesh) {
  38504. if (this.useDiffuseColor) {
  38505. defines.push("#define DIFFUSE_COLOR_RENDER");
  38506. }
  38507. else if (material) {
  38508. if (material.diffuseTexture !== undefined) {
  38509. defines.push("#define BASIC_RENDER");
  38510. }
  38511. else {
  38512. defines.push("#define DIFFUSE_COLOR_RENDER");
  38513. }
  38514. }
  38515. defines.push("#define NEED_UV");
  38516. needUV = true;
  38517. }
  38518. // Alpha test
  38519. if (material) {
  38520. if (material.needAlphaTesting()) {
  38521. defines.push("#define ALPHATEST");
  38522. }
  38523. if (material.opacityTexture !== undefined) {
  38524. defines.push("#define OPACITY");
  38525. if (material.opacityTexture.getAlphaFromRGB) {
  38526. defines.push("#define OPACITYRGB");
  38527. }
  38528. if (!needUV) {
  38529. defines.push("#define NEED_UV");
  38530. }
  38531. }
  38532. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38533. attribs.push(BABYLON.VertexBuffer.UVKind);
  38534. defines.push("#define UV1");
  38535. }
  38536. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38537. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38538. defines.push("#define UV2");
  38539. }
  38540. }
  38541. // Bones
  38542. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38543. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38544. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38545. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38546. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38547. }
  38548. else {
  38549. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38550. }
  38551. // Instances
  38552. if (useInstances) {
  38553. defines.push("#define INSTANCES");
  38554. attribs.push("world0");
  38555. attribs.push("world1");
  38556. attribs.push("world2");
  38557. attribs.push("world3");
  38558. }
  38559. // Get correct effect
  38560. var join = defines.join("\n");
  38561. if (this._cachedDefines !== join) {
  38562. this._cachedDefines = join;
  38563. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  38564. }
  38565. return this._volumetricLightScatteringPass.isReady();
  38566. };
  38567. /**
  38568. * Sets the new light position for light scattering effect
  38569. * @param {BABYLON.Vector3} The new custom light position
  38570. */
  38571. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  38572. this._customMeshPosition = position;
  38573. };
  38574. /**
  38575. * Returns the light position for light scattering effect
  38576. * @return {BABYLON.Vector3} The custom light position
  38577. */
  38578. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  38579. return this._customMeshPosition;
  38580. };
  38581. /**
  38582. * Disposes the internal assets and detaches the post-process from the camera
  38583. */
  38584. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  38585. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  38586. if (rttIndex !== -1) {
  38587. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  38588. }
  38589. this._volumetricLightScatteringRTT.dispose();
  38590. _super.prototype.dispose.call(this, camera);
  38591. };
  38592. /**
  38593. * Returns the render target texture used by the post-process
  38594. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  38595. */
  38596. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  38597. return this._volumetricLightScatteringRTT;
  38598. };
  38599. // Private methods
  38600. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  38601. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  38602. return true;
  38603. }
  38604. return false;
  38605. };
  38606. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  38607. var _this = this;
  38608. var engine = scene.getEngine();
  38609. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38610. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38611. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38612. this._volumetricLightScatteringRTT.renderList = null;
  38613. this._volumetricLightScatteringRTT.renderParticles = false;
  38614. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  38615. // Custom render function for submeshes
  38616. var renderSubMesh = function (subMesh) {
  38617. var mesh = subMesh.getRenderingMesh();
  38618. if (_this._meshExcluded(mesh)) {
  38619. return;
  38620. }
  38621. var scene = mesh.getScene();
  38622. var engine = scene.getEngine();
  38623. // Culling
  38624. engine.setState(subMesh.getMaterial().backFaceCulling);
  38625. // Managing instances
  38626. var batch = mesh._getInstancesRenderList(subMesh._id);
  38627. if (batch.mustReturn) {
  38628. return;
  38629. }
  38630. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  38631. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  38632. engine.enableEffect(_this._volumetricLightScatteringPass);
  38633. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  38634. var material = subMesh.getMaterial();
  38635. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  38636. // Alpha test
  38637. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  38638. var alphaTexture = material.getAlphaTestTexture();
  38639. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  38640. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  38641. }
  38642. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  38643. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  38644. if (alphaTexture) {
  38645. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38646. }
  38647. }
  38648. if (material.opacityTexture !== undefined) {
  38649. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  38650. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  38651. }
  38652. }
  38653. // Bones
  38654. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38655. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38656. }
  38657. // Draw
  38658. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  38659. }
  38660. };
  38661. // Render target texture callbacks
  38662. var savedSceneClearColor;
  38663. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  38664. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  38665. savedSceneClearColor = scene.clearColor;
  38666. scene.clearColor = sceneClearColor;
  38667. };
  38668. this._volumetricLightScatteringRTT.onAfterRender = function () {
  38669. scene.clearColor = savedSceneClearColor;
  38670. };
  38671. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38672. var engine = scene.getEngine();
  38673. var index;
  38674. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38675. renderSubMesh(opaqueSubMeshes.data[index]);
  38676. }
  38677. engine.setAlphaTesting(true);
  38678. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38679. renderSubMesh(alphaTestSubMeshes.data[index]);
  38680. }
  38681. engine.setAlphaTesting(false);
  38682. if (transparentSubMeshes.length) {
  38683. // Sort sub meshes
  38684. for (index = 0; index < transparentSubMeshes.length; index++) {
  38685. var submesh = transparentSubMeshes.data[index];
  38686. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  38687. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  38688. }
  38689. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  38690. sortedArray.sort(function (a, b) {
  38691. // Alpha index first
  38692. if (a._alphaIndex > b._alphaIndex) {
  38693. return 1;
  38694. }
  38695. if (a._alphaIndex < b._alphaIndex) {
  38696. return -1;
  38697. }
  38698. // Then distance to camera
  38699. if (a._distanceToCamera < b._distanceToCamera) {
  38700. return 1;
  38701. }
  38702. if (a._distanceToCamera > b._distanceToCamera) {
  38703. return -1;
  38704. }
  38705. return 0;
  38706. });
  38707. // Render sub meshes
  38708. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38709. for (index = 0; index < sortedArray.length; index++) {
  38710. renderSubMesh(sortedArray[index]);
  38711. }
  38712. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38713. }
  38714. };
  38715. };
  38716. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  38717. var transform = scene.getTransformMatrix();
  38718. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  38719. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  38720. this._screenCoordinates.x = pos.x / this._viewPort.width;
  38721. this._screenCoordinates.y = pos.y / this._viewPort.height;
  38722. if (this.invert)
  38723. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  38724. };
  38725. // Static methods
  38726. /**
  38727. * Creates a default mesh for the Volumeric Light Scattering post-process
  38728. * @param {string} The mesh name
  38729. * @param {BABYLON.Scene} The scene where to create the mesh
  38730. * @return {BABYLON.Mesh} the default mesh
  38731. */
  38732. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  38733. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  38734. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  38735. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  38736. return mesh;
  38737. };
  38738. return VolumetricLightScatteringPostProcess;
  38739. })(BABYLON.PostProcess);
  38740. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  38741. })(BABYLON || (BABYLON = {}));
  38742. // BABYLON.JS Chromatic Aberration GLSL Shader
  38743. // Author: Olivier Guyot
  38744. // Separates very slightly R, G and B colors on the edges of the screen
  38745. // Inspired by Francois Tarlier & Martins Upitis
  38746. var BABYLON;
  38747. (function (BABYLON) {
  38748. var LensRenderingPipeline = (function (_super) {
  38749. __extends(LensRenderingPipeline, _super);
  38750. /**
  38751. * @constructor
  38752. *
  38753. * Effect parameters are as follow:
  38754. * {
  38755. * chromatic_aberration: number; // from 0 to x (1 for realism)
  38756. * edge_blur: number; // from 0 to x (1 for realism)
  38757. * distortion: number; // from 0 to x (1 for realism)
  38758. * grain_amount: number; // from 0 to 1
  38759. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  38760. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  38761. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  38762. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  38763. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  38764. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  38765. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  38766. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  38767. * }
  38768. * Note: if an effect parameter is unset, effect is disabled
  38769. *
  38770. * @param {string} name - The rendering pipeline name
  38771. * @param {object} parameters - An object containing all parameters (see above)
  38772. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  38773. * @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)
  38774. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  38775. */
  38776. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  38777. var _this = this;
  38778. if (ratio === void 0) { ratio = 1.0; }
  38779. _super.call(this, scene.getEngine(), name);
  38780. // Lens effects can be of the following:
  38781. // - chromatic aberration (slight shift of RGB colors)
  38782. // - blur on the edge of the lens
  38783. // - lens distortion
  38784. // - depth-of-field blur & highlights enhancing
  38785. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  38786. // - grain effect (noise or custom texture)
  38787. // Two additional texture samplers are needed:
  38788. // - depth map (for depth-of-field)
  38789. // - grain texture
  38790. /**
  38791. * The chromatic aberration PostProcess id in the pipeline
  38792. * @type {string}
  38793. */
  38794. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  38795. /**
  38796. * The highlights enhancing PostProcess id in the pipeline
  38797. * @type {string}
  38798. */
  38799. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  38800. /**
  38801. * The depth-of-field PostProcess id in the pipeline
  38802. * @type {string}
  38803. */
  38804. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  38805. this._scene = scene;
  38806. // Fetch texture samplers
  38807. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  38808. if (parameters.grain_texture) {
  38809. this._grainTexture = parameters.grain_texture;
  38810. }
  38811. else {
  38812. this._createGrainTexture();
  38813. }
  38814. // save parameters
  38815. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  38816. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  38817. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  38818. this._distortion = parameters.distortion ? parameters.distortion : 0;
  38819. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  38820. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  38821. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  38822. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  38823. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  38824. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  38825. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  38826. // Create effects
  38827. this._createChromaticAberrationPostProcess(ratio);
  38828. this._createHighlightsPostProcess(ratio);
  38829. this._createDepthOfFieldPostProcess(ratio / 4);
  38830. // Set up pipeline
  38831. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  38832. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  38833. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  38834. if (this._highlightsGain === -1) {
  38835. this._disableEffect(this.HighlightsEnhancingEffect, null);
  38836. }
  38837. // Finish
  38838. scene.postProcessRenderPipelineManager.addPipeline(this);
  38839. if (cameras) {
  38840. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  38841. }
  38842. }
  38843. // public methods (self explanatory)
  38844. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  38845. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  38846. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  38847. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  38848. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  38849. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  38850. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  38851. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  38852. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  38853. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  38854. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  38855. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  38856. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  38857. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  38858. };
  38859. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  38860. this._highlightsPostProcess.updateEffect();
  38861. };
  38862. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  38863. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  38864. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  38865. this._highlightsGain = amount;
  38866. };
  38867. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  38868. if (this._highlightsGain === -1) {
  38869. this._highlightsGain = 1.0;
  38870. }
  38871. this._highlightsThreshold = amount;
  38872. };
  38873. LensRenderingPipeline.prototype.disableHighlights = function () {
  38874. this._highlightsGain = -1;
  38875. };
  38876. /**
  38877. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  38878. */
  38879. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  38880. if (disableDepthRender === void 0) { disableDepthRender = false; }
  38881. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  38882. this._chromaticAberrationPostProcess = undefined;
  38883. this._highlightsPostProcess = undefined;
  38884. this._depthOfFieldPostProcess = undefined;
  38885. this._grainTexture.dispose();
  38886. if (disableDepthRender)
  38887. this._scene.disableDepthRenderer();
  38888. };
  38889. // colors shifting and distortion
  38890. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  38891. var _this = this;
  38892. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  38893. [], // samplers
  38894. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  38895. this._chromaticAberrationPostProcess.onApply = function (effect) {
  38896. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  38897. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  38898. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  38899. };
  38900. };
  38901. // highlights enhancing
  38902. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  38903. var _this = this;
  38904. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  38905. [], // samplers
  38906. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  38907. this._highlightsPostProcess.onApply = function (effect) {
  38908. effect.setFloat('gain', _this._highlightsGain);
  38909. effect.setFloat('threshold', _this._highlightsThreshold);
  38910. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  38911. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  38912. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  38913. };
  38914. };
  38915. // colors shifting and distortion
  38916. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  38917. var _this = this;
  38918. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  38919. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  38920. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  38921. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  38922. this._depthOfFieldPostProcess.onApply = function (effect) {
  38923. effect.setTexture("depthSampler", _this._depthTexture);
  38924. effect.setTexture("grainSampler", _this._grainTexture);
  38925. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  38926. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  38927. effect.setFloat('grain_amount', _this._grainAmount);
  38928. effect.setBool('blur_noise', _this._blurNoise);
  38929. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  38930. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  38931. effect.setFloat('distortion', _this._distortion);
  38932. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  38933. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  38934. effect.setFloat('aperture', _this._dofAperture);
  38935. effect.setFloat('darken', _this._dofDarken);
  38936. effect.setFloat('edge_blur', _this._edgeBlur);
  38937. effect.setBool('highlights', (_this._highlightsGain !== -1));
  38938. effect.setFloat('near', _this._scene.activeCamera.minZ);
  38939. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  38940. };
  38941. };
  38942. // creates a black and white random noise texture, 512x512
  38943. LensRenderingPipeline.prototype._createGrainTexture = function () {
  38944. var size = 512;
  38945. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38946. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  38947. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  38948. var context = this._grainTexture.getContext();
  38949. var rand = function (min, max) {
  38950. return Math.random() * (max - min) + min;
  38951. };
  38952. var value;
  38953. for (var x = 0; x < size; x++) {
  38954. for (var y = 0; y < size; y++) {
  38955. value = Math.floor(rand(0.42, 0.58) * 255);
  38956. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  38957. context.fillRect(x, y, 1, 1);
  38958. }
  38959. }
  38960. this._grainTexture.update(false);
  38961. };
  38962. return LensRenderingPipeline;
  38963. })(BABYLON.PostProcessRenderPipeline);
  38964. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  38965. })(BABYLON || (BABYLON = {}));
  38966. //
  38967. // This post-process allows the modification of rendered colors by using
  38968. // a 'look-up table' (LUT). This effect is also called Color Grading.
  38969. //
  38970. // The object needs to be provided an url to a texture containing the color
  38971. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  38972. // Use an image editing software to tweak the LUT to match your needs.
  38973. //
  38974. // For an example of a color LUT, see here:
  38975. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  38976. // For explanations on color grading, see here:
  38977. // http://udn.epicgames.com/Three/ColorGrading.html
  38978. //
  38979. var BABYLON;
  38980. (function (BABYLON) {
  38981. var ColorCorrectionPostProcess = (function (_super) {
  38982. __extends(ColorCorrectionPostProcess, _super);
  38983. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  38984. var _this = this;
  38985. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  38986. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  38987. this._colorTableTexture.anisotropicFilteringLevel = 1;
  38988. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38989. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38990. this.onApply = function (effect) {
  38991. effect.setTexture("colorTable", _this._colorTableTexture);
  38992. };
  38993. }
  38994. return ColorCorrectionPostProcess;
  38995. })(BABYLON.PostProcess);
  38996. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  38997. })(BABYLON || (BABYLON = {}));
  38998. var BABYLON;
  38999. (function (BABYLON) {
  39000. var AnaglyphFreeCamera = (function (_super) {
  39001. __extends(AnaglyphFreeCamera, _super);
  39002. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  39003. _super.call(this, name, position, scene);
  39004. this.interaxialDistance = interaxialDistance;
  39005. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39006. }
  39007. AnaglyphFreeCamera.prototype.getTypeName = function () {
  39008. return "AnaglyphFreeCamera";
  39009. };
  39010. return AnaglyphFreeCamera;
  39011. })(BABYLON.FreeCamera);
  39012. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  39013. var AnaglyphArcRotateCamera = (function (_super) {
  39014. __extends(AnaglyphArcRotateCamera, _super);
  39015. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  39016. _super.call(this, name, alpha, beta, radius, target, scene);
  39017. this.interaxialDistance = interaxialDistance;
  39018. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39019. }
  39020. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  39021. return "AnaglyphArcRotateCamera";
  39022. };
  39023. return AnaglyphArcRotateCamera;
  39024. })(BABYLON.ArcRotateCamera);
  39025. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  39026. var AnaglyphGamepadCamera = (function (_super) {
  39027. __extends(AnaglyphGamepadCamera, _super);
  39028. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  39029. _super.call(this, name, position, scene);
  39030. this.interaxialDistance = interaxialDistance;
  39031. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39032. }
  39033. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  39034. return "AnaglyphGamepadCamera";
  39035. };
  39036. return AnaglyphGamepadCamera;
  39037. })(BABYLON.GamepadCamera);
  39038. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  39039. var AnaglyphUniversalCamera = (function (_super) {
  39040. __extends(AnaglyphUniversalCamera, _super);
  39041. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  39042. _super.call(this, name, position, scene);
  39043. this.interaxialDistance = interaxialDistance;
  39044. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39045. }
  39046. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  39047. return "AnaglyphUniversalCamera";
  39048. };
  39049. return AnaglyphUniversalCamera;
  39050. })(BABYLON.UniversalCamera);
  39051. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  39052. var StereoscopicFreeCamera = (function (_super) {
  39053. __extends(StereoscopicFreeCamera, _super);
  39054. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39055. _super.call(this, name, position, scene);
  39056. this.interaxialDistance = interaxialDistance;
  39057. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39058. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39059. }
  39060. StereoscopicFreeCamera.prototype.getTypeName = function () {
  39061. return "StereoscopicFreeCamera";
  39062. };
  39063. return StereoscopicFreeCamera;
  39064. })(BABYLON.FreeCamera);
  39065. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  39066. var StereoscopicArcRotateCamera = (function (_super) {
  39067. __extends(StereoscopicArcRotateCamera, _super);
  39068. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  39069. _super.call(this, name, alpha, beta, radius, target, scene);
  39070. this.interaxialDistance = interaxialDistance;
  39071. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39072. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39073. }
  39074. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  39075. return "StereoscopicArcRotateCamera";
  39076. };
  39077. return StereoscopicArcRotateCamera;
  39078. })(BABYLON.ArcRotateCamera);
  39079. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  39080. var StereoscopicGamepadCamera = (function (_super) {
  39081. __extends(StereoscopicGamepadCamera, _super);
  39082. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39083. _super.call(this, name, position, scene);
  39084. this.interaxialDistance = interaxialDistance;
  39085. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39086. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39087. }
  39088. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  39089. return "StereoscopicGamepadCamera";
  39090. };
  39091. return StereoscopicGamepadCamera;
  39092. })(BABYLON.GamepadCamera);
  39093. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  39094. var StereoscopicUniversalCamera = (function (_super) {
  39095. __extends(StereoscopicUniversalCamera, _super);
  39096. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39097. _super.call(this, name, position, scene);
  39098. this.interaxialDistance = interaxialDistance;
  39099. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39100. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39101. }
  39102. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  39103. return "StereoscopicUniversalCamera";
  39104. };
  39105. return StereoscopicUniversalCamera;
  39106. })(BABYLON.UniversalCamera);
  39107. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  39108. })(BABYLON || (BABYLON = {}));
  39109. var BABYLON;
  39110. (function (BABYLON) {
  39111. var HDRRenderingPipeline = (function (_super) {
  39112. __extends(HDRRenderingPipeline, _super);
  39113. /**
  39114. * @constructor
  39115. * @param {string} name - The rendering pipeline name
  39116. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39117. * @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)
  39118. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  39119. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39120. */
  39121. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  39122. var _this = this;
  39123. if (originalPostProcess === void 0) { originalPostProcess = null; }
  39124. _super.call(this, scene.getEngine(), name);
  39125. /**
  39126. * Public members
  39127. */
  39128. // Gaussian Blur
  39129. /**
  39130. * Gaussian blur coefficient
  39131. * @type {number}
  39132. */
  39133. this.gaussCoeff = 0.3;
  39134. /**
  39135. * Gaussian blur mean
  39136. * @type {number}
  39137. */
  39138. this.gaussMean = 1.0;
  39139. /**
  39140. * Gaussian blur standard deviation
  39141. * @type {number}
  39142. */
  39143. this.gaussStandDev = 0.8;
  39144. /**
  39145. * Gaussian blur multiplier. Multiplies the blur effect
  39146. * @type {number}
  39147. */
  39148. this.gaussMultiplier = 4.0;
  39149. // HDR
  39150. /**
  39151. * Exposure, controls the overall intensity of the pipeline
  39152. * @type {number}
  39153. */
  39154. this.exposure = 1.0;
  39155. /**
  39156. * Minimum luminance that the post-process can output. Luminance is >= 0
  39157. * @type {number}
  39158. */
  39159. this.minimumLuminance = 1.0;
  39160. /**
  39161. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  39162. * @type {number}
  39163. */
  39164. this.maximumLuminance = 1e20;
  39165. /**
  39166. * Increase rate for luminance: eye adaptation speed to dark
  39167. * @type {number}
  39168. */
  39169. this.luminanceIncreaserate = 0.5;
  39170. /**
  39171. * Decrease rate for luminance: eye adaptation speed to bright
  39172. * @type {number}
  39173. */
  39174. this.luminanceDecreaseRate = 0.5;
  39175. // Bright pass
  39176. /**
  39177. * Minimum luminance needed to compute HDR
  39178. * @type {number}
  39179. */
  39180. this.brightThreshold = 0.8;
  39181. this._needUpdate = true;
  39182. this._scene = scene;
  39183. // Bright pass
  39184. this._createBrightPassPostProcess(scene, ratio);
  39185. // Down sample X4
  39186. this._createDownSampleX4PostProcess(scene, ratio);
  39187. // Create gaussian blur post-processes
  39188. this._createGaussianBlurPostProcess(scene, ratio);
  39189. // Texture adder
  39190. this._createTextureAdderPostProcess(scene, ratio);
  39191. // Luminance generator
  39192. this._createLuminanceGeneratorPostProcess(scene);
  39193. // HDR
  39194. this._createHDRPostProcess(scene, ratio);
  39195. // Pass postprocess
  39196. if (originalPostProcess === null) {
  39197. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39198. }
  39199. else {
  39200. this._originalPostProcess = originalPostProcess;
  39201. }
  39202. // Configure pipeline
  39203. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  39204. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  39205. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  39206. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  39207. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  39208. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  39209. var addDownSamplerPostProcess = function (id) {
  39210. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  39211. };
  39212. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  39213. addDownSamplerPostProcess(i);
  39214. }
  39215. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  39216. // Finish
  39217. scene.postProcessRenderPipelineManager.addPipeline(this);
  39218. if (cameras !== null) {
  39219. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  39220. }
  39221. this.update();
  39222. }
  39223. /**
  39224. * Tells the pipeline to update its post-processes
  39225. */
  39226. HDRRenderingPipeline.prototype.update = function () {
  39227. this._needUpdate = true;
  39228. };
  39229. /**
  39230. * Returns the current calculated luminance
  39231. */
  39232. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  39233. return this._hdrCurrentLuminance;
  39234. };
  39235. /**
  39236. * Returns the currently drawn luminance
  39237. */
  39238. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  39239. return this._hdrOutputLuminance;
  39240. };
  39241. /**
  39242. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  39243. */
  39244. HDRRenderingPipeline.prototype.dispose = function () {
  39245. this._originalPostProcess = undefined;
  39246. this._brightPassPostProcess = undefined;
  39247. this._downSampleX4PostProcess = undefined;
  39248. this._guassianBlurHPostProcess = undefined;
  39249. this._guassianBlurVPostProcess = undefined;
  39250. this._textureAdderPostProcess = undefined;
  39251. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  39252. this._downSamplePostProcesses[i] = undefined;
  39253. }
  39254. this._hdrPostProcess = undefined;
  39255. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  39256. };
  39257. /**
  39258. * Creates the HDR post-process and computes the luminance adaptation
  39259. */
  39260. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  39261. var _this = this;
  39262. var hdrLastLuminance = 0.0;
  39263. this._hdrOutputLuminance = -1.0;
  39264. this._hdrCurrentLuminance = 1.0;
  39265. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  39266. this._hdrPostProcess.onApply = function (effect) {
  39267. if (_this._hdrOutputLuminance < 0.0) {
  39268. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  39269. }
  39270. else {
  39271. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  39272. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  39273. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  39274. }
  39275. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  39276. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  39277. }
  39278. else {
  39279. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  39280. }
  39281. }
  39282. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  39283. hdrLastLuminance += scene.getEngine().getDeltaTime();
  39284. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  39285. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  39286. effect.setFloat("exposure", _this.exposure);
  39287. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  39288. _this._needUpdate = false;
  39289. };
  39290. };
  39291. /**
  39292. * Texture Adder post-process
  39293. */
  39294. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  39295. var _this = this;
  39296. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  39297. this._textureAdderPostProcess.onApply = function (effect) {
  39298. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  39299. };
  39300. };
  39301. /**
  39302. * Down sample X4 post-process
  39303. */
  39304. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  39305. var _this = this;
  39306. var downSampleX4Offsets = new Array(32);
  39307. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  39308. this._downSampleX4PostProcess.onApply = function (effect) {
  39309. if (_this._needUpdate) {
  39310. var id = 0;
  39311. for (var i = -2; i < 2; i++) {
  39312. for (var j = -2; j < 2; j++) {
  39313. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  39314. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  39315. id += 2;
  39316. }
  39317. }
  39318. }
  39319. effect.setArray2("dsOffsets", downSampleX4Offsets);
  39320. };
  39321. };
  39322. /**
  39323. * Bright pass post-process
  39324. */
  39325. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  39326. var _this = this;
  39327. var brightOffsets = new Array(8);
  39328. var brightPassCallback = function (effect) {
  39329. if (_this._needUpdate) {
  39330. var sU = (1.0 / _this._brightPassPostProcess.width);
  39331. var sV = (1.0 / _this._brightPassPostProcess.height);
  39332. brightOffsets[0] = -0.5 * sU;
  39333. brightOffsets[1] = 0.5 * sV;
  39334. brightOffsets[2] = 0.5 * sU;
  39335. brightOffsets[3] = 0.5 * sV;
  39336. brightOffsets[4] = -0.5 * sU;
  39337. brightOffsets[5] = -0.5 * sV;
  39338. brightOffsets[6] = 0.5 * sU;
  39339. brightOffsets[7] = -0.5 * sV;
  39340. }
  39341. effect.setArray2("dsOffsets", brightOffsets);
  39342. effect.setFloat("brightThreshold", _this.brightThreshold);
  39343. };
  39344. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  39345. this._brightPassPostProcess.onApply = brightPassCallback;
  39346. };
  39347. /**
  39348. * Luminance generator. Creates the luminance post-process and down sample post-processes
  39349. */
  39350. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  39351. var _this = this;
  39352. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  39353. var luminanceOffsets = new Array(8);
  39354. var downSampleOffsets = new Array(18);
  39355. var halfDestPixelSize;
  39356. this._downSamplePostProcesses = new Array(lumSteps);
  39357. // Utils for luminance
  39358. var luminanceUpdateSourceOffsets = function (width, height) {
  39359. var sU = (1.0 / width);
  39360. var sV = (1.0 / height);
  39361. luminanceOffsets[0] = -0.5 * sU;
  39362. luminanceOffsets[1] = 0.5 * sV;
  39363. luminanceOffsets[2] = 0.5 * sU;
  39364. luminanceOffsets[3] = 0.5 * sV;
  39365. luminanceOffsets[4] = -0.5 * sU;
  39366. luminanceOffsets[5] = -0.5 * sV;
  39367. luminanceOffsets[6] = 0.5 * sU;
  39368. luminanceOffsets[7] = -0.5 * sV;
  39369. };
  39370. var luminanceUpdateDestOffsets = function (width, height) {
  39371. var id = 0;
  39372. for (var x = -1; x < 2; x++) {
  39373. for (var y = -1; y < 2; y++) {
  39374. downSampleOffsets[id] = (x) / width;
  39375. downSampleOffsets[id + 1] = (y) / height;
  39376. id += 2;
  39377. }
  39378. }
  39379. };
  39380. // Luminance callback
  39381. var luminanceCallback = function (effect) {
  39382. if (_this._needUpdate) {
  39383. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  39384. }
  39385. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  39386. effect.setArray2("lumOffsets", luminanceOffsets);
  39387. };
  39388. // Down sample callbacks
  39389. var downSampleCallback = function (indice) {
  39390. var i = indice;
  39391. return function (effect) {
  39392. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  39393. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  39394. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  39395. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  39396. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  39397. effect.setArray2("dsOffsets", downSampleOffsets);
  39398. };
  39399. };
  39400. var downSampleAfterRenderCallback = function (effect) {
  39401. // Unpack result
  39402. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  39403. 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);
  39404. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  39405. };
  39406. // Create luminance post-process
  39407. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  39408. 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);
  39409. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  39410. // Create down sample post-processes
  39411. for (var i = lumSteps - 2; i >= 0; i--) {
  39412. var length = Math.pow(3, i);
  39413. ratio = { width: length, height: length };
  39414. var defines = "#define DOWN_SAMPLE\n";
  39415. if (i === 0) {
  39416. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  39417. }
  39418. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  39419. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  39420. if (i === 0) {
  39421. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  39422. }
  39423. }
  39424. };
  39425. /**
  39426. * Gaussian blur post-processes. Horizontal and Vertical
  39427. */
  39428. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  39429. var _this = this;
  39430. var blurOffsetsW = new Array(9);
  39431. var blurOffsetsH = new Array(9);
  39432. var blurWeights = new Array(9);
  39433. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  39434. // Utils for gaussian blur
  39435. var calculateBlurOffsets = function (height) {
  39436. var lastOutputDimensions = {
  39437. width: scene.getEngine().getRenderWidth(),
  39438. height: scene.getEngine().getRenderHeight()
  39439. };
  39440. for (var i = 0; i < 9; i++) {
  39441. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  39442. if (height) {
  39443. blurOffsetsH[i] = value;
  39444. }
  39445. else {
  39446. blurOffsetsW[i] = value;
  39447. }
  39448. }
  39449. };
  39450. var calculateWeights = function () {
  39451. var x = 0.0;
  39452. for (var i = 0; i < 9; i++) {
  39453. x = (i - 4.0) / 4.0;
  39454. 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));
  39455. }
  39456. };
  39457. // Callback
  39458. var gaussianBlurCallback = function (height) {
  39459. return function (effect) {
  39460. if (_this._needUpdate) {
  39461. calculateWeights();
  39462. calculateBlurOffsets(height);
  39463. }
  39464. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  39465. effect.setArray("blurWeights", blurWeights);
  39466. effect.setFloat("multiplier", _this.gaussMultiplier);
  39467. };
  39468. };
  39469. // Create horizontal gaussian blur post-processes
  39470. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  39471. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  39472. // Create vertical gaussian blur post-process
  39473. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  39474. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  39475. };
  39476. // Luminance generator
  39477. HDRRenderingPipeline.LUM_STEPS = 6;
  39478. return HDRRenderingPipeline;
  39479. })(BABYLON.PostProcessRenderPipeline);
  39480. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  39481. })(BABYLON || (BABYLON = {}));
  39482. var BABYLON;
  39483. (function (BABYLON) {
  39484. var FaceAdjacencies = (function () {
  39485. function FaceAdjacencies() {
  39486. this.edges = new Array();
  39487. this.edgesConnectedCount = 0;
  39488. }
  39489. return FaceAdjacencies;
  39490. })();
  39491. var EdgesRenderer = (function () {
  39492. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  39493. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  39494. if (epsilon === void 0) { epsilon = 0.95; }
  39495. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  39496. this.edgesWidthScalerForOrthographic = 1000.0;
  39497. this.edgesWidthScalerForPerspective = 50.0;
  39498. this._linesPositions = new Array();
  39499. this._linesNormals = new Array();
  39500. this._linesIndices = new Array();
  39501. this._buffers = new Array();
  39502. this._checkVerticesInsteadOfIndices = false;
  39503. this._source = source;
  39504. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  39505. this._epsilon = epsilon;
  39506. this._prepareRessources();
  39507. this._generateEdgesLines();
  39508. }
  39509. EdgesRenderer.prototype._prepareRessources = function () {
  39510. if (this._lineShader) {
  39511. return;
  39512. }
  39513. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  39514. attributes: ["position", "normal"],
  39515. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  39516. });
  39517. this._lineShader.disableDepthWrite = true;
  39518. this._lineShader.backFaceCulling = false;
  39519. };
  39520. EdgesRenderer.prototype.dispose = function () {
  39521. this._vb0.dispose();
  39522. this._vb1.dispose();
  39523. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  39524. this._lineShader.dispose();
  39525. };
  39526. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  39527. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  39528. return 0;
  39529. }
  39530. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  39531. return 1;
  39532. }
  39533. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  39534. return 2;
  39535. }
  39536. return -1;
  39537. };
  39538. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  39539. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  39540. return 0;
  39541. }
  39542. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  39543. return 1;
  39544. }
  39545. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  39546. return 2;
  39547. }
  39548. return -1;
  39549. };
  39550. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  39551. var needToCreateLine;
  39552. if (edge === undefined) {
  39553. needToCreateLine = true;
  39554. }
  39555. else {
  39556. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  39557. needToCreateLine = dotProduct < this._epsilon;
  39558. }
  39559. if (needToCreateLine) {
  39560. var offset = this._linesPositions.length / 3;
  39561. var normal = p0.subtract(p1);
  39562. normal.normalize();
  39563. // Positions
  39564. this._linesPositions.push(p0.x);
  39565. this._linesPositions.push(p0.y);
  39566. this._linesPositions.push(p0.z);
  39567. this._linesPositions.push(p0.x);
  39568. this._linesPositions.push(p0.y);
  39569. this._linesPositions.push(p0.z);
  39570. this._linesPositions.push(p1.x);
  39571. this._linesPositions.push(p1.y);
  39572. this._linesPositions.push(p1.z);
  39573. this._linesPositions.push(p1.x);
  39574. this._linesPositions.push(p1.y);
  39575. this._linesPositions.push(p1.z);
  39576. // Normals
  39577. this._linesNormals.push(p1.x);
  39578. this._linesNormals.push(p1.y);
  39579. this._linesNormals.push(p1.z);
  39580. this._linesNormals.push(-1);
  39581. this._linesNormals.push(p1.x);
  39582. this._linesNormals.push(p1.y);
  39583. this._linesNormals.push(p1.z);
  39584. this._linesNormals.push(1);
  39585. this._linesNormals.push(p0.x);
  39586. this._linesNormals.push(p0.y);
  39587. this._linesNormals.push(p0.z);
  39588. this._linesNormals.push(-1);
  39589. this._linesNormals.push(p0.x);
  39590. this._linesNormals.push(p0.y);
  39591. this._linesNormals.push(p0.z);
  39592. this._linesNormals.push(1);
  39593. // Indices
  39594. this._linesIndices.push(offset);
  39595. this._linesIndices.push(offset + 1);
  39596. this._linesIndices.push(offset + 2);
  39597. this._linesIndices.push(offset);
  39598. this._linesIndices.push(offset + 2);
  39599. this._linesIndices.push(offset + 3);
  39600. }
  39601. };
  39602. EdgesRenderer.prototype._generateEdgesLines = function () {
  39603. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39604. var indices = this._source.getIndices();
  39605. // First let's find adjacencies
  39606. var adjacencies = new Array();
  39607. var faceNormals = new Array();
  39608. var index;
  39609. var faceAdjacencies;
  39610. // Prepare faces
  39611. for (index = 0; index < indices.length; index += 3) {
  39612. faceAdjacencies = new FaceAdjacencies();
  39613. var p0Index = indices[index];
  39614. var p1Index = indices[index + 1];
  39615. var p2Index = indices[index + 2];
  39616. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  39617. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  39618. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  39619. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  39620. faceNormal.normalize();
  39621. faceNormals.push(faceNormal);
  39622. adjacencies.push(faceAdjacencies);
  39623. }
  39624. // Scan
  39625. for (index = 0; index < adjacencies.length; index++) {
  39626. faceAdjacencies = adjacencies[index];
  39627. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  39628. var otherFaceAdjacencies = adjacencies[otherIndex];
  39629. if (faceAdjacencies.edgesConnectedCount === 3) {
  39630. break;
  39631. }
  39632. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  39633. continue;
  39634. }
  39635. var otherP0 = indices[otherIndex * 3];
  39636. var otherP1 = indices[otherIndex * 3 + 1];
  39637. var otherP2 = indices[otherIndex * 3 + 2];
  39638. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  39639. var otherEdgeIndex;
  39640. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  39641. continue;
  39642. }
  39643. switch (edgeIndex) {
  39644. case 0:
  39645. if (this._checkVerticesInsteadOfIndices) {
  39646. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  39647. }
  39648. else {
  39649. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  39650. }
  39651. break;
  39652. case 1:
  39653. if (this._checkVerticesInsteadOfIndices) {
  39654. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  39655. }
  39656. else {
  39657. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  39658. }
  39659. break;
  39660. case 2:
  39661. if (this._checkVerticesInsteadOfIndices) {
  39662. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  39663. }
  39664. else {
  39665. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  39666. }
  39667. break;
  39668. }
  39669. if (otherEdgeIndex === -1) {
  39670. continue;
  39671. }
  39672. faceAdjacencies.edges[edgeIndex] = otherIndex;
  39673. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  39674. faceAdjacencies.edgesConnectedCount++;
  39675. otherFaceAdjacencies.edgesConnectedCount++;
  39676. if (faceAdjacencies.edgesConnectedCount === 3) {
  39677. break;
  39678. }
  39679. }
  39680. }
  39681. }
  39682. // Create lines
  39683. for (index = 0; index < adjacencies.length; index++) {
  39684. // 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
  39685. var current = adjacencies[index];
  39686. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  39687. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  39688. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  39689. }
  39690. // Merge into a single mesh
  39691. var engine = this._source.getScene().getEngine();
  39692. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  39693. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  39694. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  39695. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  39696. this._ib = engine.createIndexBuffer(this._linesIndices);
  39697. this._indicesCount = this._linesIndices.length;
  39698. };
  39699. EdgesRenderer.prototype.render = function () {
  39700. if (!this._lineShader.isReady()) {
  39701. return;
  39702. }
  39703. var scene = this._source.getScene();
  39704. var engine = scene.getEngine();
  39705. this._lineShader._preBind();
  39706. // VBOs
  39707. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  39708. scene.resetCachedMaterial();
  39709. this._lineShader.setColor4("color", this._source.edgesColor);
  39710. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  39711. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  39712. }
  39713. else {
  39714. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  39715. }
  39716. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  39717. this._lineShader.bind(this._source.getWorldMatrix());
  39718. // Draw order
  39719. engine.draw(true, 0, this._indicesCount);
  39720. this._lineShader.unbind();
  39721. engine.setDepthWrite(true);
  39722. };
  39723. return EdgesRenderer;
  39724. })();
  39725. BABYLON.EdgesRenderer = EdgesRenderer;
  39726. })(BABYLON || (BABYLON = {}));
  39727. var BABYLON;
  39728. (function (BABYLON) {
  39729. (function (TonemappingOperator) {
  39730. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  39731. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  39732. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  39733. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  39734. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  39735. var TonemappingOperator = BABYLON.TonemappingOperator;
  39736. ;
  39737. var TonemapPostProcess = (function (_super) {
  39738. __extends(TonemapPostProcess, _super);
  39739. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  39740. var _this = this;
  39741. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39742. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  39743. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  39744. this._operator = _operator;
  39745. this.exposureAdjustment = exposureAdjustment;
  39746. var defines = "#define ";
  39747. if (this._operator === TonemappingOperator.Hable)
  39748. defines += "HABLE_TONEMAPPING";
  39749. else if (this._operator === TonemappingOperator.Reinhard)
  39750. defines += "REINHARD_TONEMAPPING";
  39751. else if (this._operator === TonemappingOperator.HejiDawson)
  39752. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  39753. else if (this._operator === TonemappingOperator.Photographic)
  39754. defines += "PHOTOGRAPHIC_TONEMAPPING";
  39755. //sadly a second call to create the effect.
  39756. this.updateEffect(defines);
  39757. this.onApply = function (effect) {
  39758. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  39759. };
  39760. }
  39761. return TonemapPostProcess;
  39762. })(BABYLON.PostProcess);
  39763. BABYLON.TonemapPostProcess = TonemapPostProcess;
  39764. })(BABYLON || (BABYLON = {}));
  39765. var BABYLON;
  39766. (function (BABYLON) {
  39767. var ReflectionProbe = (function () {
  39768. function ReflectionProbe(name, size, scene, generateMipMaps) {
  39769. var _this = this;
  39770. if (generateMipMaps === void 0) { generateMipMaps = true; }
  39771. this.name = name;
  39772. this._viewMatrix = BABYLON.Matrix.Identity();
  39773. this._target = BABYLON.Vector3.Zero();
  39774. this._add = BABYLON.Vector3.Zero();
  39775. this.position = BABYLON.Vector3.Zero();
  39776. this._scene = scene;
  39777. this._scene.reflectionProbes.push(this);
  39778. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  39779. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  39780. switch (faceIndex) {
  39781. case 0:
  39782. _this._add.copyFromFloats(1, 0, 0);
  39783. break;
  39784. case 1:
  39785. _this._add.copyFromFloats(-1, 0, 0);
  39786. break;
  39787. case 2:
  39788. _this._add.copyFromFloats(0, -1, 0);
  39789. break;
  39790. case 3:
  39791. _this._add.copyFromFloats(0, 1, 0);
  39792. break;
  39793. case 4:
  39794. _this._add.copyFromFloats(0, 0, 1);
  39795. break;
  39796. case 5:
  39797. _this._add.copyFromFloats(0, 0, -1);
  39798. break;
  39799. }
  39800. if (_this._attachedMesh) {
  39801. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  39802. }
  39803. _this.position.addToRef(_this._add, _this._target);
  39804. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  39805. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  39806. };
  39807. this._renderTargetTexture.onAfterUnbind = function () {
  39808. scene.updateTransformMatrix(true);
  39809. };
  39810. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  39811. }
  39812. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  39813. get: function () {
  39814. return this._renderTargetTexture.refreshRate;
  39815. },
  39816. set: function (value) {
  39817. this._renderTargetTexture.refreshRate = value;
  39818. },
  39819. enumerable: true,
  39820. configurable: true
  39821. });
  39822. ReflectionProbe.prototype.getScene = function () {
  39823. return this._scene;
  39824. };
  39825. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  39826. get: function () {
  39827. return this._renderTargetTexture;
  39828. },
  39829. enumerable: true,
  39830. configurable: true
  39831. });
  39832. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  39833. get: function () {
  39834. return this._renderTargetTexture.renderList;
  39835. },
  39836. enumerable: true,
  39837. configurable: true
  39838. });
  39839. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  39840. this._attachedMesh = mesh;
  39841. };
  39842. ReflectionProbe.prototype.dispose = function () {
  39843. var index = this._scene.reflectionProbes.indexOf(this);
  39844. if (index !== -1) {
  39845. // Remove from the scene if found
  39846. this._scene.reflectionProbes.splice(index, 1);
  39847. }
  39848. if (this._renderTargetTexture) {
  39849. this._renderTargetTexture.dispose();
  39850. this._renderTargetTexture = null;
  39851. }
  39852. };
  39853. return ReflectionProbe;
  39854. })();
  39855. BABYLON.ReflectionProbe = ReflectionProbe;
  39856. })(BABYLON || (BABYLON = {}));
  39857. var BABYLON;
  39858. (function (BABYLON) {
  39859. var SolidParticle = (function () {
  39860. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  39861. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  39862. this.position = BABYLON.Vector3.Zero(); // position
  39863. this.rotation = BABYLON.Vector3.Zero(); // rotation
  39864. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  39865. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  39866. this.velocity = BABYLON.Vector3.Zero(); // velocity
  39867. this.alive = true; // alive
  39868. this.idx = particleIndex;
  39869. this._pos = positionIndex;
  39870. this._model = model;
  39871. this.shapeId = shapeId;
  39872. this.idxInShape = idxInShape;
  39873. }
  39874. return SolidParticle;
  39875. })();
  39876. BABYLON.SolidParticle = SolidParticle;
  39877. var ModelShape = (function () {
  39878. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  39879. this.shapeID = id;
  39880. this._shape = shape;
  39881. this._shapeUV = shapeUV;
  39882. this._positionFunction = posFunction;
  39883. this._vertexFunction = vtxFunction;
  39884. }
  39885. return ModelShape;
  39886. })();
  39887. BABYLON.ModelShape = ModelShape;
  39888. })(BABYLON || (BABYLON = {}));
  39889. var BABYLON;
  39890. (function (BABYLON) {
  39891. /**
  39892. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  39893. */
  39894. var SolidParticleSystem = (function () {
  39895. /**
  39896. * Creates a SPS (Solid Particle System) object.
  39897. * @param name the SPS name, this will be the underlying mesh name
  39898. * @param scene the scene in which the SPS is added
  39899. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  39900. */
  39901. function SolidParticleSystem(name, scene, options) {
  39902. // public members
  39903. /**
  39904. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  39905. * Example : var p = SPS.particles[i];
  39906. */
  39907. this.particles = new Array();
  39908. /**
  39909. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  39910. */
  39911. this.nbParticles = 0;
  39912. /**
  39913. * If the particles must ever face the camera (default false). Useful for planar particles.
  39914. */
  39915. this.billboard = false;
  39916. /**
  39917. * This a counter ofr your own usage. It's not set by any SPS functions.
  39918. */
  39919. this.counter = 0;
  39920. /**
  39921. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  39922. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  39923. */
  39924. this.vars = {};
  39925. this._positions = new Array();
  39926. this._indices = new Array();
  39927. this._normals = new Array();
  39928. this._colors = new Array();
  39929. this._uvs = new Array();
  39930. this._index = 0; // indices index
  39931. this._updatable = true;
  39932. this._pickable = false;
  39933. this._isVisibilityBoxLocked = false;
  39934. this._alwaysVisible = false;
  39935. this._shapeCounter = 0;
  39936. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  39937. this._color = new BABYLON.Color4(0, 0, 0, 0);
  39938. this._computeParticleColor = true;
  39939. this._computeParticleTexture = true;
  39940. this._computeParticleRotation = true;
  39941. this._computeParticleVertex = false;
  39942. this._computeBoundingBox = false;
  39943. this._cam_axisZ = BABYLON.Vector3.Zero();
  39944. this._cam_axisY = BABYLON.Vector3.Zero();
  39945. this._cam_axisX = BABYLON.Vector3.Zero();
  39946. this._axisX = BABYLON.Axis.X;
  39947. this._axisY = BABYLON.Axis.Y;
  39948. this._axisZ = BABYLON.Axis.Z;
  39949. this._fakeCamPos = BABYLON.Vector3.Zero();
  39950. this._rotMatrix = new BABYLON.Matrix();
  39951. this._invertMatrix = new BABYLON.Matrix();
  39952. this._rotated = BABYLON.Vector3.Zero();
  39953. this._quaternion = new BABYLON.Quaternion();
  39954. this._vertex = BABYLON.Vector3.Zero();
  39955. this._normal = BABYLON.Vector3.Zero();
  39956. this._yaw = 0.0;
  39957. this._pitch = 0.0;
  39958. this._roll = 0.0;
  39959. this._halfroll = 0.0;
  39960. this._halfpitch = 0.0;
  39961. this._halfyaw = 0.0;
  39962. this._sinRoll = 0.0;
  39963. this._cosRoll = 0.0;
  39964. this._sinPitch = 0.0;
  39965. this._cosPitch = 0.0;
  39966. this._sinYaw = 0.0;
  39967. this._cosYaw = 0.0;
  39968. this._w = 0.0;
  39969. this._minimum = BABYLON.Tmp.Vector3[0];
  39970. this._maximum = BABYLON.Tmp.Vector3[1];
  39971. this.name = name;
  39972. this._scene = scene;
  39973. this._camera = scene.activeCamera;
  39974. this._pickable = options ? options.isPickable : false;
  39975. if (options && options.updatable) {
  39976. this._updatable = options.updatable;
  39977. }
  39978. else {
  39979. this._updatable = true;
  39980. }
  39981. if (this._pickable) {
  39982. this.pickedParticles = [];
  39983. }
  39984. }
  39985. /**
  39986. * Builds the SPS underlying mesh. Returns a standard Mesh.
  39987. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  39988. */
  39989. SolidParticleSystem.prototype.buildMesh = function () {
  39990. if (this.nbParticles === 0) {
  39991. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  39992. this.addShape(triangle, 1);
  39993. triangle.dispose();
  39994. }
  39995. this._positions32 = new Float32Array(this._positions);
  39996. this._uvs32 = new Float32Array(this._uvs);
  39997. this._colors32 = new Float32Array(this._colors);
  39998. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  39999. this._normals32 = new Float32Array(this._normals);
  40000. this._fixedNormal32 = new Float32Array(this._normals);
  40001. var vertexData = new BABYLON.VertexData();
  40002. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  40003. vertexData.indices = this._indices;
  40004. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  40005. if (this._uvs32) {
  40006. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  40007. ;
  40008. }
  40009. if (this._colors32) {
  40010. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  40011. }
  40012. var mesh = new BABYLON.Mesh(this.name, this._scene);
  40013. vertexData.applyToMesh(mesh, this._updatable);
  40014. this.mesh = mesh;
  40015. this.mesh.isPickable = this._pickable;
  40016. // free memory
  40017. this._positions = null;
  40018. this._normals = null;
  40019. this._uvs = null;
  40020. this._colors = null;
  40021. if (!this._updatable) {
  40022. this.particles.length = 0;
  40023. }
  40024. return mesh;
  40025. };
  40026. /**
  40027. * Digests the mesh and generates as many solid particles in the system as wanted.
  40028. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  40029. * Thus the particles generated from digest() have their property "positiion" yet set.
  40030. * @param mesh the mesh to be digested
  40031. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  40032. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  40033. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  40034. */
  40035. SolidParticleSystem.prototype.digest = function (mesh, options) {
  40036. var size = (options && options.facetNb) || 1;
  40037. var number = (options && options.number);
  40038. var delta = (options && options.delta) || 0;
  40039. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40040. var meshInd = mesh.getIndices();
  40041. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40042. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40043. var f = 0; // facet counter
  40044. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  40045. // compute size from number
  40046. if (number) {
  40047. number = (number > totalFacets) ? totalFacets : number;
  40048. size = Math.round(totalFacets / number);
  40049. delta = 0;
  40050. }
  40051. else {
  40052. size = (size > totalFacets) ? totalFacets : size;
  40053. }
  40054. var facetPos = []; // submesh positions
  40055. var facetInd = []; // submesh indices
  40056. var facetUV = []; // submesh UV
  40057. var facetCol = []; // submesh colors
  40058. var barycenter = BABYLON.Tmp.Vector3[0];
  40059. var rand;
  40060. var sizeO = size;
  40061. while (f < totalFacets) {
  40062. size = sizeO + Math.floor((1 + delta) * Math.random());
  40063. if (f > totalFacets - size) {
  40064. size = totalFacets - f;
  40065. }
  40066. // reset temp arrays
  40067. facetPos.length = 0;
  40068. facetInd.length = 0;
  40069. facetUV.length = 0;
  40070. facetCol.length = 0;
  40071. // iterate over "size" facets
  40072. var fi = 0;
  40073. for (var j = f * 3; j < (f + size) * 3; j++) {
  40074. facetInd.push(fi);
  40075. var i = meshInd[j];
  40076. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  40077. if (meshUV) {
  40078. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  40079. }
  40080. if (meshCol) {
  40081. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  40082. }
  40083. fi++;
  40084. }
  40085. // create a model shape for each single particle
  40086. var idx = this.nbParticles;
  40087. var shape = this._posToShape(facetPos);
  40088. var shapeUV = this._uvsToShapeUV(facetUV);
  40089. // compute the barycenter of the shape
  40090. var v;
  40091. for (v = 0; v < shape.length; v++) {
  40092. barycenter.addInPlace(shape[v]);
  40093. }
  40094. barycenter.scaleInPlace(1 / shape.length);
  40095. // shift the shape from its barycenter to the origin
  40096. for (v = 0; v < shape.length; v++) {
  40097. shape[v].subtractInPlace(barycenter);
  40098. }
  40099. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  40100. // add the particle in the SPS
  40101. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  40102. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  40103. // initialize the particle position
  40104. this.particles[this.nbParticles].position.addInPlace(barycenter);
  40105. this._index += shape.length;
  40106. idx++;
  40107. this.nbParticles++;
  40108. this._shapeCounter++;
  40109. f += size;
  40110. }
  40111. };
  40112. //reset copy
  40113. SolidParticleSystem.prototype._resetCopy = function () {
  40114. this._copy.position.x = 0;
  40115. this._copy.position.y = 0;
  40116. this._copy.position.z = 0;
  40117. this._copy.rotation.x = 0;
  40118. this._copy.rotation.y = 0;
  40119. this._copy.rotation.z = 0;
  40120. this._copy.quaternion = null;
  40121. this._copy.scale.x = 1;
  40122. this._copy.scale.y = 1;
  40123. this._copy.scale.z = 1;
  40124. this._copy.uvs.x = 0;
  40125. this._copy.uvs.y = 0;
  40126. this._copy.uvs.z = 1;
  40127. this._copy.uvs.w = 1;
  40128. this._copy.color = null;
  40129. };
  40130. // _meshBuilder : inserts the shape model in the global SPS mesh
  40131. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  40132. var i;
  40133. var u = 0;
  40134. var c = 0;
  40135. this._resetCopy();
  40136. if (options && options.positionFunction) {
  40137. options.positionFunction(this._copy, idx, idxInShape);
  40138. }
  40139. if (this._copy.quaternion) {
  40140. this._quaternion.x = this._copy.quaternion.x;
  40141. this._quaternion.y = this._copy.quaternion.y;
  40142. this._quaternion.z = this._copy.quaternion.z;
  40143. this._quaternion.w = this._copy.quaternion.w;
  40144. }
  40145. else {
  40146. this._yaw = this._copy.rotation.y;
  40147. this._pitch = this._copy.rotation.x;
  40148. this._roll = this._copy.rotation.z;
  40149. this._quaternionRotationYPR();
  40150. }
  40151. this._quaternionToRotationMatrix();
  40152. for (i = 0; i < shape.length; i++) {
  40153. this._vertex.x = shape[i].x;
  40154. this._vertex.y = shape[i].y;
  40155. this._vertex.z = shape[i].z;
  40156. if (options && options.vertexFunction) {
  40157. options.vertexFunction(this._copy, this._vertex, i);
  40158. }
  40159. this._vertex.x *= this._copy.scale.x;
  40160. this._vertex.y *= this._copy.scale.y;
  40161. this._vertex.z *= this._copy.scale.z;
  40162. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40163. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  40164. if (meshUV) {
  40165. 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);
  40166. u += 2;
  40167. }
  40168. if (this._copy.color) {
  40169. this._color = this._copy.color;
  40170. }
  40171. else if (meshCol && meshCol[c]) {
  40172. this._color.r = meshCol[c];
  40173. this._color.g = meshCol[c + 1];
  40174. this._color.b = meshCol[c + 2];
  40175. this._color.a = meshCol[c + 3];
  40176. }
  40177. else {
  40178. this._color.r = 1;
  40179. this._color.g = 1;
  40180. this._color.b = 1;
  40181. this._color.a = 1;
  40182. }
  40183. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  40184. c += 4;
  40185. }
  40186. for (i = 0; i < meshInd.length; i++) {
  40187. indices.push(p + meshInd[i]);
  40188. }
  40189. if (this._pickable) {
  40190. var nbfaces = meshInd.length / 3;
  40191. for (i = 0; i < nbfaces; i++) {
  40192. this.pickedParticles.push({ idx: idx, faceId: i });
  40193. }
  40194. }
  40195. };
  40196. // returns a shape array from positions array
  40197. SolidParticleSystem.prototype._posToShape = function (positions) {
  40198. var shape = [];
  40199. for (var i = 0; i < positions.length; i += 3) {
  40200. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  40201. }
  40202. return shape;
  40203. };
  40204. // returns a shapeUV array from a Vector4 uvs
  40205. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  40206. var shapeUV = [];
  40207. if (uvs) {
  40208. for (var i = 0; i < uvs.length; i++)
  40209. shapeUV.push(uvs[i]);
  40210. }
  40211. return shapeUV;
  40212. };
  40213. // adds a new particle object in the particles array
  40214. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  40215. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  40216. };
  40217. /**
  40218. * Adds some particles to the SPS from the model shape.
  40219. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  40220. * @param mesh any Mesh object that will be used as a model for the solid particles.
  40221. * @param nb the number of particles to be created from this model
  40222. * @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
  40223. */
  40224. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  40225. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40226. var meshInd = mesh.getIndices();
  40227. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40228. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40229. var shape = this._posToShape(meshPos);
  40230. var shapeUV = this._uvsToShapeUV(meshUV);
  40231. var posfunc = options ? options.positionFunction : null;
  40232. var vtxfunc = options ? options.vertexFunction : null;
  40233. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  40234. // particles
  40235. var idx = this.nbParticles;
  40236. for (var i = 0; i < nb; i++) {
  40237. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  40238. if (this._updatable) {
  40239. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  40240. }
  40241. this._index += shape.length;
  40242. idx++;
  40243. }
  40244. this.nbParticles += nb;
  40245. this._shapeCounter++;
  40246. return this._shapeCounter - 1;
  40247. };
  40248. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  40249. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  40250. this._resetCopy();
  40251. if (particle._model._positionFunction) {
  40252. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  40253. }
  40254. if (this._copy.quaternion) {
  40255. this._quaternion.x = this._copy.quaternion.x;
  40256. this._quaternion.y = this._copy.quaternion.y;
  40257. this._quaternion.z = this._copy.quaternion.z;
  40258. this._quaternion.w = this._copy.quaternion.w;
  40259. }
  40260. else {
  40261. this._yaw = this._copy.rotation.y;
  40262. this._pitch = this._copy.rotation.x;
  40263. this._roll = this._copy.rotation.z;
  40264. this._quaternionRotationYPR();
  40265. }
  40266. this._quaternionToRotationMatrix();
  40267. this._shape = particle._model._shape;
  40268. for (var pt = 0; pt < this._shape.length; pt++) {
  40269. this._vertex.x = this._shape[pt].x;
  40270. this._vertex.y = this._shape[pt].y;
  40271. this._vertex.z = this._shape[pt].z;
  40272. if (particle._model._vertexFunction) {
  40273. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  40274. }
  40275. this._vertex.x *= this._copy.scale.x;
  40276. this._vertex.y *= this._copy.scale.y;
  40277. this._vertex.z *= this._copy.scale.z;
  40278. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40279. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  40280. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  40281. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  40282. }
  40283. particle.position.x = 0;
  40284. particle.position.y = 0;
  40285. particle.position.z = 0;
  40286. particle.rotation.x = 0;
  40287. particle.rotation.y = 0;
  40288. particle.rotation.z = 0;
  40289. particle.quaternion = null;
  40290. particle.scale.x = 1;
  40291. particle.scale.y = 1;
  40292. particle.scale.z = 1;
  40293. };
  40294. /**
  40295. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  40296. */
  40297. SolidParticleSystem.prototype.rebuildMesh = function () {
  40298. for (var p = 0; p < this.particles.length; p++) {
  40299. this._rebuildParticle(this.particles[p]);
  40300. }
  40301. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40302. };
  40303. /**
  40304. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  40305. * This method calls updateParticle() for each particles of the SPS.
  40306. * For an animated SPS, it is usually called within the render loop.
  40307. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  40308. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  40309. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  40310. */
  40311. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  40312. if (start === void 0) { start = 0; }
  40313. if (end === void 0) { end = this.nbParticles - 1; }
  40314. if (update === void 0) { update = true; }
  40315. if (!this._updatable) {
  40316. return;
  40317. }
  40318. // custom beforeUpdate
  40319. this.beforeUpdateParticles(start, end, update);
  40320. this._cam_axisX.x = 1;
  40321. this._cam_axisX.y = 0;
  40322. this._cam_axisX.z = 0;
  40323. this._cam_axisY.x = 0;
  40324. this._cam_axisY.y = 1;
  40325. this._cam_axisY.z = 0;
  40326. this._cam_axisZ.x = 0;
  40327. this._cam_axisZ.y = 0;
  40328. this._cam_axisZ.z = 1;
  40329. // if the particles will always face the camera
  40330. if (this.billboard) {
  40331. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  40332. this._yaw = this.mesh.rotation.y;
  40333. this._pitch = this.mesh.rotation.x;
  40334. this._roll = this.mesh.rotation.z;
  40335. this._quaternionRotationYPR();
  40336. this._quaternionToRotationMatrix();
  40337. this._rotMatrix.invertToRef(this._invertMatrix);
  40338. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  40339. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  40340. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  40341. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  40342. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  40343. this._cam_axisY.normalize();
  40344. this._cam_axisX.normalize();
  40345. this._cam_axisZ.normalize();
  40346. }
  40347. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  40348. var idx = 0;
  40349. var index = 0;
  40350. var colidx = 0;
  40351. var colorIndex = 0;
  40352. var uvidx = 0;
  40353. var uvIndex = 0;
  40354. if (this._computeBoundingBox) {
  40355. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  40356. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  40357. }
  40358. // particle loop
  40359. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  40360. for (var p = start; p <= end; p++) {
  40361. this._particle = this.particles[p];
  40362. this._shape = this._particle._model._shape;
  40363. this._shapeUV = this._particle._model._shapeUV;
  40364. // call to custom user function to update the particle properties
  40365. this.updateParticle(this._particle);
  40366. // particle rotation matrix
  40367. if (this.billboard) {
  40368. this._particle.rotation.x = 0.0;
  40369. this._particle.rotation.y = 0.0;
  40370. }
  40371. if (this._computeParticleRotation) {
  40372. if (this._particle.quaternion) {
  40373. this._quaternion.x = this._particle.quaternion.x;
  40374. this._quaternion.y = this._particle.quaternion.y;
  40375. this._quaternion.z = this._particle.quaternion.z;
  40376. this._quaternion.w = this._particle.quaternion.w;
  40377. }
  40378. else {
  40379. this._yaw = this._particle.rotation.y;
  40380. this._pitch = this._particle.rotation.x;
  40381. this._roll = this._particle.rotation.z;
  40382. this._quaternionRotationYPR();
  40383. }
  40384. this._quaternionToRotationMatrix();
  40385. }
  40386. for (var pt = 0; pt < this._shape.length; pt++) {
  40387. idx = index + pt * 3;
  40388. colidx = colorIndex + pt * 4;
  40389. uvidx = uvIndex + pt * 2;
  40390. this._vertex.x = this._shape[pt].x;
  40391. this._vertex.y = this._shape[pt].y;
  40392. this._vertex.z = this._shape[pt].z;
  40393. if (this._computeParticleVertex) {
  40394. this.updateParticleVertex(this._particle, this._vertex, pt);
  40395. }
  40396. // positions
  40397. this._vertex.x *= this._particle.scale.x;
  40398. this._vertex.y *= this._particle.scale.y;
  40399. this._vertex.z *= this._particle.scale.z;
  40400. 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];
  40401. 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;
  40402. 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;
  40403. 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;
  40404. 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;
  40405. 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;
  40406. 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;
  40407. if (this._computeBoundingBox) {
  40408. if (this._positions32[idx] < this._minimum.x) {
  40409. this._minimum.x = this._positions32[idx];
  40410. }
  40411. if (this._positions32[idx] > this._maximum.x) {
  40412. this._maximum.x = this._positions32[idx];
  40413. }
  40414. if (this._positions32[idx + 1] < this._minimum.y) {
  40415. this._minimum.y = this._positions32[idx + 1];
  40416. }
  40417. if (this._positions32[idx + 1] > this._maximum.y) {
  40418. this._maximum.y = this._positions32[idx + 1];
  40419. }
  40420. if (this._positions32[idx + 2] < this._minimum.z) {
  40421. this._minimum.z = this._positions32[idx + 2];
  40422. }
  40423. if (this._positions32[idx + 2] > this._maximum.z) {
  40424. this._maximum.z = this._positions32[idx + 2];
  40425. }
  40426. }
  40427. // normals : if the particles can't be morphed then just rotate the normals
  40428. if (!this._computeParticleVertex && !this.billboard) {
  40429. this._normal.x = this._fixedNormal32[idx];
  40430. this._normal.y = this._fixedNormal32[idx + 1];
  40431. this._normal.z = this._fixedNormal32[idx + 2];
  40432. 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];
  40433. 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;
  40434. 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;
  40435. 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;
  40436. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  40437. 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;
  40438. 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;
  40439. }
  40440. if (this._computeParticleColor) {
  40441. this._colors32[colidx] = this._particle.color.r;
  40442. this._colors32[colidx + 1] = this._particle.color.g;
  40443. this._colors32[colidx + 2] = this._particle.color.b;
  40444. this._colors32[colidx + 3] = this._particle.color.a;
  40445. }
  40446. if (this._computeParticleTexture) {
  40447. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  40448. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  40449. }
  40450. }
  40451. index = idx + 3;
  40452. colorIndex = colidx + 4;
  40453. uvIndex = uvidx + 2;
  40454. }
  40455. if (update) {
  40456. if (this._computeParticleColor) {
  40457. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  40458. }
  40459. if (this._computeParticleTexture) {
  40460. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  40461. }
  40462. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40463. if (!this.mesh.areNormalsFrozen) {
  40464. if (this._computeParticleVertex || this.billboard) {
  40465. // recompute the normals only if the particles can be morphed, update then the normal reference array
  40466. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  40467. for (var i = 0; i < this._normals32.length; i++) {
  40468. this._fixedNormal32[i] = this._normals32[i];
  40469. }
  40470. }
  40471. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  40472. }
  40473. }
  40474. if (this._computeBoundingBox) {
  40475. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  40476. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  40477. }
  40478. this.afterUpdateParticles(start, end, update);
  40479. };
  40480. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  40481. this._halfroll = this._roll * 0.5;
  40482. this._halfpitch = this._pitch * 0.5;
  40483. this._halfyaw = this._yaw * 0.5;
  40484. this._sinRoll = Math.sin(this._halfroll);
  40485. this._cosRoll = Math.cos(this._halfroll);
  40486. this._sinPitch = Math.sin(this._halfpitch);
  40487. this._cosPitch = Math.cos(this._halfpitch);
  40488. this._sinYaw = Math.sin(this._halfyaw);
  40489. this._cosYaw = Math.cos(this._halfyaw);
  40490. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  40491. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  40492. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  40493. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  40494. };
  40495. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  40496. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  40497. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  40498. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  40499. this._rotMatrix.m[3] = 0;
  40500. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  40501. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  40502. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  40503. this._rotMatrix.m[7] = 0;
  40504. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  40505. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  40506. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  40507. this._rotMatrix.m[11] = 0;
  40508. this._rotMatrix.m[12] = 0;
  40509. this._rotMatrix.m[13] = 0;
  40510. this._rotMatrix.m[14] = 0;
  40511. this._rotMatrix.m[15] = 1.0;
  40512. };
  40513. /**
  40514. * Disposes the SPS
  40515. */
  40516. SolidParticleSystem.prototype.dispose = function () {
  40517. this.mesh.dispose();
  40518. this.vars = null;
  40519. // drop references to internal big arrays for the GC
  40520. this._positions = null;
  40521. this._indices = null;
  40522. this._normals = null;
  40523. this._uvs = null;
  40524. this._colors = null;
  40525. this._positions32 = null;
  40526. this._normals32 = null;
  40527. this._fixedNormal32 = null;
  40528. this._uvs32 = null;
  40529. this._colors32 = null;
  40530. this.pickedParticles = null;
  40531. };
  40532. /**
  40533. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  40534. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40535. */
  40536. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  40537. if (!this._isVisibilityBoxLocked) {
  40538. this.mesh.refreshBoundingInfo();
  40539. }
  40540. };
  40541. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  40542. * @param size the size (float) of the visibility box
  40543. * note : this doesn't lock the SPS mesh bounding box.
  40544. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40545. */
  40546. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  40547. var vis = size / 2;
  40548. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  40549. };
  40550. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  40551. // getter and setter
  40552. /**
  40553. * True if the SPS is set as always visible
  40554. */
  40555. get: function () {
  40556. return this._alwaysVisible;
  40557. },
  40558. /**
  40559. * Sets the SPS as always visible or not
  40560. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40561. */
  40562. set: function (val) {
  40563. this._alwaysVisible = val;
  40564. this.mesh.alwaysSelectAsActiveMesh = val;
  40565. },
  40566. enumerable: true,
  40567. configurable: true
  40568. });
  40569. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  40570. /**
  40571. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  40572. */
  40573. get: function () {
  40574. return this._isVisibilityBoxLocked;
  40575. },
  40576. /**
  40577. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  40578. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  40579. */
  40580. set: function (val) {
  40581. this._isVisibilityBoxLocked = val;
  40582. this.mesh.getBoundingInfo().isLocked = val;
  40583. },
  40584. enumerable: true,
  40585. configurable: true
  40586. });
  40587. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  40588. // getters
  40589. get: function () {
  40590. return this._computeParticleRotation;
  40591. },
  40592. // Optimizer setters
  40593. /**
  40594. * Tells to setParticles() to compute the particle rotations or not.
  40595. * Default value : true. The SPS is faster when it's set to false.
  40596. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  40597. */
  40598. set: function (val) {
  40599. this._computeParticleRotation = val;
  40600. },
  40601. enumerable: true,
  40602. configurable: true
  40603. });
  40604. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  40605. get: function () {
  40606. return this._computeParticleColor;
  40607. },
  40608. /**
  40609. * Tells to setParticles() to compute the particle colors or not.
  40610. * Default value : true. The SPS is faster when it's set to false.
  40611. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  40612. */
  40613. set: function (val) {
  40614. this._computeParticleColor = val;
  40615. },
  40616. enumerable: true,
  40617. configurable: true
  40618. });
  40619. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  40620. get: function () {
  40621. return this._computeParticleTexture;
  40622. },
  40623. /**
  40624. * Tells to setParticles() to compute the particle textures or not.
  40625. * Default value : true. The SPS is faster when it's set to false.
  40626. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  40627. */
  40628. set: function (val) {
  40629. this._computeParticleTexture = val;
  40630. },
  40631. enumerable: true,
  40632. configurable: true
  40633. });
  40634. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  40635. get: function () {
  40636. return this._computeParticleVertex;
  40637. },
  40638. /**
  40639. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  40640. * Default value : false. The SPS is faster when it's set to false.
  40641. * Note : the particle custom vertex positions aren't stored values.
  40642. */
  40643. set: function (val) {
  40644. this._computeParticleVertex = val;
  40645. },
  40646. enumerable: true,
  40647. configurable: true
  40648. });
  40649. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  40650. get: function () {
  40651. return this._computeBoundingBox;
  40652. },
  40653. /**
  40654. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  40655. */
  40656. set: function (val) {
  40657. this._computeBoundingBox = val;
  40658. },
  40659. enumerable: true,
  40660. configurable: true
  40661. });
  40662. // =======================================================================
  40663. // Particle behavior logic
  40664. // these following methods may be overwritten by the user to fit his needs
  40665. /**
  40666. * This function does nothing. It may be overwritten to set all the particles first values.
  40667. * The SPS doesn't call this function, you may have to call it by your own.
  40668. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  40669. */
  40670. SolidParticleSystem.prototype.initParticles = function () {
  40671. };
  40672. /**
  40673. * This function does nothing. It may be overwritten to recycle a particle.
  40674. * The SPS doesn't call this function, you may have to call it by your own.
  40675. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  40676. */
  40677. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  40678. return particle;
  40679. };
  40680. /**
  40681. * Updates a particle : this function should be overwritten by the user.
  40682. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  40683. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  40684. * ex : just set a particle position or velocity and recycle conditions
  40685. */
  40686. SolidParticleSystem.prototype.updateParticle = function (particle) {
  40687. return particle;
  40688. };
  40689. /**
  40690. * Updates a vertex of a particle : it can be overwritten by the user.
  40691. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  40692. * @param particle the current particle
  40693. * @param vertex the current index of the current particle
  40694. * @param pt the index of the current vertex in the particle shape
  40695. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  40696. * ex : just set a vertex particle position
  40697. */
  40698. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  40699. return vertex;
  40700. };
  40701. /**
  40702. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  40703. * This does nothing and may be overwritten by the user.
  40704. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40705. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40706. * @param update the boolean update value actually passed to setParticles()
  40707. */
  40708. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  40709. };
  40710. /**
  40711. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  40712. * This will be passed three parameters.
  40713. * This does nothing and may be overwritten by the user.
  40714. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40715. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40716. * @param update the boolean update value actually passed to setParticles()
  40717. */
  40718. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  40719. };
  40720. return SolidParticleSystem;
  40721. })();
  40722. BABYLON.SolidParticleSystem = SolidParticleSystem;
  40723. })(BABYLON || (BABYLON = {}));
  40724. var BABYLON;
  40725. (function (BABYLON) {
  40726. var Internals;
  40727. (function (Internals) {
  40728. var FileFaceOrientation = (function () {
  40729. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  40730. this.name = name;
  40731. this.worldAxisForNormal = worldAxisForNormal;
  40732. this.worldAxisForFileX = worldAxisForFileX;
  40733. this.worldAxisForFileY = worldAxisForFileY;
  40734. }
  40735. return FileFaceOrientation;
  40736. })();
  40737. ;
  40738. /**
  40739. * Helper class dealing with the extraction of spherical polynomial dataArray
  40740. * from a cube map.
  40741. */
  40742. var CubeMapToSphericalPolynomialTools = (function () {
  40743. function CubeMapToSphericalPolynomialTools() {
  40744. }
  40745. /**
  40746. * Converts a cubemap to the according Spherical Polynomial data.
  40747. * This extracts the first 3 orders only as they are the only one used in the lighting.
  40748. *
  40749. * @param cubeInfo The Cube map to extract the information from.
  40750. * @return The Spherical Polynomial data.
  40751. */
  40752. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  40753. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  40754. var totalSolidAngle = 0.0;
  40755. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  40756. var du = 2.0 / cubeInfo.size;
  40757. var dv = du;
  40758. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  40759. var minUV = du * 0.5 - 1.0;
  40760. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  40761. var fileFace = this.FileFaces[faceIndex];
  40762. var dataArray = cubeInfo[fileFace.name];
  40763. var v = minUV;
  40764. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  40765. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  40766. // Because SP is still linear, so summation is fine in that basis.
  40767. for (var y = 0; y < cubeInfo.size; y++) {
  40768. var u = minUV;
  40769. for (var x = 0; x < cubeInfo.size; x++) {
  40770. // World direction (not normalised)
  40771. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  40772. worldDirection.normalize();
  40773. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  40774. if (1) {
  40775. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  40776. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  40777. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  40778. var color = new BABYLON.Color3(r, g, b);
  40779. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40780. }
  40781. else {
  40782. if (faceIndex == 0) {
  40783. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40784. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40785. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40786. }
  40787. else if (faceIndex == 1) {
  40788. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40789. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40790. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40791. }
  40792. else if (faceIndex == 2) {
  40793. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40794. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40795. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40796. }
  40797. else if (faceIndex == 3) {
  40798. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40799. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40800. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40801. }
  40802. else if (faceIndex == 4) {
  40803. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40804. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40805. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40806. }
  40807. else if (faceIndex == 5) {
  40808. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40809. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40810. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40811. }
  40812. 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]);
  40813. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40814. }
  40815. totalSolidAngle += deltaSolidAngle;
  40816. u += du;
  40817. }
  40818. v += dv;
  40819. }
  40820. }
  40821. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  40822. var correction = correctSolidAngle / totalSolidAngle;
  40823. sphericalHarmonics.scale(correction);
  40824. // Additionally scale by pi -- audit needed
  40825. sphericalHarmonics.scale(1.0 / Math.PI);
  40826. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  40827. };
  40828. CubeMapToSphericalPolynomialTools.FileFaces = [
  40829. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  40830. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  40831. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  40832. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  40833. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  40834. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  40835. ];
  40836. return CubeMapToSphericalPolynomialTools;
  40837. })();
  40838. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  40839. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40840. })(BABYLON || (BABYLON = {}));
  40841. var BABYLON;
  40842. (function (BABYLON) {
  40843. var Internals;
  40844. (function (Internals) {
  40845. /**
  40846. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  40847. */
  40848. var PanoramaToCubeMapTools = (function () {
  40849. function PanoramaToCubeMapTools() {
  40850. }
  40851. /**
  40852. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  40853. *
  40854. * @param float32Array The source data.
  40855. * @param inputWidth The width of the input panorama.
  40856. * @param inputhHeight The height of the input panorama.
  40857. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  40858. * @return The cubemap data
  40859. */
  40860. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  40861. if (!float32Array) {
  40862. throw "ConvertPanoramaToCubemap: input cannot be null";
  40863. }
  40864. if (float32Array.length != inputWidth * inputHeight * 3) {
  40865. throw "ConvertPanoramaToCubemap: input size is wrong";
  40866. }
  40867. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  40868. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  40869. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  40870. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  40871. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  40872. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  40873. return {
  40874. front: textureFront,
  40875. back: textureBack,
  40876. left: textureLeft,
  40877. right: textureRight,
  40878. up: textureUp,
  40879. down: textureDown,
  40880. size: size
  40881. };
  40882. };
  40883. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  40884. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  40885. var textureArray = new Float32Array(buffer);
  40886. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  40887. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  40888. var dy = 1 / texSize;
  40889. var fy = 0;
  40890. for (var y = 0; y < texSize; y++) {
  40891. var xv1 = faceData[0];
  40892. var xv2 = faceData[2];
  40893. for (var x = 0; x < texSize; x++) {
  40894. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  40895. v.normalize();
  40896. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  40897. // 3 channels per pixels
  40898. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  40899. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  40900. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  40901. xv1 = xv1.add(rotDX1);
  40902. xv2 = xv2.add(rotDX2);
  40903. }
  40904. fy += dy;
  40905. }
  40906. return textureArray;
  40907. };
  40908. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  40909. var theta = Math.atan2(vDir.z, vDir.x);
  40910. var phi = Math.acos(vDir.y);
  40911. while (theta < -Math.PI)
  40912. theta += 2 * Math.PI;
  40913. while (theta > Math.PI)
  40914. theta -= 2 * Math.PI;
  40915. var dx = theta / Math.PI;
  40916. var dy = phi / Math.PI;
  40917. // recenter.
  40918. dx = dx * 0.5 + 0.5;
  40919. var px = Math.round(dx * inputWidth);
  40920. if (px < 0)
  40921. px = 0;
  40922. else if (px >= inputWidth)
  40923. px = inputWidth - 1;
  40924. var py = Math.round(dy * inputHeight);
  40925. if (py < 0)
  40926. py = 0;
  40927. else if (py >= inputHeight)
  40928. py = inputHeight - 1;
  40929. var inputY = (inputHeight - py - 1);
  40930. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  40931. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  40932. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  40933. return {
  40934. r: r,
  40935. g: g,
  40936. b: b
  40937. };
  40938. };
  40939. PanoramaToCubeMapTools.FACE_FRONT = [
  40940. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40941. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40942. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40943. new BABYLON.Vector3(1.0, 1.0, -1.0)
  40944. ];
  40945. PanoramaToCubeMapTools.FACE_BACK = [
  40946. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40947. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40948. new BABYLON.Vector3(1.0, 1.0, 1.0),
  40949. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  40950. ];
  40951. PanoramaToCubeMapTools.FACE_RIGHT = [
  40952. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40953. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40954. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40955. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40956. ];
  40957. PanoramaToCubeMapTools.FACE_LEFT = [
  40958. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40959. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40960. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40961. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  40962. ];
  40963. PanoramaToCubeMapTools.FACE_DOWN = [
  40964. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40965. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40966. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40967. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40968. ];
  40969. PanoramaToCubeMapTools.FACE_UP = [
  40970. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40971. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40972. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40973. new BABYLON.Vector3(1.0, -1.0, -1.0)
  40974. ];
  40975. return PanoramaToCubeMapTools;
  40976. })();
  40977. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  40978. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40979. })(BABYLON || (BABYLON = {}));
  40980. var BABYLON;
  40981. (function (BABYLON) {
  40982. var Internals;
  40983. (function (Internals) {
  40984. ;
  40985. /**
  40986. * This groups tools to convert HDR texture to native colors array.
  40987. */
  40988. var HDRTools = (function () {
  40989. function HDRTools() {
  40990. }
  40991. HDRTools.Ldexp = function (mantissa, exponent) {
  40992. if (exponent > 1023) {
  40993. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  40994. }
  40995. if (exponent < -1074) {
  40996. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  40997. }
  40998. return mantissa * Math.pow(2, exponent);
  40999. };
  41000. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  41001. if (exponent > 0) {
  41002. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  41003. float32array[index + 0] = red * exponent;
  41004. float32array[index + 1] = green * exponent;
  41005. float32array[index + 2] = blue * exponent;
  41006. }
  41007. else {
  41008. float32array[index + 0] = 0;
  41009. float32array[index + 1] = 0;
  41010. float32array[index + 2] = 0;
  41011. }
  41012. };
  41013. HDRTools.readStringLine = function (uint8array, startIndex) {
  41014. var line = "";
  41015. var character = "";
  41016. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  41017. character = String.fromCharCode(uint8array[i]);
  41018. if (character == "\n") {
  41019. break;
  41020. }
  41021. line += character;
  41022. }
  41023. return line;
  41024. };
  41025. /**
  41026. * Reads header information from an RGBE texture stored in a native array.
  41027. * More information on this format are available here:
  41028. * https://en.wikipedia.org/wiki/RGBE_image_format
  41029. *
  41030. * @param uint8array The binary file stored in native array.
  41031. * @return The header information.
  41032. */
  41033. HDRTools.RGBE_ReadHeader = function (uint8array) {
  41034. var height = 0;
  41035. var width = 0;
  41036. var line = this.readStringLine(uint8array, 0);
  41037. if (line[0] != '#' || line[1] != '?') {
  41038. throw "Bad HDR Format.";
  41039. }
  41040. var endOfHeader = false;
  41041. var findFormat = false;
  41042. var lineIndex = 0;
  41043. do {
  41044. lineIndex += (line.length + 1);
  41045. line = this.readStringLine(uint8array, lineIndex);
  41046. if (line == "FORMAT=32-bit_rle_rgbe") {
  41047. findFormat = true;
  41048. }
  41049. else if (line.length == 0) {
  41050. endOfHeader = true;
  41051. }
  41052. } while (!endOfHeader);
  41053. if (!findFormat) {
  41054. throw "HDR Bad header format, unsupported FORMAT";
  41055. }
  41056. lineIndex += (line.length + 1);
  41057. line = this.readStringLine(uint8array, lineIndex);
  41058. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  41059. var match = sizeRegexp.exec(line);
  41060. // TODO. Support +Y and -X if needed.
  41061. if (match.length < 3) {
  41062. throw "HDR Bad header format, no size";
  41063. }
  41064. width = parseInt(match[2]);
  41065. height = parseInt(match[1]);
  41066. if (width < 8 || width > 0x7fff) {
  41067. throw "HDR Bad header format, unsupported size";
  41068. }
  41069. lineIndex += (line.length + 1);
  41070. return {
  41071. height: height,
  41072. width: width,
  41073. dataPosition: lineIndex
  41074. };
  41075. };
  41076. /**
  41077. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  41078. * This RGBE texture needs to store the information as a panorama.
  41079. *
  41080. * More information on this format are available here:
  41081. * https://en.wikipedia.org/wiki/RGBE_image_format
  41082. *
  41083. * @param buffer The binary file stored in an array buffer.
  41084. * @param size The expected size of the extracted cubemap.
  41085. * @return The Cube Map information.
  41086. */
  41087. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  41088. var uint8array = new Uint8Array(buffer);
  41089. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  41090. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  41091. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  41092. return cubeMapData;
  41093. };
  41094. /**
  41095. * Returns the pixels data extracted from an RGBE texture.
  41096. * This pixels will be stored left to right up to down in the R G B order in one array.
  41097. *
  41098. * More information on this format are available here:
  41099. * https://en.wikipedia.org/wiki/RGBE_image_format
  41100. *
  41101. * @param uint8array The binary file stored in an array buffer.
  41102. * @param hdrInfo The header information of the file.
  41103. * @return The pixels data in RGB right to left up to down order.
  41104. */
  41105. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  41106. // Keep for multi format supports.
  41107. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  41108. };
  41109. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  41110. var num_scanlines = hdrInfo.height;
  41111. var scanline_width = hdrInfo.width;
  41112. var a, b, c, d, count;
  41113. var dataIndex = hdrInfo.dataPosition;
  41114. var index = 0, endIndex = 0, i = 0;
  41115. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  41116. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  41117. // 3 channels of 4 bytes per pixel in float.
  41118. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  41119. var resultArray = new Float32Array(resultBuffer);
  41120. // read in each successive scanline
  41121. while (num_scanlines > 0) {
  41122. a = uint8array[dataIndex++];
  41123. b = uint8array[dataIndex++];
  41124. c = uint8array[dataIndex++];
  41125. d = uint8array[dataIndex++];
  41126. if (a != 2 || b != 2 || (c & 0x80)) {
  41127. // this file is not run length encoded
  41128. throw "HDR Bad header format, not RLE";
  41129. }
  41130. if (((c << 8) | d) != scanline_width) {
  41131. throw "HDR Bad header format, wrong scan line width";
  41132. }
  41133. index = 0;
  41134. // read each of the four channels for the scanline into the buffer
  41135. for (i = 0; i < 4; i++) {
  41136. endIndex = (i + 1) * scanline_width;
  41137. while (index < endIndex) {
  41138. a = uint8array[dataIndex++];
  41139. b = uint8array[dataIndex++];
  41140. if (a > 128) {
  41141. // a run of the same value
  41142. count = a - 128;
  41143. if ((count == 0) || (count > endIndex - index)) {
  41144. throw "HDR Bad Format, bad scanline data (run)";
  41145. }
  41146. while (count-- > 0) {
  41147. scanLineArray[index++] = b;
  41148. }
  41149. }
  41150. else {
  41151. // a non-run
  41152. count = a;
  41153. if ((count == 0) || (count > endIndex - index)) {
  41154. throw "HDR Bad Format, bad scanline data (non-run)";
  41155. }
  41156. scanLineArray[index++] = b;
  41157. if (--count > 0) {
  41158. for (var j = 0; j < count; j++) {
  41159. scanLineArray[index++] = uint8array[dataIndex++];
  41160. }
  41161. }
  41162. }
  41163. }
  41164. }
  41165. // now convert data from buffer into floats
  41166. for (i = 0; i < scanline_width; i++) {
  41167. a = scanLineArray[i];
  41168. b = scanLineArray[i + scanline_width];
  41169. c = scanLineArray[i + 2 * scanline_width];
  41170. d = scanLineArray[i + 3 * scanline_width];
  41171. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  41172. }
  41173. num_scanlines--;
  41174. }
  41175. return resultArray;
  41176. };
  41177. return HDRTools;
  41178. })();
  41179. Internals.HDRTools = HDRTools;
  41180. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41181. })(BABYLON || (BABYLON = {}));
  41182. //_______________________________________________________________
  41183. // Extracted from CubeMapGen:
  41184. // https://code.google.com/archive/p/cubemapgen/
  41185. //
  41186. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  41187. //_______________________________________________________________
  41188. var BABYLON;
  41189. (function (BABYLON) {
  41190. var Internals;
  41191. (function (Internals) {
  41192. /**
  41193. * The bounding box information used during the conversion process.
  41194. */
  41195. var CMGBoundinBox = (function () {
  41196. function CMGBoundinBox() {
  41197. this.min = new BABYLON.Vector3(0, 0, 0);
  41198. this.max = new BABYLON.Vector3(0, 0, 0);
  41199. this.clear();
  41200. }
  41201. CMGBoundinBox.prototype.clear = function () {
  41202. this.min.x = CMGBoundinBox.MAX;
  41203. this.min.y = CMGBoundinBox.MAX;
  41204. this.min.z = CMGBoundinBox.MAX;
  41205. this.max.x = CMGBoundinBox.MIN;
  41206. this.max.y = CMGBoundinBox.MIN;
  41207. this.max.z = CMGBoundinBox.MIN;
  41208. };
  41209. CMGBoundinBox.prototype.augment = function (x, y, z) {
  41210. this.min.x = Math.min(this.min.x, x);
  41211. this.min.y = Math.min(this.min.y, y);
  41212. this.min.z = Math.min(this.min.z, z);
  41213. this.max.x = Math.max(this.max.x, x);
  41214. this.max.y = Math.max(this.max.y, y);
  41215. this.max.z = Math.max(this.max.z, z);
  41216. };
  41217. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  41218. this.min.x = Math.max(this.min.x, x);
  41219. this.min.y = Math.max(this.min.y, y);
  41220. this.min.z = Math.max(this.min.z, z);
  41221. };
  41222. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  41223. this.max.x = Math.min(this.max.x, x);
  41224. this.max.y = Math.min(this.max.y, y);
  41225. this.max.z = Math.min(this.max.z, z);
  41226. };
  41227. CMGBoundinBox.prototype.empty = function () {
  41228. if ((this.min.x > this.max.y) ||
  41229. (this.min.y > this.max.y) ||
  41230. (this.min.z > this.max.y)) {
  41231. return true;
  41232. }
  41233. else {
  41234. return false;
  41235. }
  41236. };
  41237. CMGBoundinBox.MAX = Number.MAX_VALUE;
  41238. CMGBoundinBox.MIN = Number.MIN_VALUE;
  41239. return CMGBoundinBox;
  41240. })();
  41241. /**
  41242. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  41243. * required by the glossinees of a material.
  41244. *
  41245. * This only supports the cosine drop power as well as Warp fixup generation method.
  41246. *
  41247. * This is using the process from CubeMapGen described here:
  41248. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  41249. */
  41250. var PMREMGenerator = (function () {
  41251. /**
  41252. * Constructor of the generator.
  41253. *
  41254. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  41255. * @param inputSize The size of the cubemap faces
  41256. * @param outputSize The size of the output cubemap faces
  41257. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  41258. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  41259. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  41260. * @param specularPower The max specular level of the desired cubemap
  41261. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  41262. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  41263. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  41264. */
  41265. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  41266. this.input = input;
  41267. this.inputSize = inputSize;
  41268. this.outputSize = outputSize;
  41269. this.maxNumMipLevels = maxNumMipLevels;
  41270. this.numChannels = numChannels;
  41271. this.isFloat = isFloat;
  41272. this.specularPower = specularPower;
  41273. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  41274. this.excludeBase = excludeBase;
  41275. this.fixup = fixup;
  41276. this._outputSurface = [];
  41277. this._numMipLevels = 0;
  41278. }
  41279. /**
  41280. * Launches the filter process and return the result.
  41281. *
  41282. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  41283. */
  41284. PMREMGenerator.prototype.filterCubeMap = function () {
  41285. // Init cubemap processor
  41286. this.init();
  41287. // Filters the cubemap
  41288. this.filterCubeMapMipChain();
  41289. // Returns the filtered mips.
  41290. return this._outputSurface;
  41291. };
  41292. PMREMGenerator.prototype.init = function () {
  41293. var i;
  41294. var j;
  41295. var mipLevelSize;
  41296. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  41297. if (this.maxNumMipLevels == 0) {
  41298. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  41299. }
  41300. //first miplevel size
  41301. mipLevelSize = this.outputSize;
  41302. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  41303. for (j = 0; j < this.maxNumMipLevels; j++) {
  41304. this._outputSurface.length++;
  41305. this._outputSurface[j] = [];
  41306. //Iterate over faces for output images
  41307. for (i = 0; i < 6; i++) {
  41308. this._outputSurface[j].length++;
  41309. // Initializes a new array for the output.
  41310. if (this.isFloat) {
  41311. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  41312. }
  41313. else {
  41314. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  41315. }
  41316. }
  41317. //next mip level is half size
  41318. mipLevelSize >>= 1;
  41319. this._numMipLevels++;
  41320. //terminate if mip chain becomes too small
  41321. if (mipLevelSize == 0) {
  41322. this.maxNumMipLevels = j;
  41323. return;
  41324. }
  41325. }
  41326. };
  41327. //--------------------------------------------------------------------------------------
  41328. //Cube map filtering and mip chain generation.
  41329. // the cube map filtereing is specified using a number of parameters:
  41330. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  41331. // indicates the region of the hemisphere to filter over for each tap.
  41332. //
  41333. // Note that the top mip level is also a filtered version of the original input images
  41334. // as well in order to create mip chains for diffuse environment illumination.
  41335. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  41336. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  41337. //
  41338. // Then the mip angle used to genreate the next level of the mip chain from the first level
  41339. // is a_InitialMipAngle
  41340. //
  41341. // The angle for the subsequent levels of the mip chain are specified by their parents
  41342. // filtering angle and a per-level scale and bias
  41343. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  41344. //
  41345. //--------------------------------------------------------------------------------------
  41346. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  41347. // First, take count of the lighting model to modify SpecularPower
  41348. // 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;
  41349. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  41350. //Cone angle start (for generating subsequent mip levels)
  41351. var currentSpecularPower = this.specularPower;
  41352. //Build filter lookup tables based on the source miplevel size
  41353. this.precomputeFilterLookupTables(this.inputSize);
  41354. // Note that we need to filter the first level before generating mipmap
  41355. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  41356. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  41357. // TODO : Write a function to copy and scale the base mipmap in output
  41358. // I am just lazy here and just put a high specular power value, and do some if.
  41359. if (this.excludeBase && (levelIndex == 0)) {
  41360. // 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).
  41361. currentSpecularPower = 100000.0;
  41362. }
  41363. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  41364. var srcCubeImage = this.input;
  41365. var dstCubeImage = this._outputSurface[levelIndex];
  41366. var dstSize = this.outputSize >> levelIndex;
  41367. // Compute required angle.
  41368. var angle = this.getBaseFilterAngle(currentSpecularPower);
  41369. // filter cube surfaces
  41370. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  41371. // fix seams
  41372. if (this.fixup) {
  41373. this.fixupCubeEdges(dstCubeImage, dstSize);
  41374. }
  41375. // Decrease the specular power to generate the mipmap chain
  41376. // TODO : Use another method for Exclude (see first comment at start of the function
  41377. if (this.excludeBase && (levelIndex == 0)) {
  41378. currentSpecularPower = this.specularPower;
  41379. }
  41380. currentSpecularPower *= this.cosinePowerDropPerMip;
  41381. }
  41382. };
  41383. //--------------------------------------------------------------------------------------
  41384. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  41385. // It allow to optimize the texel to access base on the specular power.
  41386. //--------------------------------------------------------------------------------------
  41387. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  41388. // We want to find the alpha such that:
  41389. // cos(alpha)^cosinePower = epsilon
  41390. // That's: acos(epsilon^(1/cosinePower))
  41391. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  41392. var angle = 180.0;
  41393. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  41394. angle *= 180.0 / Math.PI; // Convert to degree
  41395. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  41396. return angle;
  41397. };
  41398. //--------------------------------------------------------------------------------------
  41399. //Builds the following lookup tables prior to filtering:
  41400. // -normalizer cube map
  41401. // -tap weight lookup table
  41402. //
  41403. //--------------------------------------------------------------------------------------
  41404. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  41405. var srcTexelAngle;
  41406. var iCubeFace;
  41407. //clear pre-existing normalizer cube map
  41408. this._normCubeMap = [];
  41409. //Normalized vectors per cubeface and per-texel solid angle
  41410. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  41411. };
  41412. //--------------------------------------------------------------------------------------
  41413. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  41414. //
  41415. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  41416. //
  41417. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  41418. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  41419. // below
  41420. //--------------------------------------------------------------------------------------
  41421. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  41422. var iCubeFace;
  41423. var u;
  41424. var v;
  41425. //iterate over cube faces
  41426. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  41427. //First three channels for norm cube, and last channel for solid angle
  41428. this._normCubeMap.push(new Float32Array(size * size * 4));
  41429. //fast texture walk, build normalizer cube map
  41430. var facesData = this.input[iCubeFace];
  41431. for (v = 0; v < size; v++) {
  41432. for (u = 0; u < size; u++) {
  41433. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  41434. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  41435. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  41436. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  41437. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  41438. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  41439. }
  41440. }
  41441. }
  41442. };
  41443. //--------------------------------------------------------------------------------------
  41444. // Convert cubemap face texel coordinates and face idx to 3D vector
  41445. // note the U and V coords are integer coords and range from 0 to size-1
  41446. // this routine can be used to generate a normalizer cube map
  41447. //--------------------------------------------------------------------------------------
  41448. // SL BEGIN
  41449. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  41450. var nvcU;
  41451. var nvcV;
  41452. var tempVec;
  41453. // Change from original AMD code
  41454. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  41455. // + 0.5f is for texel center addressing
  41456. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  41457. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  41458. // warp fixup
  41459. if (fixup && size > 1) {
  41460. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  41461. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  41462. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  41463. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  41464. }
  41465. // Get current vector
  41466. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  41467. // U contribution
  41468. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  41469. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  41470. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  41471. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  41472. // V contribution and Sum
  41473. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  41474. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  41475. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  41476. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  41477. //add face axis
  41478. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  41479. PMREMGenerator._vectorTemp.x += faceAxis[0];
  41480. PMREMGenerator._vectorTemp.y += faceAxis[1];
  41481. PMREMGenerator._vectorTemp.z += faceAxis[2];
  41482. //normalize vector
  41483. PMREMGenerator._vectorTemp.normalize();
  41484. return PMREMGenerator._vectorTemp;
  41485. };
  41486. //--------------------------------------------------------------------------------------
  41487. // Convert 3D vector to cubemap face texel coordinates and face idx
  41488. // note the U and V coords are integer coords and range from 0 to size-1
  41489. // this routine can be used to generate a normalizer cube map
  41490. //
  41491. // returns face IDX and texel coords
  41492. //--------------------------------------------------------------------------------------
  41493. // SL BEGIN
  41494. /*
  41495. Mapping Texture Coordinates to Cube Map Faces
  41496. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  41497. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  41498. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  41499. map arrangement in Pixar's RenderMan package.
  41500. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  41501. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  41502. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  41503. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  41504. the major axis direction). The target column in the table below explains how the major axis direction
  41505. maps to the 2D image of a particular cube map target.
  41506. major axis
  41507. direction target sc tc ma
  41508. ---------- --------------------------------- --- --- ---
  41509. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  41510. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  41511. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  41512. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  41513. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  41514. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  41515. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  41516. an updated (s,t) is calculated as follows
  41517. s = ( sc/|ma| + 1 ) / 2
  41518. t = ( tc/|ma| + 1 ) / 2
  41519. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  41520. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  41521. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  41522. */
  41523. // Note this method return U and V in range from 0 to size-1
  41524. // SL END
  41525. // Store the information in vector3 for convenience (faceindex, u, v)
  41526. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  41527. var maxCoord;
  41528. var faceIdx;
  41529. //absolute value 3
  41530. var absX = Math.abs(x);
  41531. var absY = Math.abs(y);
  41532. var absZ = Math.abs(z);
  41533. if (absX >= absY && absX >= absZ) {
  41534. maxCoord = absX;
  41535. if (x >= 0) {
  41536. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  41537. }
  41538. else {
  41539. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  41540. }
  41541. }
  41542. else if (absY >= absX && absY >= absZ) {
  41543. maxCoord = absY;
  41544. if (y >= 0) {
  41545. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  41546. }
  41547. else {
  41548. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  41549. }
  41550. }
  41551. else {
  41552. maxCoord = absZ;
  41553. if (z >= 0) {
  41554. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  41555. }
  41556. else {
  41557. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  41558. }
  41559. }
  41560. //divide through by max coord so face vector lies on cube face
  41561. var scale = 1 / maxCoord;
  41562. x *= scale;
  41563. y *= scale;
  41564. z *= scale;
  41565. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  41566. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  41567. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  41568. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  41569. // Modify original AMD code to return value from 0 to Size - 1
  41570. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  41571. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  41572. PMREMGenerator._vectorTemp.x = faceIdx;
  41573. PMREMGenerator._vectorTemp.y = u;
  41574. PMREMGenerator._vectorTemp.z = v;
  41575. return PMREMGenerator._vectorTemp;
  41576. };
  41577. //--------------------------------------------------------------------------------------
  41578. //Original code from Ignacio CastaÒo
  41579. // This formula is from Manne ÷hrstrˆm's thesis.
  41580. // Take two coordiantes in the range [-1, 1] that define a portion of a
  41581. // cube face and return the area of the projection of that portion on the
  41582. // surface of the sphere.
  41583. //--------------------------------------------------------------------------------------
  41584. PMREMGenerator.prototype.areaElement = function (x, y) {
  41585. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  41586. };
  41587. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  41588. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  41589. // (+ 0.5f is for texel center addressing)
  41590. u = (2.0 * (u + 0.5) / size) - 1.0;
  41591. v = (2.0 * (v + 0.5) / size) - 1.0;
  41592. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  41593. var invResolution = 1.0 / size;
  41594. // U and V are the -1..1 texture coordinate on the current face.
  41595. // Get projected area for this texel
  41596. var x0 = u - invResolution;
  41597. var y0 = v - invResolution;
  41598. var x1 = u + invResolution;
  41599. var y1 = v + invResolution;
  41600. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  41601. return solidAngle;
  41602. };
  41603. //--------------------------------------------------------------------------------------
  41604. //The key to the speed of these filtering routines is to quickly define a per-face
  41605. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  41606. // Later these pixels are selectively processed based on their dot products to see if
  41607. // they reside within the filtering cone.
  41608. //
  41609. //This is done by computing the smallest per-texel angle to get a conservative estimate
  41610. // of the number of texels needed to be covered in width and height order to filter the
  41611. // region. the bounding box for the center taps face is defined first, and if the
  41612. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  41613. // defined next
  41614. //--------------------------------------------------------------------------------------
  41615. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  41616. // note that pixels within these regions may be rejected
  41617. // based on the anlge
  41618. var iCubeFace;
  41619. var u;
  41620. var v;
  41621. // bounding box per face to specify region to process
  41622. var filterExtents = [];
  41623. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  41624. filterExtents.push(new CMGBoundinBox());
  41625. }
  41626. // min angle a src texel can cover (in degrees)
  41627. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  41628. // angle about center tap to define filter cone
  41629. // filter angle is 1/2 the cone angle
  41630. var filterAngle = filterConeAngle / 2.0;
  41631. //ensure filter angle is larger than a texel
  41632. if (filterAngle < srcTexelAngle) {
  41633. filterAngle = srcTexelAngle;
  41634. }
  41635. //ensure filter cone is always smaller than the hemisphere
  41636. if (filterAngle > 90.0) {
  41637. filterAngle = 90.0;
  41638. }
  41639. // the maximum number of texels in 1D the filter cone angle will cover
  41640. // used to determine bounding box size for filter extents
  41641. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  41642. // ensure conservative region always covers at least one texel
  41643. if (filterSize < 1) {
  41644. filterSize = 1;
  41645. }
  41646. // dotProdThresh threshold based on cone angle to determine whether or not taps
  41647. // reside within the cone angle
  41648. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  41649. // process required faces
  41650. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  41651. //iterate over dst cube map face texel
  41652. for (v = 0; v < dstSize; v++) {
  41653. for (u = 0; u < dstSize; u++) {
  41654. //get center tap direction
  41655. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  41656. //clear old per-face filter extents
  41657. this.clearFilterExtents(filterExtents);
  41658. //define per-face filter extents
  41659. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  41660. //perform filtering of src faces using filter extents
  41661. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  41662. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  41663. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  41664. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  41665. }
  41666. }
  41667. }
  41668. };
  41669. //--------------------------------------------------------------------------------------
  41670. //Clear filter extents for the 6 cube map faces
  41671. //--------------------------------------------------------------------------------------
  41672. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  41673. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  41674. filterExtents[iCubeFaces].clear();
  41675. }
  41676. };
  41677. //--------------------------------------------------------------------------------------
  41678. //Define per-face bounding box filter extents
  41679. //
  41680. // These define conservative texel regions in each of the faces the filter can possibly
  41681. // process. When the pixels in the regions are actually processed, the dot product
  41682. // between the tap vector and the center tap vector is used to determine the weight of
  41683. // the tap and whether or not the tap is within the cone.
  41684. //
  41685. //--------------------------------------------------------------------------------------
  41686. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  41687. //neighboring face and bleed over amount, and width of BBOX for
  41688. // left, right, top, and bottom edges of this face
  41689. var bleedOverAmount = [0, 0, 0, 0];
  41690. var bleedOverBBoxMin = [0, 0, 0, 0];
  41691. var bleedOverBBoxMax = [0, 0, 0, 0];
  41692. var neighborFace;
  41693. var neighborEdge;
  41694. var oppositeFaceIdx;
  41695. //get face idx, and u, v info from center tap dir
  41696. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  41697. var faceIdx = result.x;
  41698. var u = result.y;
  41699. var v = result.z;
  41700. //define bbox size within face
  41701. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  41702. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  41703. filterExtents[faceIdx].clampMin(0, 0, 0);
  41704. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  41705. //u and v extent in face corresponding to center tap
  41706. var minU = filterExtents[faceIdx].min.x;
  41707. var minV = filterExtents[faceIdx].min.y;
  41708. var maxU = filterExtents[faceIdx].max.x;
  41709. var maxV = filterExtents[faceIdx].max.y;
  41710. //bleed over amounts for face across u=0 edge (left)
  41711. bleedOverAmount[0] = (bboxSize - u);
  41712. bleedOverBBoxMin[0] = minV;
  41713. bleedOverBBoxMax[0] = maxV;
  41714. //bleed over amounts for face across u=1 edge (right)
  41715. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  41716. bleedOverBBoxMin[1] = minV;
  41717. bleedOverBBoxMax[1] = maxV;
  41718. //bleed over to face across v=0 edge (up)
  41719. bleedOverAmount[2] = (bboxSize - v);
  41720. bleedOverBBoxMin[2] = minU;
  41721. bleedOverBBoxMax[2] = maxU;
  41722. //bleed over to face across v=1 edge (down)
  41723. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  41724. bleedOverBBoxMin[3] = minU;
  41725. bleedOverBBoxMax[3] = maxU;
  41726. //compute bleed over regions in neighboring faces
  41727. for (var i = 0; i < 4; i++) {
  41728. if (bleedOverAmount[i] > 0) {
  41729. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  41730. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  41731. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  41732. // be flipped: the cases are
  41733. // if a left edge mates with a left or bottom edge on the neighbor
  41734. // if a top edge mates with a top or right edge on the neighbor
  41735. // if a right edge mates with a right or top edge on the neighbor
  41736. // if a bottom edge mates with a bottom or left edge on the neighbor
  41737. //Seeing as the edges are enumerated as follows
  41738. // left =0
  41739. // right =1
  41740. // top =2
  41741. // bottom =3
  41742. //
  41743. // so if the edge enums are the same, or the sum of the enums == 3,
  41744. // the bbox needs to be flipped
  41745. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  41746. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  41747. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  41748. }
  41749. //The way the bounding box is extended onto the neighboring face
  41750. // depends on which edge of neighboring face abuts with this one
  41751. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  41752. case PMREMGenerator.CP_EDGE_LEFT:
  41753. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  41754. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  41755. break;
  41756. case PMREMGenerator.CP_EDGE_RIGHT:
  41757. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  41758. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  41759. break;
  41760. case PMREMGenerator.CP_EDGE_TOP:
  41761. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  41762. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  41763. break;
  41764. case PMREMGenerator.CP_EDGE_BOTTOM:
  41765. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  41766. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  41767. break;
  41768. }
  41769. //clamp filter extents in non-center tap faces to remain within surface
  41770. filterExtents[neighborFace].clampMin(0, 0, 0);
  41771. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  41772. }
  41773. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  41774. // from the center tap face, then process the opposite face entirely for now.
  41775. //Note that the cases in which this happens, what usually happens is that
  41776. // more than one edge bleeds onto the opposite face, and the bounding box
  41777. // encompasses the entire cube map face.
  41778. if (bleedOverAmount[i] > srcSize) {
  41779. //determine opposite face
  41780. switch (faceIdx) {
  41781. case PMREMGenerator.CP_FACE_X_POS:
  41782. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  41783. break;
  41784. case PMREMGenerator.CP_FACE_X_NEG:
  41785. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  41786. break;
  41787. case PMREMGenerator.CP_FACE_Y_POS:
  41788. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  41789. break;
  41790. case PMREMGenerator.CP_FACE_Y_NEG:
  41791. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  41792. break;
  41793. case PMREMGenerator.CP_FACE_Z_POS:
  41794. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  41795. break;
  41796. case PMREMGenerator.CP_FACE_Z_NEG:
  41797. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  41798. break;
  41799. default:
  41800. break;
  41801. }
  41802. //just encompass entire face for now
  41803. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  41804. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  41805. }
  41806. }
  41807. };
  41808. //--------------------------------------------------------------------------------------
  41809. //ProcessFilterExtents
  41810. // Process bounding box in each cube face
  41811. //
  41812. //--------------------------------------------------------------------------------------
  41813. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  41814. //accumulators are 64-bit floats in order to have the precision needed
  41815. // over a summation of a large number of pixels
  41816. var dstAccum = [0, 0, 0, 0];
  41817. var weightAccum = 0;
  41818. var k = 0;
  41819. var nSrcChannels = this.numChannels;
  41820. // norm cube map and srcCubeMap have same face width
  41821. var faceWidth = srcSize;
  41822. //amount to add to pointer to move to next scanline in images
  41823. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  41824. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  41825. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  41826. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  41827. // iterate over cubefaces
  41828. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  41829. //if bbox is non empty
  41830. if (!filterExtents[iFaceIdx].empty()) {
  41831. var uStart = filterExtents[iFaceIdx].min.x;
  41832. var vStart = filterExtents[iFaceIdx].min.y;
  41833. var uEnd = filterExtents[iFaceIdx].max.x;
  41834. var vEnd = filterExtents[iFaceIdx].max.y;
  41835. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  41836. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  41837. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  41838. for (var v = vStart; v <= vEnd; v++) {
  41839. var normCubeRowWalk = 0;
  41840. var srcCubeRowWalk = 0;
  41841. for (var u = uStart; u <= uEnd; u++) {
  41842. //pointer to direction in cube map associated with texel
  41843. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  41844. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  41845. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  41846. //check dot product to see if texel is within cone
  41847. var tapDotProd = texelVectX * centerTapDir.x +
  41848. texelVectY * centerTapDir.y +
  41849. texelVectZ * centerTapDir.z;
  41850. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  41851. //solid angle stored in 4th channel of normalizer/solid angle cube map
  41852. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  41853. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  41854. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  41855. // so just adding one to specularpower do the trick.
  41856. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  41857. //iterate over channels
  41858. for (k = 0; k < nSrcChannels; k++) {
  41859. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  41860. srcCubeRowWalk++;
  41861. }
  41862. weightAccum += weight; //accumulate weight
  41863. }
  41864. else {
  41865. //step across source pixel
  41866. srcCubeRowWalk += nSrcChannels;
  41867. }
  41868. normCubeRowWalk += 4; // 4 channels per norm cube map.
  41869. }
  41870. startIndexNormCubeMap += normCubePitch;
  41871. startIndexSrcCubeMap += srcCubePitch;
  41872. }
  41873. }
  41874. }
  41875. //divide through by weights if weight is non zero
  41876. if (weightAccum != 0.0) {
  41877. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  41878. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  41879. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  41880. if (this.numChannels > 3) {
  41881. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  41882. }
  41883. }
  41884. else {
  41885. // otherwise sample nearest
  41886. // get face idx and u, v texel coordinate in face
  41887. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  41888. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  41889. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  41890. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  41891. if (this.numChannels > 3) {
  41892. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  41893. }
  41894. }
  41895. return PMREMGenerator._vectorTemp;
  41896. };
  41897. //--------------------------------------------------------------------------------------
  41898. // Fixup cube edges
  41899. //
  41900. // average texels on cube map faces across the edges
  41901. // WARP/BENT Method Only.
  41902. //--------------------------------------------------------------------------------------
  41903. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  41904. var k;
  41905. var j;
  41906. var i;
  41907. var iFace;
  41908. var iCorner = 0;
  41909. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  41910. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  41911. // note that if functionality to filter across the three texels for each corner, then
  41912. //indexed by corner and face idx. the array contains the face the start points belongs to.
  41913. var cornerPtr = [
  41914. [[], [], []],
  41915. [[], [], []],
  41916. [[], [], []],
  41917. [[], [], []],
  41918. [[], [], []],
  41919. [[], [], []],
  41920. [[], [], []],
  41921. [[], [], []]
  41922. ];
  41923. //if there is no fixup, or fixup width = 0, do nothing
  41924. if (cubeMapSize < 1) {
  41925. return;
  41926. }
  41927. //special case 1x1 cubemap, average face colors
  41928. if (cubeMapSize == 1) {
  41929. //iterate over channels
  41930. for (k = 0; k < this.numChannels; k++) {
  41931. var accum = 0.0;
  41932. //iterate over faces to accumulate face colors
  41933. for (iFace = 0; iFace < 6; iFace++) {
  41934. accum += cubeMap[iFace][k];
  41935. }
  41936. //compute average over 6 face colors
  41937. accum /= 6.0;
  41938. //iterate over faces to distribute face colors
  41939. for (iFace = 0; iFace < 6; iFace++) {
  41940. cubeMap[iFace][k] = accum;
  41941. }
  41942. }
  41943. return;
  41944. }
  41945. //iterate over faces to collect list of corner texel pointers
  41946. for (iFace = 0; iFace < 6; iFace++) {
  41947. //the 4 corner pointers for this face
  41948. faceCornerStartIndicies[0] = [iFace, 0];
  41949. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  41950. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  41951. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  41952. //iterate over face corners to collect cube corner pointers
  41953. for (iCorner = 0; iCorner < 4; iCorner++) {
  41954. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  41955. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  41956. cornerNumPtrs[corner]++;
  41957. }
  41958. }
  41959. //iterate over corners to average across corner tap values
  41960. for (iCorner = 0; iCorner < 8; iCorner++) {
  41961. for (k = 0; k < this.numChannels; k++) {
  41962. var cornerTapAccum = 0.0;
  41963. //iterate over corner texels and average results
  41964. for (i = 0; i < 3; i++) {
  41965. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  41966. }
  41967. //divide by 3 to compute average of corner tap values
  41968. cornerTapAccum *= (1.0 / 3.0);
  41969. //iterate over corner texels and average results
  41970. for (i = 0; i < 3; i++) {
  41971. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  41972. }
  41973. }
  41974. }
  41975. //iterate over the twelve edges of the cube to average across edges
  41976. for (i = 0; i < 12; i++) {
  41977. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  41978. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  41979. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  41980. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  41981. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  41982. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  41983. var edgeWalk = 0;
  41984. var neighborEdgeWalk = 0;
  41985. //Determine walking pointers based on edge type
  41986. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  41987. switch (edge) {
  41988. case PMREMGenerator.CP_EDGE_LEFT:
  41989. // no change to faceEdgeStartPtr
  41990. edgeWalk = this.numChannels * cubeMapSize;
  41991. break;
  41992. case PMREMGenerator.CP_EDGE_RIGHT:
  41993. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  41994. edgeWalk = this.numChannels * cubeMapSize;
  41995. break;
  41996. case PMREMGenerator.CP_EDGE_TOP:
  41997. // no change to faceEdgeStartPtr
  41998. edgeWalk = this.numChannels;
  41999. break;
  42000. case PMREMGenerator.CP_EDGE_BOTTOM:
  42001. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  42002. edgeWalk = this.numChannels;
  42003. break;
  42004. }
  42005. //For certain types of edge abutments, the neighbor edge walk needs to
  42006. // be flipped: the cases are
  42007. // if a left edge mates with a left or bottom edge on the neighbor
  42008. // if a top edge mates with a top or right edge on the neighbor
  42009. // if a right edge mates with a right or top edge on the neighbor
  42010. // if a bottom edge mates with a bottom or left edge on the neighbor
  42011. //Seeing as the edges are enumerated as follows
  42012. // left =0
  42013. // right =1
  42014. // top =2
  42015. // bottom =3
  42016. //
  42017. //If the edge enums are the same, or the sum of the enums == 3,
  42018. // the neighbor edge walk needs to be flipped
  42019. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  42020. switch (neighborEdge) {
  42021. case PMREMGenerator.CP_EDGE_LEFT:
  42022. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  42023. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  42024. break;
  42025. case PMREMGenerator.CP_EDGE_RIGHT:
  42026. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  42027. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  42028. break;
  42029. case PMREMGenerator.CP_EDGE_TOP:
  42030. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  42031. neighborEdgeWalk = -this.numChannels;
  42032. break;
  42033. case PMREMGenerator.CP_EDGE_BOTTOM:
  42034. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  42035. neighborEdgeWalk = -this.numChannels;
  42036. break;
  42037. }
  42038. }
  42039. else {
  42040. //swapped direction neighbor edge walk
  42041. switch (neighborEdge) {
  42042. case PMREMGenerator.CP_EDGE_LEFT:
  42043. //no change to neighborEdgeStartPtr for this case since it points
  42044. // to the upper left corner already
  42045. neighborEdgeWalk = this.numChannels * cubeMapSize;
  42046. break;
  42047. case PMREMGenerator.CP_EDGE_RIGHT:
  42048. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  42049. neighborEdgeWalk = this.numChannels * cubeMapSize;
  42050. break;
  42051. case PMREMGenerator.CP_EDGE_TOP:
  42052. //no change to neighborEdgeStartPtr for this case since it points
  42053. // to the upper left corner already
  42054. neighborEdgeWalk = this.numChannels;
  42055. break;
  42056. case PMREMGenerator.CP_EDGE_BOTTOM:
  42057. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  42058. neighborEdgeWalk = this.numChannels;
  42059. break;
  42060. }
  42061. }
  42062. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  42063. //nearby neighborhood
  42064. //step ahead one texel on edge
  42065. edgeStartIndex += edgeWalk;
  42066. neighborEdgeStartIndex += neighborEdgeWalk;
  42067. // note that this loop does not process the corner texels, since they have already been
  42068. // averaged across faces across earlier
  42069. for (j = 1; j < (cubeMapSize - 1); j++) {
  42070. //for each set of taps along edge, average them
  42071. // and rewrite the results into the edges
  42072. for (k = 0; k < this.numChannels; k++) {
  42073. var edgeTap = cubeMap[face][edgeStartIndex + k];
  42074. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  42075. //compute average of tap intensity values
  42076. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  42077. //propagate average of taps to edge taps
  42078. cubeMap[face][edgeStartIndex + k] = avgTap;
  42079. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  42080. }
  42081. edgeStartIndex += edgeWalk;
  42082. neighborEdgeStartIndex += neighborEdgeWalk;
  42083. }
  42084. }
  42085. };
  42086. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  42087. PMREMGenerator.CP_UDIR = 0;
  42088. PMREMGenerator.CP_VDIR = 1;
  42089. PMREMGenerator.CP_FACEAXIS = 2;
  42090. //used to index cube faces
  42091. PMREMGenerator.CP_FACE_X_POS = 0;
  42092. PMREMGenerator.CP_FACE_X_NEG = 1;
  42093. PMREMGenerator.CP_FACE_Y_POS = 2;
  42094. PMREMGenerator.CP_FACE_Y_NEG = 3;
  42095. PMREMGenerator.CP_FACE_Z_POS = 4;
  42096. PMREMGenerator.CP_FACE_Z_NEG = 5;
  42097. //used to index image edges
  42098. // NOTE.. the actual number corresponding to the edge is important
  42099. // do not change these, or the code will break
  42100. //
  42101. // CP_EDGE_LEFT is u = 0
  42102. // CP_EDGE_RIGHT is u = width-1
  42103. // CP_EDGE_TOP is v = 0
  42104. // CP_EDGE_BOTTOM is v = height-1
  42105. PMREMGenerator.CP_EDGE_LEFT = 0;
  42106. PMREMGenerator.CP_EDGE_RIGHT = 1;
  42107. PMREMGenerator.CP_EDGE_TOP = 2;
  42108. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  42109. //corners of CUBE map (P or N specifys if it corresponds to the
  42110. // positive or negative direction each of X, Y, and Z
  42111. PMREMGenerator.CP_CORNER_NNN = 0;
  42112. PMREMGenerator.CP_CORNER_NNP = 1;
  42113. PMREMGenerator.CP_CORNER_NPN = 2;
  42114. PMREMGenerator.CP_CORNER_NPP = 3;
  42115. PMREMGenerator.CP_CORNER_PNN = 4;
  42116. PMREMGenerator.CP_CORNER_PNP = 5;
  42117. PMREMGenerator.CP_CORNER_PPN = 6;
  42118. PMREMGenerator.CP_CORNER_PPP = 7;
  42119. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  42120. //3x2 matrices that map cube map indexing vectors in 3d
  42121. // (after face selection and divide through by the
  42122. // _ABSOLUTE VALUE_ of the max coord)
  42123. // into NVC space
  42124. //Note this currently assumes the D3D cube face ordering and orientation
  42125. PMREMGenerator._sgFace2DMapping = [
  42126. //XPOS face
  42127. [[0, 0, -1],
  42128. [0, -1, 0],
  42129. [1, 0, 0]],
  42130. //XNEG face
  42131. [[0, 0, 1],
  42132. [0, -1, 0],
  42133. [-1, 0, 0]],
  42134. //YPOS face
  42135. [[1, 0, 0],
  42136. [0, 0, 1],
  42137. [0, 1, 0]],
  42138. //YNEG face
  42139. [[1, 0, 0],
  42140. [0, 0, -1],
  42141. [0, -1, 0]],
  42142. //ZPOS face
  42143. [[1, 0, 0],
  42144. [0, -1, 0],
  42145. [0, 0, 1]],
  42146. //ZNEG face
  42147. [[-1, 0, 0],
  42148. [0, -1, 0],
  42149. [0, 0, -1]],
  42150. ];
  42151. //------------------------------------------------------------------------------
  42152. // D3D cube map face specification
  42153. // mapping from 3D x,y,z cube map lookup coordinates
  42154. // to 2D within face u,v coordinates
  42155. //
  42156. // --------------------> U direction
  42157. // | (within-face texture space)
  42158. // | _____
  42159. // | | |
  42160. // | | +Y |
  42161. // | _____|_____|_____ _____
  42162. // | | | | | |
  42163. // | | -X | +Z | +X | -Z |
  42164. // | |_____|_____|_____|_____|
  42165. // | | |
  42166. // | | -Y |
  42167. // | |_____|
  42168. // |
  42169. // v V direction
  42170. // (within-face texture space)
  42171. //------------------------------------------------------------------------------
  42172. //Information about neighbors and how texture coorrdinates change across faces
  42173. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  42174. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  42175. //Note this currently assumes the D3D cube face ordering and orientation
  42176. PMREMGenerator._sgCubeNgh = [
  42177. //XPOS face
  42178. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  42179. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  42180. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  42181. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  42182. //XNEG face
  42183. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  42184. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  42185. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  42186. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  42187. //YPOS face
  42188. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  42189. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  42190. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  42191. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  42192. //YNEG face
  42193. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  42194. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42195. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42196. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  42197. //ZPOS face
  42198. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  42199. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  42200. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42201. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  42202. //ZNEG face
  42203. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  42204. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  42205. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  42206. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  42207. ];
  42208. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  42209. // this table is used to average over the edges.
  42210. PMREMGenerator._sgCubeEdgeList = [
  42211. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  42212. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  42213. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  42214. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42215. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  42216. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  42217. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  42218. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  42219. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  42220. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  42221. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  42222. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  42223. ];
  42224. //Information about which of the 8 cube corners are correspond to the
  42225. // the 4 corners in each cube face
  42226. // the order is upper left, upper right, lower left, lower right
  42227. PMREMGenerator._sgCubeCornerList = [
  42228. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  42229. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  42230. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  42231. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  42232. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  42233. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  42234. ];
  42235. return PMREMGenerator;
  42236. })();
  42237. Internals.PMREMGenerator = PMREMGenerator;
  42238. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42239. })(BABYLON || (BABYLON = {}));
  42240. var BABYLON;
  42241. (function (BABYLON) {
  42242. /**
  42243. * This represents a texture coming from an HDR input.
  42244. *
  42245. * The only supported format is currently panorama picture stored in RGBE format.
  42246. * Example of such files can be found on HDRLib: http://hdrlib.com/
  42247. */
  42248. var HDRCubeTexture = (function (_super) {
  42249. __extends(HDRCubeTexture, _super);
  42250. /**
  42251. * Instantiates an HDRTexture from the following parameters.
  42252. *
  42253. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  42254. * @param scene The scene the texture will be used in
  42255. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  42256. * @param noMipmap Forces to not generate the mipmap if true
  42257. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  42258. * @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)
  42259. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  42260. */
  42261. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  42262. if (noMipmap === void 0) { noMipmap = false; }
  42263. if (generateHarmonics === void 0) { generateHarmonics = true; }
  42264. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  42265. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  42266. _super.call(this, scene);
  42267. this._useInGammaSpace = false;
  42268. this._generateHarmonics = true;
  42269. /**
  42270. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  42271. */
  42272. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  42273. /**
  42274. * The spherical polynomial data extracted from the texture.
  42275. */
  42276. this.sphericalPolynomial = null;
  42277. /**
  42278. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  42279. * This is usefull at run time to apply the good shader.
  42280. */
  42281. this.isPMREM = false;
  42282. this.name = url;
  42283. this.url = url;
  42284. this._noMipmap = noMipmap;
  42285. this.hasAlpha = false;
  42286. this._size = size;
  42287. this._useInGammaSpace = useInGammaSpace;
  42288. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  42289. this.isPMREM = this._usePMREMGenerator;
  42290. if (!url) {
  42291. return;
  42292. }
  42293. this._texture = this._getFromCache(url, noMipmap);
  42294. if (!this._texture) {
  42295. if (!scene.useDelayedTextureLoading) {
  42296. this.loadTexture();
  42297. }
  42298. else {
  42299. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42300. }
  42301. }
  42302. this.isCube = true;
  42303. this._textureMatrix = BABYLON.Matrix.Identity();
  42304. }
  42305. HDRCubeTexture.prototype.loadTexture = function () {
  42306. var _this = this;
  42307. var callback = function (buffer) {
  42308. // Extract the raw linear data.
  42309. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  42310. // Generate harmonics if needed.
  42311. if (_this._generateHarmonics) {
  42312. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  42313. }
  42314. var results = [];
  42315. var byteArray = null;
  42316. // Create uintarray fallback.
  42317. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  42318. // 3 channels of 1 bytes per pixel in bytes.
  42319. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  42320. byteArray = new Uint8Array(byteBuffer);
  42321. }
  42322. // Push each faces.
  42323. for (var j = 0; j < 6; j++) {
  42324. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  42325. // If special cases.
  42326. if (_this._useInGammaSpace || byteArray) {
  42327. for (var i = 0; i < _this._size * _this._size; i++) {
  42328. // Put in gamma space if requested.
  42329. if (_this._useInGammaSpace) {
  42330. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  42331. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  42332. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  42333. }
  42334. // Convert to int texture for fallback.
  42335. if (byteArray) {
  42336. // R
  42337. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  42338. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  42339. // G
  42340. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  42341. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  42342. // B
  42343. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  42344. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  42345. }
  42346. }
  42347. }
  42348. results.push(dataFace);
  42349. }
  42350. return results;
  42351. };
  42352. var mipmapGenerator = null;
  42353. if (!this._noMipmap && this._usePMREMGenerator) {
  42354. mipmapGenerator = function (data) {
  42355. // Custom setup of the generator matching with the PBR shader values.
  42356. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  42357. return generator.filterCubeMap();
  42358. };
  42359. }
  42360. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  42361. };
  42362. HDRCubeTexture.prototype.clone = function () {
  42363. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  42364. // Base texture
  42365. newTexture.level = this.level;
  42366. newTexture.wrapU = this.wrapU;
  42367. newTexture.wrapV = this.wrapV;
  42368. newTexture.coordinatesIndex = this.coordinatesIndex;
  42369. newTexture.coordinatesMode = this.coordinatesMode;
  42370. return newTexture;
  42371. };
  42372. // Methods
  42373. HDRCubeTexture.prototype.delayLoad = function () {
  42374. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  42375. return;
  42376. }
  42377. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42378. this._texture = this._getFromCache(this.url, this._noMipmap);
  42379. if (!this._texture) {
  42380. this.loadTexture();
  42381. }
  42382. };
  42383. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  42384. return this._textureMatrix;
  42385. };
  42386. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  42387. var texture = null;
  42388. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  42389. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  42390. texture.name = parsedTexture.name;
  42391. texture.hasAlpha = parsedTexture.hasAlpha;
  42392. texture.level = parsedTexture.level;
  42393. texture.coordinatesMode = parsedTexture.coordinatesMode;
  42394. }
  42395. return texture;
  42396. };
  42397. HDRCubeTexture.prototype.serialize = function () {
  42398. if (!this.name) {
  42399. return null;
  42400. }
  42401. var serializationObject = {};
  42402. serializationObject.name = this.name;
  42403. serializationObject.hasAlpha = this.hasAlpha;
  42404. serializationObject.isCube = true;
  42405. serializationObject.level = this.level;
  42406. serializationObject.size = this._size;
  42407. serializationObject.coordinatesMode = this.coordinatesMode;
  42408. serializationObject.useInGammaSpace = this._useInGammaSpace;
  42409. serializationObject.generateHarmonics = this._generateHarmonics;
  42410. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  42411. return serializationObject;
  42412. };
  42413. HDRCubeTexture._facesMapping = [
  42414. "right",
  42415. "up",
  42416. "front",
  42417. "left",
  42418. "down",
  42419. "back"
  42420. ];
  42421. return HDRCubeTexture;
  42422. })(BABYLON.BaseTexture);
  42423. BABYLON.HDRCubeTexture = HDRCubeTexture;
  42424. })(BABYLON || (BABYLON = {}));
  42425. var BABYLON;
  42426. (function (BABYLON) {
  42427. var Debug;
  42428. (function (Debug) {
  42429. /**
  42430. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  42431. */
  42432. var SkeletonViewer = (function () {
  42433. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  42434. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  42435. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  42436. this.skeleton = skeleton;
  42437. this.mesh = mesh;
  42438. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  42439. this.renderingGroupId = renderingGroupId;
  42440. this.color = BABYLON.Color3.White();
  42441. this._debugLines = [];
  42442. this._isEnabled = false;
  42443. this._scene = scene;
  42444. this.update();
  42445. this._renderFunction = this.update.bind(this);
  42446. }
  42447. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  42448. get: function () {
  42449. return this._isEnabled;
  42450. },
  42451. set: function (value) {
  42452. if (this._isEnabled === value) {
  42453. return;
  42454. }
  42455. this._isEnabled = value;
  42456. if (value) {
  42457. this._scene.registerBeforeRender(this._renderFunction);
  42458. }
  42459. else {
  42460. this._scene.unregisterBeforeRender(this._renderFunction);
  42461. }
  42462. },
  42463. enumerable: true,
  42464. configurable: true
  42465. });
  42466. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  42467. if (x === void 0) { x = 0; }
  42468. if (y === void 0) { y = 0; }
  42469. if (z === void 0) { z = 0; }
  42470. var tmat = BABYLON.Tmp.Matrix[0];
  42471. var parentBone = bone.getParent();
  42472. tmat.copyFrom(bone.getLocalMatrix());
  42473. if (x !== 0 || y !== 0 || z !== 0) {
  42474. var tmat2 = BABYLON.Tmp.Matrix[1];
  42475. BABYLON.Matrix.IdentityToRef(tmat2);
  42476. tmat2.m[12] = x;
  42477. tmat2.m[13] = y;
  42478. tmat2.m[14] = z;
  42479. tmat2.multiplyToRef(tmat, tmat);
  42480. }
  42481. if (parentBone) {
  42482. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  42483. }
  42484. tmat.multiplyToRef(meshMat, tmat);
  42485. position.x = tmat.m[12];
  42486. position.y = tmat.m[13];
  42487. position.z = tmat.m[14];
  42488. };
  42489. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  42490. var len = bones.length;
  42491. for (var i = 0; i < len; i++) {
  42492. var bone = bones[i];
  42493. var points = this._debugLines[i];
  42494. if (!points) {
  42495. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  42496. this._debugLines[i] = points;
  42497. }
  42498. this._getBonePosition(points[0], bone, meshMat);
  42499. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  42500. }
  42501. };
  42502. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  42503. var len = bones.length;
  42504. var boneNum = 0;
  42505. for (var i = len - 1; i >= 0; i--) {
  42506. var childBone = bones[i];
  42507. var parentBone = childBone.getParent();
  42508. if (!parentBone) {
  42509. continue;
  42510. }
  42511. var points = this._debugLines[boneNum];
  42512. if (!points) {
  42513. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  42514. this._debugLines[boneNum] = points;
  42515. }
  42516. this._getBonePosition(points[0], childBone, meshMat);
  42517. this._getBonePosition(points[1], parentBone, meshMat);
  42518. boneNum++;
  42519. }
  42520. };
  42521. SkeletonViewer.prototype.update = function () {
  42522. if (this.autoUpdateBonesMatrices) {
  42523. this._updateBoneMatrix(this.skeleton.bones[0]);
  42524. }
  42525. if (this.skeleton.bones[0].length === undefined) {
  42526. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  42527. }
  42528. else {
  42529. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  42530. }
  42531. if (!this._debugMesh) {
  42532. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  42533. this._debugMesh.renderingGroupId = this.renderingGroupId;
  42534. }
  42535. else {
  42536. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  42537. }
  42538. this._debugMesh.color = this.color;
  42539. };
  42540. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  42541. if (bone.getParent()) {
  42542. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  42543. }
  42544. var children = bone.children;
  42545. var len = children.length;
  42546. for (var i = 0; i < len; i++) {
  42547. this._updateBoneMatrix(children[i]);
  42548. }
  42549. };
  42550. SkeletonViewer.prototype.dispose = function () {
  42551. if (this._debugMesh) {
  42552. this.isEnabled = false;
  42553. this._debugMesh.dispose();
  42554. this._debugMesh = null;
  42555. }
  42556. };
  42557. return SkeletonViewer;
  42558. })();
  42559. Debug.SkeletonViewer = SkeletonViewer;
  42560. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  42561. })(BABYLON || (BABYLON = {}));
  42562. 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}"};
  42563. 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"};
  42564. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:!(o.z-i>e.z)},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new n(o,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=t.x*i.m[0]+t.y*i.m[4],o=t.x*i.m[1]+t.y*i.m[5];return new n(r,o)},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n}();t.Vector2=o;var s=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new h(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var s=o.width,e=o.height,h=o.x,u=o.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,s,e){var h=r.normalize(),a=s.normalize(),u=c.X,m=c.Y,y=0,p=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=_.Vector3[0],T=0,R=_.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var M=_.Vector3[2],F=_.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),M.x=l,M.y=x,M.z=z,M.normalize(),n.CrossToRef(M,R,F),F.normalize(),n.CrossToRef(a,M,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,M),T=Math.min(1,Math.max(-1,T)),p=Math.acos(T)*v,n.Dot(F,m)<0&&(p=Math.PI+p,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=p,e.y=y,e.z=f},n}();t.Vector3=s;var e=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=e;var h=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=s.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=h;var a=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,E=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*S)*b,t.m[14]=-(i*P-n*C+r*S)*b,t.m[3]=-(n*I-r*q+o*E)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*E-n*V+r*W)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*S,i[n+3]=r*T+o*F+s*P+e*I,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*F+u*P+m*I,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*d+c*_+p*A+f*C,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*F+p*P+f*I,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*F+z*P+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return h.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.FromValues=function(i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);\ni.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){h.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){var o=new s(0,0,0),e=new h,a=new s(0,0,0);i.decompose(o,e,a);var u=new s(0,0,0),m=new h,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=h.Slerp(e,m,r),f=s.Lerp(a,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new h,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=a;var u=function(){function t(t,i,n,r){this.normal=new s(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=a.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,u,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return s.Dot(n,i)+r},t}();t.Plane=u;var m=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=m;var y=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new u(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=c;var p=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new x(e,h,a),m=u.angle.radians()/s;u.orientation===f.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,l=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,l),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=z;var w=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},n}();t.Path3D=w;var v=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)e.push(new s(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,o,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=v;var d=function(){function t(){this.L00=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=d;var g=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=g;var T=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var R=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=R;var _=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.Zero()],t.Quaternion=[new h(0,0,0,0)],t.Matrix=[a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero()],t}();t.Tmp=_}(BABYLON||(BABYLON={}));";
  42565. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  42566. module.exports = BABYLON;
  42567. };