babylon.max.js 2.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. // Operators
  62. Color3.prototype.toArray = function (array, index) {
  63. if (index === undefined) {
  64. index = 0;
  65. }
  66. array[index] = this.r;
  67. array[index + 1] = this.g;
  68. array[index + 2] = this.b;
  69. return this;
  70. };
  71. Color3.prototype.toColor4 = function (alpha) {
  72. if (alpha === void 0) { alpha = 1; }
  73. return new Color4(this.r, this.g, this.b, alpha);
  74. };
  75. Color3.prototype.asArray = function () {
  76. var result = [];
  77. this.toArray(result, 0);
  78. return result;
  79. };
  80. Color3.prototype.toLuminance = function () {
  81. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  82. };
  83. Color3.prototype.multiply = function (otherColor) {
  84. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  85. };
  86. Color3.prototype.multiplyToRef = function (otherColor, result) {
  87. result.r = this.r * otherColor.r;
  88. result.g = this.g * otherColor.g;
  89. result.b = this.b * otherColor.b;
  90. return this;
  91. };
  92. Color3.prototype.equals = function (otherColor) {
  93. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  94. };
  95. Color3.prototype.equalsFloats = function (r, g, b) {
  96. return this.r === r && this.g === g && this.b === b;
  97. };
  98. Color3.prototype.scale = function (scale) {
  99. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  100. };
  101. Color3.prototype.scaleToRef = function (scale, result) {
  102. result.r = this.r * scale;
  103. result.g = this.g * scale;
  104. result.b = this.b * scale;
  105. return this;
  106. };
  107. Color3.prototype.add = function (otherColor) {
  108. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  109. };
  110. Color3.prototype.addToRef = function (otherColor, result) {
  111. result.r = this.r + otherColor.r;
  112. result.g = this.g + otherColor.g;
  113. result.b = this.b + otherColor.b;
  114. return this;
  115. };
  116. Color3.prototype.subtract = function (otherColor) {
  117. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  118. };
  119. Color3.prototype.subtractToRef = function (otherColor, result) {
  120. result.r = this.r - otherColor.r;
  121. result.g = this.g - otherColor.g;
  122. result.b = this.b - otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.clone = function () {
  126. return new Color3(this.r, this.g, this.b);
  127. };
  128. Color3.prototype.copyFrom = function (source) {
  129. this.r = source.r;
  130. this.g = source.g;
  131. this.b = source.b;
  132. return this;
  133. };
  134. Color3.prototype.copyFromFloats = function (r, g, b) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. return this;
  139. };
  140. Color3.prototype.toHexString = function () {
  141. var intR = (this.r * 255) | 0;
  142. var intG = (this.g * 255) | 0;
  143. var intB = (this.b * 255) | 0;
  144. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  145. };
  146. Color3.prototype.toLinearSpace = function () {
  147. var convertedColor = new Color3();
  148. this.toLinearSpaceToRef(convertedColor);
  149. return convertedColor;
  150. };
  151. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  152. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  153. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  154. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  155. return this;
  156. };
  157. Color3.prototype.toGammaSpace = function () {
  158. var convertedColor = new Color3();
  159. this.toGammaSpaceToRef(convertedColor);
  160. return convertedColor;
  161. };
  162. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  163. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  164. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  165. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  166. return this;
  167. };
  168. // Statics
  169. Color3.FromHexString = function (hex) {
  170. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  171. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  172. return new Color3(0, 0, 0);
  173. }
  174. var r = parseInt(hex.substring(1, 3), 16);
  175. var g = parseInt(hex.substring(3, 5), 16);
  176. var b = parseInt(hex.substring(5, 7), 16);
  177. return Color3.FromInts(r, g, b);
  178. };
  179. Color3.FromArray = function (array, offset) {
  180. if (offset === void 0) { offset = 0; }
  181. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  182. };
  183. Color3.FromInts = function (r, g, b) {
  184. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  185. };
  186. Color3.Lerp = function (start, end, amount) {
  187. var r = start.r + ((end.r - start.r) * amount);
  188. var g = start.g + ((end.g - start.g) * amount);
  189. var b = start.b + ((end.b - start.b) * amount);
  190. return new Color3(r, g, b);
  191. };
  192. Color3.Red = function () { return new Color3(1, 0, 0); };
  193. Color3.Green = function () { return new Color3(0, 1, 0); };
  194. Color3.Blue = function () { return new Color3(0, 0, 1); };
  195. Color3.Black = function () { return new Color3(0, 0, 0); };
  196. Color3.White = function () { return new Color3(1, 1, 1); };
  197. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  198. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  199. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  200. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  201. return Color3;
  202. })();
  203. BABYLON.Color3 = Color3;
  204. var Color4 = (function () {
  205. function Color4(r, g, b, a) {
  206. this.r = r;
  207. this.g = g;
  208. this.b = b;
  209. this.a = a;
  210. }
  211. // Operators
  212. Color4.prototype.addInPlace = function (right) {
  213. this.r += right.r;
  214. this.g += right.g;
  215. this.b += right.b;
  216. this.a += right.a;
  217. return this;
  218. };
  219. Color4.prototype.asArray = function () {
  220. var result = [];
  221. this.toArray(result, 0);
  222. return result;
  223. };
  224. Color4.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.r;
  229. array[index + 1] = this.g;
  230. array[index + 2] = this.b;
  231. array[index + 3] = this.a;
  232. return this;
  233. };
  234. Color4.prototype.add = function (right) {
  235. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  236. };
  237. Color4.prototype.subtract = function (right) {
  238. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  239. };
  240. Color4.prototype.subtractToRef = function (right, result) {
  241. result.r = this.r - right.r;
  242. result.g = this.g - right.g;
  243. result.b = this.b - right.b;
  244. result.a = this.a - right.a;
  245. return this;
  246. };
  247. Color4.prototype.scale = function (scale) {
  248. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  249. };
  250. Color4.prototype.scaleToRef = function (scale, result) {
  251. result.r = this.r * scale;
  252. result.g = this.g * scale;
  253. result.b = this.b * scale;
  254. result.a = this.a * scale;
  255. return this;
  256. };
  257. Color4.prototype.toString = function () {
  258. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  259. };
  260. Color4.prototype.clone = function () {
  261. return new Color4(this.r, this.g, this.b, this.a);
  262. };
  263. Color4.prototype.copyFrom = function (source) {
  264. this.r = source.r;
  265. this.g = source.g;
  266. this.b = source.b;
  267. this.a = source.a;
  268. return this;
  269. };
  270. Color4.prototype.toHexString = function () {
  271. var intR = (this.r * 255) | 0;
  272. var intG = (this.g * 255) | 0;
  273. var intB = (this.b * 255) | 0;
  274. var intA = (this.a * 255) | 0;
  275. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  276. };
  277. // Statics
  278. Color4.FromHexString = function (hex) {
  279. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  280. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  281. return new Color4(0, 0, 0, 0);
  282. }
  283. var r = parseInt(hex.substring(1, 3), 16);
  284. var g = parseInt(hex.substring(3, 5), 16);
  285. var b = parseInt(hex.substring(5, 7), 16);
  286. var a = parseInt(hex.substring(7, 9), 16);
  287. return Color4.FromInts(r, g, b, a);
  288. };
  289. Color4.Lerp = function (left, right, amount) {
  290. var result = new Color4(0, 0, 0, 0);
  291. Color4.LerpToRef(left, right, amount, result);
  292. return result;
  293. };
  294. Color4.LerpToRef = function (left, right, amount, result) {
  295. result.r = left.r + (right.r - left.r) * amount;
  296. result.g = left.g + (right.g - left.g) * amount;
  297. result.b = left.b + (right.b - left.b) * amount;
  298. result.a = left.a + (right.a - left.a) * amount;
  299. };
  300. Color4.FromArray = function (array, offset) {
  301. if (offset === void 0) { offset = 0; }
  302. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  303. };
  304. Color4.FromInts = function (r, g, b, a) {
  305. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  306. };
  307. Color4.CheckColors4 = function (colors, count) {
  308. // Check if color3 was used
  309. if (colors.length === count * 3) {
  310. var colors4 = [];
  311. for (var index = 0; index < colors.length; index += 3) {
  312. var newIndex = (index / 3) * 4;
  313. colors4[newIndex] = colors[index];
  314. colors4[newIndex + 1] = colors[index + 1];
  315. colors4[newIndex + 2] = colors[index + 2];
  316. colors4[newIndex + 3] = 1.0;
  317. }
  318. return colors4;
  319. }
  320. return colors;
  321. };
  322. return Color4;
  323. })();
  324. BABYLON.Color4 = Color4;
  325. var Vector2 = (function () {
  326. function Vector2(x, y) {
  327. this.x = x;
  328. this.y = y;
  329. }
  330. Vector2.prototype.toString = function () {
  331. return "{X: " + this.x + " Y:" + this.y + "}";
  332. };
  333. // Operators
  334. Vector2.prototype.toArray = function (array, index) {
  335. if (index === void 0) { index = 0; }
  336. array[index] = this.x;
  337. array[index + 1] = this.y;
  338. return this;
  339. };
  340. Vector2.prototype.asArray = function () {
  341. var result = [];
  342. this.toArray(result, 0);
  343. return result;
  344. };
  345. Vector2.prototype.copyFrom = function (source) {
  346. this.x = source.x;
  347. this.y = source.y;
  348. return this;
  349. };
  350. Vector2.prototype.copyFromFloats = function (x, y) {
  351. this.x = x;
  352. this.y = y;
  353. return this;
  354. };
  355. Vector2.prototype.add = function (otherVector) {
  356. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  357. };
  358. Vector2.prototype.addVector3 = function (otherVector) {
  359. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  360. };
  361. Vector2.prototype.subtract = function (otherVector) {
  362. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  363. };
  364. Vector2.prototype.subtractInPlace = function (otherVector) {
  365. this.x -= otherVector.x;
  366. this.y -= otherVector.y;
  367. return this;
  368. };
  369. Vector2.prototype.multiplyInPlace = function (otherVector) {
  370. this.x *= otherVector.x;
  371. this.y *= otherVector.y;
  372. return this;
  373. };
  374. Vector2.prototype.multiply = function (otherVector) {
  375. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  376. };
  377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  378. result.x = this.x * otherVector.x;
  379. result.y = this.y * otherVector.y;
  380. return this;
  381. };
  382. Vector2.prototype.multiplyByFloats = function (x, y) {
  383. return new Vector2(this.x * x, this.y * y);
  384. };
  385. Vector2.prototype.divide = function (otherVector) {
  386. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  387. };
  388. Vector2.prototype.divideToRef = function (otherVector, result) {
  389. result.x = this.x / otherVector.x;
  390. result.y = this.y / otherVector.y;
  391. return this;
  392. };
  393. Vector2.prototype.negate = function () {
  394. return new Vector2(-this.x, -this.y);
  395. };
  396. Vector2.prototype.scaleInPlace = function (scale) {
  397. this.x *= scale;
  398. this.y *= scale;
  399. return this;
  400. };
  401. Vector2.prototype.scale = function (scale) {
  402. return new Vector2(this.x * scale, this.y * scale);
  403. };
  404. Vector2.prototype.equals = function (otherVector) {
  405. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  406. };
  407. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  408. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  409. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  410. };
  411. // Properties
  412. Vector2.prototype.length = function () {
  413. return Math.sqrt(this.x * this.x + this.y * this.y);
  414. };
  415. Vector2.prototype.lengthSquared = function () {
  416. return (this.x * this.x + this.y * this.y);
  417. };
  418. // Methods
  419. Vector2.prototype.normalize = function () {
  420. var len = this.length();
  421. if (len === 0)
  422. return this;
  423. var num = 1.0 / len;
  424. this.x *= num;
  425. this.y *= num;
  426. return this;
  427. };
  428. Vector2.prototype.clone = function () {
  429. return new Vector2(this.x, this.y);
  430. };
  431. // Statics
  432. Vector2.Zero = function () {
  433. return new Vector2(0, 0);
  434. };
  435. Vector2.FromArray = function (array, offset) {
  436. if (offset === void 0) { offset = 0; }
  437. return new Vector2(array[offset], array[offset + 1]);
  438. };
  439. Vector2.FromArrayToRef = function (array, offset, result) {
  440. result.x = array[offset];
  441. result.y = array[offset + 1];
  442. };
  443. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  444. var squared = amount * amount;
  445. var cubed = amount * squared;
  446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Clamp = function (value, min, max) {
  455. var x = value.x;
  456. x = (x > max.x) ? max.x : x;
  457. x = (x < min.x) ? min.x : x;
  458. var y = value.y;
  459. y = (y > max.y) ? max.y : y;
  460. y = (y < min.y) ? min.y : y;
  461. return new Vector2(x, y);
  462. };
  463. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  464. var squared = amount * amount;
  465. var cubed = amount * squared;
  466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  468. var part3 = (cubed - (2.0 * squared)) + amount;
  469. var part4 = cubed - squared;
  470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  472. return new Vector2(x, y);
  473. };
  474. Vector2.Lerp = function (start, end, amount) {
  475. var x = start.x + ((end.x - start.x) * amount);
  476. var y = start.y + ((end.y - start.y) * amount);
  477. return new Vector2(x, y);
  478. };
  479. Vector2.Dot = function (left, right) {
  480. return left.x * right.x + left.y * right.y;
  481. };
  482. Vector2.Normalize = function (vector) {
  483. var newVector = vector.clone();
  484. newVector.normalize();
  485. return newVector;
  486. };
  487. Vector2.Minimize = function (left, right) {
  488. var x = (left.x < right.x) ? left.x : right.x;
  489. var y = (left.y < right.y) ? left.y : right.y;
  490. return new Vector2(x, y);
  491. };
  492. Vector2.Maximize = function (left, right) {
  493. var x = (left.x > right.x) ? left.x : right.x;
  494. var y = (left.y > right.y) ? left.y : right.y;
  495. return new Vector2(x, y);
  496. };
  497. Vector2.Transform = function (vector, transformation) {
  498. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  499. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  500. return new Vector2(x, y);
  501. };
  502. Vector2.Distance = function (value1, value2) {
  503. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  504. };
  505. Vector2.DistanceSquared = function (value1, value2) {
  506. var x = value1.x - value2.x;
  507. var y = value1.y - value2.y;
  508. return (x * x) + (y * y);
  509. };
  510. return Vector2;
  511. })();
  512. BABYLON.Vector2 = Vector2;
  513. var Vector3 = (function () {
  514. function Vector3(x, y, z) {
  515. this.x = x;
  516. this.y = y;
  517. this.z = z;
  518. }
  519. Vector3.prototype.toString = function () {
  520. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  521. };
  522. // Operators
  523. Vector3.prototype.asArray = function () {
  524. var result = [];
  525. this.toArray(result, 0);
  526. return result;
  527. };
  528. Vector3.prototype.toArray = function (array, index) {
  529. if (index === void 0) { index = 0; }
  530. array[index] = this.x;
  531. array[index + 1] = this.y;
  532. array[index + 2] = this.z;
  533. return this;
  534. };
  535. Vector3.prototype.toQuaternion = function () {
  536. var result = new Quaternion(0, 0, 0, 1);
  537. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  538. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  539. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  540. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  541. var cosy = Math.cos(this.y * 0.5);
  542. var siny = Math.sin(this.y * 0.5);
  543. result.x = coszMinusx * siny;
  544. result.y = -sinzMinusx * siny;
  545. result.z = sinxPlusz * cosy;
  546. result.w = cosxPlusz * cosy;
  547. return result;
  548. };
  549. Vector3.prototype.addInPlace = function (otherVector) {
  550. this.x += otherVector.x;
  551. this.y += otherVector.y;
  552. this.z += otherVector.z;
  553. return this;
  554. };
  555. Vector3.prototype.add = function (otherVector) {
  556. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  557. };
  558. Vector3.prototype.addToRef = function (otherVector, result) {
  559. result.x = this.x + otherVector.x;
  560. result.y = this.y + otherVector.y;
  561. result.z = this.z + otherVector.z;
  562. return this;
  563. };
  564. Vector3.prototype.subtractInPlace = function (otherVector) {
  565. this.x -= otherVector.x;
  566. this.y -= otherVector.y;
  567. this.z -= otherVector.z;
  568. return this;
  569. };
  570. Vector3.prototype.subtract = function (otherVector) {
  571. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  572. };
  573. Vector3.prototype.subtractToRef = function (otherVector, result) {
  574. result.x = this.x - otherVector.x;
  575. result.y = this.y - otherVector.y;
  576. result.z = this.z - otherVector.z;
  577. return this;
  578. };
  579. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  580. return new Vector3(this.x - x, this.y - y, this.z - z);
  581. };
  582. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  583. result.x = this.x - x;
  584. result.y = this.y - y;
  585. result.z = this.z - z;
  586. return this;
  587. };
  588. Vector3.prototype.negate = function () {
  589. return new Vector3(-this.x, -this.y, -this.z);
  590. };
  591. Vector3.prototype.scaleInPlace = function (scale) {
  592. this.x *= scale;
  593. this.y *= scale;
  594. this.z *= scale;
  595. return this;
  596. };
  597. Vector3.prototype.scale = function (scale) {
  598. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  599. };
  600. Vector3.prototype.scaleToRef = function (scale, result) {
  601. result.x = this.x * scale;
  602. result.y = this.y * scale;
  603. result.z = this.z * scale;
  604. };
  605. Vector3.prototype.equals = function (otherVector) {
  606. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  607. };
  608. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  609. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  610. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  611. };
  612. Vector3.prototype.equalsToFloats = function (x, y, z) {
  613. return this.x === x && this.y === y && this.z === z;
  614. };
  615. Vector3.prototype.multiplyInPlace = function (otherVector) {
  616. this.x *= otherVector.x;
  617. this.y *= otherVector.y;
  618. this.z *= otherVector.z;
  619. return this;
  620. };
  621. Vector3.prototype.multiply = function (otherVector) {
  622. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  623. };
  624. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  625. result.x = this.x * otherVector.x;
  626. result.y = this.y * otherVector.y;
  627. result.z = this.z * otherVector.z;
  628. return this;
  629. };
  630. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  631. return new Vector3(this.x * x, this.y * y, this.z * z);
  632. };
  633. Vector3.prototype.divide = function (otherVector) {
  634. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  635. };
  636. Vector3.prototype.divideToRef = function (otherVector, result) {
  637. result.x = this.x / otherVector.x;
  638. result.y = this.y / otherVector.y;
  639. result.z = this.z / otherVector.z;
  640. return this;
  641. };
  642. Vector3.prototype.MinimizeInPlace = function (other) {
  643. if (other.x < this.x)
  644. this.x = other.x;
  645. if (other.y < this.y)
  646. this.y = other.y;
  647. if (other.z < this.z)
  648. this.z = other.z;
  649. return this;
  650. };
  651. Vector3.prototype.MaximizeInPlace = function (other) {
  652. if (other.x > this.x)
  653. this.x = other.x;
  654. if (other.y > this.y)
  655. this.y = other.y;
  656. if (other.z > this.z)
  657. this.z = other.z;
  658. return this;
  659. };
  660. // Properties
  661. Vector3.prototype.length = function () {
  662. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  663. };
  664. Vector3.prototype.lengthSquared = function () {
  665. return (this.x * this.x + this.y * this.y + this.z * this.z);
  666. };
  667. // Methods
  668. Vector3.prototype.normalize = function () {
  669. var len = this.length();
  670. if (len === 0 || len === 1.0)
  671. return this;
  672. var num = 1.0 / len;
  673. this.x *= num;
  674. this.y *= num;
  675. this.z *= num;
  676. return this;
  677. };
  678. Vector3.prototype.clone = function () {
  679. return new Vector3(this.x, this.y, this.z);
  680. };
  681. Vector3.prototype.copyFrom = function (source) {
  682. this.x = source.x;
  683. this.y = source.y;
  684. this.z = source.z;
  685. return this;
  686. };
  687. Vector3.prototype.copyFromFloats = function (x, y, z) {
  688. this.x = x;
  689. this.y = y;
  690. this.z = z;
  691. return this;
  692. };
  693. // Statics
  694. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  695. var d0 = Vector3.Dot(vector0, axis) - size;
  696. var d1 = Vector3.Dot(vector1, axis) - size;
  697. var s = d0 / (d0 - d1);
  698. return s;
  699. };
  700. Vector3.FromArray = function (array, offset) {
  701. if (!offset) {
  702. offset = 0;
  703. }
  704. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  705. };
  706. Vector3.FromFloatArray = function (array, offset) {
  707. if (!offset) {
  708. offset = 0;
  709. }
  710. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  711. };
  712. Vector3.FromArrayToRef = function (array, offset, result) {
  713. result.x = array[offset];
  714. result.y = array[offset + 1];
  715. result.z = array[offset + 2];
  716. };
  717. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  718. result.x = array[offset];
  719. result.y = array[offset + 1];
  720. result.z = array[offset + 2];
  721. };
  722. Vector3.FromFloatsToRef = function (x, y, z, result) {
  723. result.x = x;
  724. result.y = y;
  725. result.z = z;
  726. };
  727. Vector3.Zero = function () {
  728. return new Vector3(0, 0, 0);
  729. };
  730. Vector3.Up = function () {
  731. return new Vector3(0, 1.0, 0);
  732. };
  733. Vector3.TransformCoordinates = function (vector, transformation) {
  734. var result = Vector3.Zero();
  735. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  736. return result;
  737. };
  738. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  739. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  740. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  741. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  742. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  743. result.x = x / w;
  744. result.y = y / w;
  745. result.z = z / w;
  746. };
  747. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  748. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  749. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  750. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  751. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  752. result.x = rx / rw;
  753. result.y = ry / rw;
  754. result.z = rz / rw;
  755. };
  756. Vector3.TransformNormal = function (vector, transformation) {
  757. var result = Vector3.Zero();
  758. Vector3.TransformNormalToRef(vector, transformation, result);
  759. return result;
  760. };
  761. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  762. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  763. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  764. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  765. };
  766. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  767. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  768. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  769. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  770. };
  771. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  772. var squared = amount * amount;
  773. var cubed = amount * squared;
  774. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  775. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  776. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  777. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  778. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  779. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  780. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  781. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  782. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  783. return new Vector3(x, y, z);
  784. };
  785. Vector3.Clamp = function (value, min, max) {
  786. var x = value.x;
  787. x = (x > max.x) ? max.x : x;
  788. x = (x < min.x) ? min.x : x;
  789. var y = value.y;
  790. y = (y > max.y) ? max.y : y;
  791. y = (y < min.y) ? min.y : y;
  792. var z = value.z;
  793. z = (z > max.z) ? max.z : z;
  794. z = (z < min.z) ? min.z : z;
  795. return new Vector3(x, y, z);
  796. };
  797. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  798. var squared = amount * amount;
  799. var cubed = amount * squared;
  800. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  801. var part2 = (-2.0 * cubed) + (3.0 * squared);
  802. var part3 = (cubed - (2.0 * squared)) + amount;
  803. var part4 = cubed - squared;
  804. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  805. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  806. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  807. return new Vector3(x, y, z);
  808. };
  809. Vector3.Lerp = function (start, end, amount) {
  810. var x = start.x + ((end.x - start.x) * amount);
  811. var y = start.y + ((end.y - start.y) * amount);
  812. var z = start.z + ((end.z - start.z) * amount);
  813. return new Vector3(x, y, z);
  814. };
  815. Vector3.Dot = function (left, right) {
  816. return (left.x * right.x + left.y * right.y + left.z * right.z);
  817. };
  818. Vector3.Cross = function (left, right) {
  819. var result = Vector3.Zero();
  820. Vector3.CrossToRef(left, right, result);
  821. return result;
  822. };
  823. Vector3.CrossToRef = function (left, right, result) {
  824. result.x = left.y * right.z - left.z * right.y;
  825. result.y = left.z * right.x - left.x * right.z;
  826. result.z = left.x * right.y - left.y * right.x;
  827. };
  828. Vector3.Normalize = function (vector) {
  829. var result = Vector3.Zero();
  830. Vector3.NormalizeToRef(vector, result);
  831. return result;
  832. };
  833. Vector3.NormalizeToRef = function (vector, result) {
  834. result.copyFrom(vector);
  835. result.normalize();
  836. };
  837. Vector3.Project = function (vector, world, transform, viewport) {
  838. var cw = viewport.width;
  839. var ch = viewport.height;
  840. var cx = viewport.x;
  841. var cy = viewport.y;
  842. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  843. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  844. return Vector3.TransformCoordinates(vector, finalMatrix);
  845. };
  846. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  847. var matrix = world.multiply(transform);
  848. matrix.invert();
  849. source.x = source.x / viewportWidth * 2 - 1;
  850. source.y = -(source.y / viewportHeight * 2 - 1);
  851. var vector = Vector3.TransformCoordinates(source, matrix);
  852. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  853. if (MathTools.WithinEpsilon(num, 1.0)) {
  854. vector = vector.scale(1.0 / num);
  855. }
  856. return vector;
  857. };
  858. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  859. var matrix = world.multiply(view).multiply(projection);
  860. matrix.invert();
  861. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  862. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  863. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  864. if (MathTools.WithinEpsilon(num, 1.0)) {
  865. vector = vector.scale(1.0 / num);
  866. }
  867. return vector;
  868. };
  869. Vector3.Minimize = function (left, right) {
  870. var min = left.clone();
  871. min.MinimizeInPlace(right);
  872. return min;
  873. };
  874. Vector3.Maximize = function (left, right) {
  875. var max = left.clone();
  876. max.MaximizeInPlace(right);
  877. return max;
  878. };
  879. Vector3.Distance = function (value1, value2) {
  880. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  881. };
  882. Vector3.DistanceSquared = function (value1, value2) {
  883. var x = value1.x - value2.x;
  884. var y = value1.y - value2.y;
  885. var z = value1.z - value2.z;
  886. return (x * x) + (y * y) + (z * z);
  887. };
  888. Vector3.Center = function (value1, value2) {
  889. var center = value1.add(value2);
  890. center.scaleInPlace(0.5);
  891. return center;
  892. };
  893. /**
  894. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  895. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  896. * to something in order to rotate it from its local system to the given target system.
  897. */
  898. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  899. var rotation = Vector3.Zero();
  900. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  901. return rotation;
  902. };
  903. /**
  904. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  905. */
  906. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  907. var u = axis1.normalize();
  908. var w = axis3.normalize();
  909. // world axis
  910. var X = Axis.X;
  911. var Y = Axis.Y;
  912. // equation unknowns and vars
  913. var yaw = 0.0;
  914. var pitch = 0.0;
  915. var roll = 0.0;
  916. var x = 0.0;
  917. var y = 0.0;
  918. var z = 0.0;
  919. var t = 0.0;
  920. var sign = -1.0;
  921. var nbRevert = 0;
  922. var cross = Tmp.Vector3[0];
  923. var dot = 0.0;
  924. // step 1 : rotation around w
  925. // Rv3(u) = u1, and u1 belongs to plane xOz
  926. // Rv3(w) = w1 = w invariant
  927. var u1 = Tmp.Vector3[1];
  928. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  929. z = 1.0;
  930. }
  931. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  932. x = 1.0;
  933. }
  934. else {
  935. t = w.z / w.x;
  936. x = -t * Math.sqrt(1 / (1 + t * t));
  937. z = Math.sqrt(1 / (1 + t * t));
  938. }
  939. u1.x = x;
  940. u1.y = y;
  941. u1.z = z;
  942. u1.normalize();
  943. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  944. cross.normalize();
  945. if (Vector3.Dot(w, cross) < 0) {
  946. sign = 1.0;
  947. }
  948. dot = Vector3.Dot(u, u1);
  949. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  950. roll = Math.acos(dot) * sign;
  951. if (Vector3.Dot(u1, X) < 0) {
  952. roll = Math.PI + roll;
  953. u1 = u1.scaleInPlace(-1);
  954. nbRevert++;
  955. }
  956. // step 2 : rotate around u1
  957. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  958. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  959. var w2 = Tmp.Vector3[2];
  960. var v2 = Tmp.Vector3[3];
  961. x = 0.0;
  962. y = 0.0;
  963. z = 0.0;
  964. sign = -1.0;
  965. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  966. x = 1.0;
  967. }
  968. else {
  969. t = u1.z / u1.x;
  970. x = -t * Math.sqrt(1 / (1 + t * t));
  971. z = Math.sqrt(1 / (1 + t * t));
  972. }
  973. w2.x = x;
  974. w2.y = y;
  975. w2.z = z;
  976. w2.normalize();
  977. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  978. v2.normalize();
  979. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  980. cross.normalize();
  981. if (Vector3.Dot(u1, cross) < 0) {
  982. sign = 1.0;
  983. }
  984. dot = Vector3.Dot(w, w2);
  985. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  986. pitch = Math.acos(dot) * sign;
  987. if (Vector3.Dot(v2, Y) < 0) {
  988. pitch = Math.PI + pitch;
  989. nbRevert++;
  990. }
  991. // step 3 : rotate around v2
  992. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  993. sign = -1.0;
  994. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  995. cross.normalize();
  996. if (Vector3.Dot(cross, Y) < 0) {
  997. sign = 1.0;
  998. }
  999. dot = Vector3.Dot(u1, X);
  1000. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1001. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1002. if (dot < 0 && nbRevert < 2) {
  1003. yaw = Math.PI + yaw;
  1004. }
  1005. ref.x = pitch;
  1006. ref.y = yaw;
  1007. ref.z = roll;
  1008. };
  1009. return Vector3;
  1010. })();
  1011. BABYLON.Vector3 = Vector3;
  1012. //Vector4 class created for EulerAngle class conversion to Quaternion
  1013. var Vector4 = (function () {
  1014. function Vector4(x, y, z, w) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. this.w = w;
  1019. }
  1020. Vector4.prototype.toString = function () {
  1021. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1022. };
  1023. // Operators
  1024. Vector4.prototype.asArray = function () {
  1025. var result = [];
  1026. this.toArray(result, 0);
  1027. return result;
  1028. };
  1029. Vector4.prototype.toArray = function (array, index) {
  1030. if (index === undefined) {
  1031. index = 0;
  1032. }
  1033. array[index] = this.x;
  1034. array[index + 1] = this.y;
  1035. array[index + 2] = this.z;
  1036. array[index + 3] = this.w;
  1037. return this;
  1038. };
  1039. Vector4.prototype.addInPlace = function (otherVector) {
  1040. this.x += otherVector.x;
  1041. this.y += otherVector.y;
  1042. this.z += otherVector.z;
  1043. this.w += otherVector.w;
  1044. return this;
  1045. };
  1046. Vector4.prototype.add = function (otherVector) {
  1047. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1048. };
  1049. Vector4.prototype.addToRef = function (otherVector, result) {
  1050. result.x = this.x + otherVector.x;
  1051. result.y = this.y + otherVector.y;
  1052. result.z = this.z + otherVector.z;
  1053. result.w = this.w + otherVector.w;
  1054. return this;
  1055. };
  1056. Vector4.prototype.subtractInPlace = function (otherVector) {
  1057. this.x -= otherVector.x;
  1058. this.y -= otherVector.y;
  1059. this.z -= otherVector.z;
  1060. this.w -= otherVector.w;
  1061. return this;
  1062. };
  1063. Vector4.prototype.subtract = function (otherVector) {
  1064. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1065. };
  1066. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1067. result.x = this.x - otherVector.x;
  1068. result.y = this.y - otherVector.y;
  1069. result.z = this.z - otherVector.z;
  1070. result.w = this.w - otherVector.w;
  1071. return this;
  1072. };
  1073. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1074. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1075. };
  1076. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1077. result.x = this.x - x;
  1078. result.y = this.y - y;
  1079. result.z = this.z - z;
  1080. result.w = this.w - w;
  1081. return this;
  1082. };
  1083. Vector4.prototype.negate = function () {
  1084. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1085. };
  1086. Vector4.prototype.scaleInPlace = function (scale) {
  1087. this.x *= scale;
  1088. this.y *= scale;
  1089. this.z *= scale;
  1090. this.w *= scale;
  1091. return this;
  1092. };
  1093. Vector4.prototype.scale = function (scale) {
  1094. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1095. };
  1096. Vector4.prototype.scaleToRef = function (scale, result) {
  1097. result.x = this.x * scale;
  1098. result.y = this.y * scale;
  1099. result.z = this.z * scale;
  1100. result.w = this.w * scale;
  1101. };
  1102. Vector4.prototype.equals = function (otherVector) {
  1103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1104. };
  1105. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1106. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1107. return otherVector
  1108. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1109. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1110. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1111. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1112. };
  1113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1114. return this.x === x && this.y === y && this.z === z && this.w === w;
  1115. };
  1116. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1117. this.x *= otherVector.x;
  1118. this.y *= otherVector.y;
  1119. this.z *= otherVector.z;
  1120. this.w *= otherVector.w;
  1121. return this;
  1122. };
  1123. Vector4.prototype.multiply = function (otherVector) {
  1124. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1125. };
  1126. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1127. result.x = this.x * otherVector.x;
  1128. result.y = this.y * otherVector.y;
  1129. result.z = this.z * otherVector.z;
  1130. result.w = this.w * otherVector.w;
  1131. return this;
  1132. };
  1133. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1134. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1135. };
  1136. Vector4.prototype.divide = function (otherVector) {
  1137. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1138. };
  1139. Vector4.prototype.divideToRef = function (otherVector, result) {
  1140. result.x = this.x / otherVector.x;
  1141. result.y = this.y / otherVector.y;
  1142. result.z = this.z / otherVector.z;
  1143. result.w = this.w / otherVector.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.MinimizeInPlace = function (other) {
  1147. if (other.x < this.x)
  1148. this.x = other.x;
  1149. if (other.y < this.y)
  1150. this.y = other.y;
  1151. if (other.z < this.z)
  1152. this.z = other.z;
  1153. if (other.w < this.w)
  1154. this.w = other.w;
  1155. return this;
  1156. };
  1157. Vector4.prototype.MaximizeInPlace = function (other) {
  1158. if (other.x > this.x)
  1159. this.x = other.x;
  1160. if (other.y > this.y)
  1161. this.y = other.y;
  1162. if (other.z > this.z)
  1163. this.z = other.z;
  1164. if (other.w > this.w)
  1165. this.w = other.w;
  1166. return this;
  1167. };
  1168. // Properties
  1169. Vector4.prototype.length = function () {
  1170. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1171. };
  1172. Vector4.prototype.lengthSquared = function () {
  1173. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1174. };
  1175. // Methods
  1176. Vector4.prototype.normalize = function () {
  1177. var len = this.length();
  1178. if (len === 0)
  1179. return this;
  1180. var num = 1.0 / len;
  1181. this.x *= num;
  1182. this.y *= num;
  1183. this.z *= num;
  1184. this.w *= num;
  1185. return this;
  1186. };
  1187. Vector4.prototype.clone = function () {
  1188. return new Vector4(this.x, this.y, this.z, this.w);
  1189. };
  1190. Vector4.prototype.copyFrom = function (source) {
  1191. this.x = source.x;
  1192. this.y = source.y;
  1193. this.z = source.z;
  1194. this.w = source.w;
  1195. return this;
  1196. };
  1197. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1198. this.x = x;
  1199. this.y = y;
  1200. this.z = z;
  1201. this.w = w;
  1202. return this;
  1203. };
  1204. // Statics
  1205. Vector4.FromArray = function (array, offset) {
  1206. if (!offset) {
  1207. offset = 0;
  1208. }
  1209. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1210. };
  1211. Vector4.FromArrayToRef = function (array, offset, result) {
  1212. result.x = array[offset];
  1213. result.y = array[offset + 1];
  1214. result.z = array[offset + 2];
  1215. result.w = array[offset + 3];
  1216. };
  1217. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1218. result.x = array[offset];
  1219. result.y = array[offset + 1];
  1220. result.z = array[offset + 2];
  1221. result.w = array[offset + 3];
  1222. };
  1223. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1224. result.x = x;
  1225. result.y = y;
  1226. result.z = z;
  1227. result.w = w;
  1228. };
  1229. Vector4.Zero = function () {
  1230. return new Vector4(0, 0, 0, 0);
  1231. };
  1232. Vector4.Normalize = function (vector) {
  1233. var result = Vector4.Zero();
  1234. Vector4.NormalizeToRef(vector, result);
  1235. return result;
  1236. };
  1237. Vector4.NormalizeToRef = function (vector, result) {
  1238. result.copyFrom(vector);
  1239. result.normalize();
  1240. };
  1241. Vector4.Minimize = function (left, right) {
  1242. var min = left.clone();
  1243. min.MinimizeInPlace(right);
  1244. return min;
  1245. };
  1246. Vector4.Maximize = function (left, right) {
  1247. var max = left.clone();
  1248. max.MaximizeInPlace(right);
  1249. return max;
  1250. };
  1251. Vector4.Distance = function (value1, value2) {
  1252. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1253. };
  1254. Vector4.DistanceSquared = function (value1, value2) {
  1255. var x = value1.x - value2.x;
  1256. var y = value1.y - value2.y;
  1257. var z = value1.z - value2.z;
  1258. var w = value1.w - value2.w;
  1259. return (x * x) + (y * y) + (z * z) + (w * w);
  1260. };
  1261. Vector4.Center = function (value1, value2) {
  1262. var center = value1.add(value2);
  1263. center.scaleInPlace(0.5);
  1264. return center;
  1265. };
  1266. return Vector4;
  1267. })();
  1268. BABYLON.Vector4 = Vector4;
  1269. var Quaternion = (function () {
  1270. function Quaternion(x, y, z, w) {
  1271. if (x === void 0) { x = 0; }
  1272. if (y === void 0) { y = 0; }
  1273. if (z === void 0) { z = 0; }
  1274. if (w === void 0) { w = 1; }
  1275. this.x = x;
  1276. this.y = y;
  1277. this.z = z;
  1278. this.w = w;
  1279. }
  1280. Quaternion.prototype.toString = function () {
  1281. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1282. };
  1283. Quaternion.prototype.asArray = function () {
  1284. return [this.x, this.y, this.z, this.w];
  1285. };
  1286. Quaternion.prototype.equals = function (otherQuaternion) {
  1287. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1288. };
  1289. Quaternion.prototype.clone = function () {
  1290. return new Quaternion(this.x, this.y, this.z, this.w);
  1291. };
  1292. Quaternion.prototype.copyFrom = function (other) {
  1293. this.x = other.x;
  1294. this.y = other.y;
  1295. this.z = other.z;
  1296. this.w = other.w;
  1297. return this;
  1298. };
  1299. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1300. this.x = x;
  1301. this.y = y;
  1302. this.z = z;
  1303. this.w = w;
  1304. return this;
  1305. };
  1306. Quaternion.prototype.add = function (other) {
  1307. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1308. };
  1309. Quaternion.prototype.subtract = function (other) {
  1310. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1311. };
  1312. Quaternion.prototype.scale = function (value) {
  1313. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1314. };
  1315. Quaternion.prototype.multiply = function (q1) {
  1316. var result = new Quaternion(0, 0, 0, 1.0);
  1317. this.multiplyToRef(q1, result);
  1318. return result;
  1319. };
  1320. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1321. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1322. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1323. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1324. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1325. result.copyFromFloats(x, y, z, w);
  1326. return this;
  1327. };
  1328. Quaternion.prototype.multiplyInPlace = function (q1) {
  1329. this.multiplyToRef(q1, this);
  1330. return this;
  1331. };
  1332. Quaternion.prototype.conjugateToRef = function (ref) {
  1333. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1334. return this;
  1335. };
  1336. Quaternion.prototype.conjugateInPlace = function () {
  1337. this.x *= -1;
  1338. this.y *= -1;
  1339. this.z *= -1;
  1340. return this;
  1341. };
  1342. Quaternion.prototype.conjugate = function () {
  1343. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1344. return result;
  1345. };
  1346. Quaternion.prototype.length = function () {
  1347. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1348. };
  1349. Quaternion.prototype.normalize = function () {
  1350. var length = 1.0 / this.length();
  1351. this.x *= length;
  1352. this.y *= length;
  1353. this.z *= length;
  1354. this.w *= length;
  1355. return this;
  1356. };
  1357. Quaternion.prototype.toEulerAngles = function (order) {
  1358. if (order === void 0) { order = "YZX"; }
  1359. var result = Vector3.Zero();
  1360. this.toEulerAnglesToRef(result, order);
  1361. return result;
  1362. };
  1363. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1364. if (order === void 0) { order = "YZX"; }
  1365. var heading, attitude, bank;
  1366. var x = this.x, y = this.y, z = this.z, w = this.w;
  1367. switch (order) {
  1368. case "YZX":
  1369. var test = x * y + z * w;
  1370. if (test > 0.499) {
  1371. heading = 2 * Math.atan2(x, w);
  1372. attitude = Math.PI / 2;
  1373. bank = 0;
  1374. }
  1375. if (test < -0.499) {
  1376. heading = -2 * Math.atan2(x, w);
  1377. attitude = -Math.PI / 2;
  1378. bank = 0;
  1379. }
  1380. if (isNaN(heading)) {
  1381. var sqx = x * x;
  1382. var sqy = y * y;
  1383. var sqz = z * z;
  1384. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1385. attitude = Math.asin(2 * test); // attitude
  1386. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1387. }
  1388. break;
  1389. default:
  1390. throw new Error("Euler order " + order + " not supported yet.");
  1391. }
  1392. result.y = heading;
  1393. result.z = attitude;
  1394. result.x = bank;
  1395. return this;
  1396. };
  1397. ;
  1398. Quaternion.prototype.toRotationMatrix = function (result) {
  1399. var xx = this.x * this.x;
  1400. var yy = this.y * this.y;
  1401. var zz = this.z * this.z;
  1402. var xy = this.x * this.y;
  1403. var zw = this.z * this.w;
  1404. var zx = this.z * this.x;
  1405. var yw = this.y * this.w;
  1406. var yz = this.y * this.z;
  1407. var xw = this.x * this.w;
  1408. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1409. result.m[1] = 2.0 * (xy + zw);
  1410. result.m[2] = 2.0 * (zx - yw);
  1411. result.m[3] = 0;
  1412. result.m[4] = 2.0 * (xy - zw);
  1413. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1414. result.m[6] = 2.0 * (yz + xw);
  1415. result.m[7] = 0;
  1416. result.m[8] = 2.0 * (zx + yw);
  1417. result.m[9] = 2.0 * (yz - xw);
  1418. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1419. result.m[11] = 0;
  1420. result.m[12] = 0;
  1421. result.m[13] = 0;
  1422. result.m[14] = 0;
  1423. result.m[15] = 1.0;
  1424. return this;
  1425. };
  1426. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1427. Quaternion.FromRotationMatrixToRef(matrix, this);
  1428. return this;
  1429. };
  1430. // Statics
  1431. Quaternion.FromRotationMatrix = function (matrix) {
  1432. var result = new Quaternion();
  1433. Quaternion.FromRotationMatrixToRef(matrix, result);
  1434. return result;
  1435. };
  1436. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1437. var data = matrix.m;
  1438. var m11 = data[0], m12 = data[4], m13 = data[8];
  1439. var m21 = data[1], m22 = data[5], m23 = data[9];
  1440. var m31 = data[2], m32 = data[6], m33 = data[10];
  1441. var trace = m11 + m22 + m33;
  1442. var s;
  1443. if (trace > 0) {
  1444. s = 0.5 / Math.sqrt(trace + 1.0);
  1445. result.w = 0.25 / s;
  1446. result.x = (m32 - m23) * s;
  1447. result.y = (m13 - m31) * s;
  1448. result.z = (m21 - m12) * s;
  1449. }
  1450. else if (m11 > m22 && m11 > m33) {
  1451. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1452. result.w = (m32 - m23) / s;
  1453. result.x = 0.25 * s;
  1454. result.y = (m12 + m21) / s;
  1455. result.z = (m13 + m31) / s;
  1456. }
  1457. else if (m22 > m33) {
  1458. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1459. result.w = (m13 - m31) / s;
  1460. result.x = (m12 + m21) / s;
  1461. result.y = 0.25 * s;
  1462. result.z = (m23 + m32) / s;
  1463. }
  1464. else {
  1465. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1466. result.w = (m21 - m12) / s;
  1467. result.x = (m13 + m31) / s;
  1468. result.y = (m23 + m32) / s;
  1469. result.z = 0.25 * s;
  1470. }
  1471. };
  1472. Quaternion.Inverse = function (q) {
  1473. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1474. };
  1475. Quaternion.Identity = function () {
  1476. return new Quaternion(0, 0, 0, 1);
  1477. };
  1478. Quaternion.RotationAxis = function (axis, angle) {
  1479. var result = new Quaternion();
  1480. var sin = Math.sin(angle / 2);
  1481. axis.normalize();
  1482. result.w = Math.cos(angle / 2);
  1483. result.x = axis.x * sin;
  1484. result.y = axis.y * sin;
  1485. result.z = axis.z * sin;
  1486. return result;
  1487. };
  1488. Quaternion.FromArray = function (array, offset) {
  1489. if (!offset) {
  1490. offset = 0;
  1491. }
  1492. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1493. };
  1494. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1495. var result = new Quaternion();
  1496. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1497. return result;
  1498. };
  1499. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1500. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1501. var halfRoll = roll * 0.5;
  1502. var halfPitch = pitch * 0.5;
  1503. var halfYaw = yaw * 0.5;
  1504. var sinRoll = Math.sin(halfRoll);
  1505. var cosRoll = Math.cos(halfRoll);
  1506. var sinPitch = Math.sin(halfPitch);
  1507. var cosPitch = Math.cos(halfPitch);
  1508. var sinYaw = Math.sin(halfYaw);
  1509. var cosYaw = Math.cos(halfYaw);
  1510. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1511. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1512. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1513. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1514. };
  1515. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1516. var result = new Quaternion();
  1517. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1518. return result;
  1519. };
  1520. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1521. // Produces a quaternion from Euler angles in the z-x-z orientation
  1522. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1523. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1524. var halfBeta = beta * 0.5;
  1525. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1526. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1527. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1528. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1529. };
  1530. Quaternion.Slerp = function (left, right, amount) {
  1531. var num2;
  1532. var num3;
  1533. var num = amount;
  1534. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1535. var flag = false;
  1536. if (num4 < 0) {
  1537. flag = true;
  1538. num4 = -num4;
  1539. }
  1540. if (num4 > 0.999999) {
  1541. num3 = 1 - num;
  1542. num2 = flag ? -num : num;
  1543. }
  1544. else {
  1545. var num5 = Math.acos(num4);
  1546. var num6 = (1.0 / Math.sin(num5));
  1547. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1548. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1549. }
  1550. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1551. };
  1552. return Quaternion;
  1553. })();
  1554. BABYLON.Quaternion = Quaternion;
  1555. var Matrix = (function () {
  1556. function Matrix() {
  1557. this.m = new Float32Array(16);
  1558. }
  1559. // Properties
  1560. Matrix.prototype.isIdentity = function () {
  1561. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1562. return false;
  1563. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1564. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1565. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1566. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1567. return false;
  1568. return true;
  1569. };
  1570. Matrix.prototype.determinant = function () {
  1571. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1572. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1573. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1574. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1575. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1576. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1577. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1578. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1579. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1580. };
  1581. // Methods
  1582. Matrix.prototype.toArray = function () {
  1583. return this.m;
  1584. };
  1585. Matrix.prototype.asArray = function () {
  1586. return this.toArray();
  1587. };
  1588. Matrix.prototype.invert = function () {
  1589. this.invertToRef(this);
  1590. return this;
  1591. };
  1592. Matrix.prototype.reset = function () {
  1593. for (var index = 0; index < 16; index++) {
  1594. this.m[index] = 0;
  1595. }
  1596. return this;
  1597. };
  1598. Matrix.prototype.add = function (other) {
  1599. var result = new Matrix();
  1600. this.addToRef(other, result);
  1601. return result;
  1602. };
  1603. Matrix.prototype.addToRef = function (other, result) {
  1604. for (var index = 0; index < 16; index++) {
  1605. result.m[index] = this.m[index] + other.m[index];
  1606. }
  1607. return this;
  1608. };
  1609. Matrix.prototype.addToSelf = function (other) {
  1610. for (var index = 0; index < 16; index++) {
  1611. this.m[index] += other.m[index];
  1612. }
  1613. return this;
  1614. };
  1615. Matrix.prototype.invertToRef = function (other) {
  1616. var l1 = this.m[0];
  1617. var l2 = this.m[1];
  1618. var l3 = this.m[2];
  1619. var l4 = this.m[3];
  1620. var l5 = this.m[4];
  1621. var l6 = this.m[5];
  1622. var l7 = this.m[6];
  1623. var l8 = this.m[7];
  1624. var l9 = this.m[8];
  1625. var l10 = this.m[9];
  1626. var l11 = this.m[10];
  1627. var l12 = this.m[11];
  1628. var l13 = this.m[12];
  1629. var l14 = this.m[13];
  1630. var l15 = this.m[14];
  1631. var l16 = this.m[15];
  1632. var l17 = (l11 * l16) - (l12 * l15);
  1633. var l18 = (l10 * l16) - (l12 * l14);
  1634. var l19 = (l10 * l15) - (l11 * l14);
  1635. var l20 = (l9 * l16) - (l12 * l13);
  1636. var l21 = (l9 * l15) - (l11 * l13);
  1637. var l22 = (l9 * l14) - (l10 * l13);
  1638. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1639. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1640. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1641. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1642. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1643. var l28 = (l7 * l16) - (l8 * l15);
  1644. var l29 = (l6 * l16) - (l8 * l14);
  1645. var l30 = (l6 * l15) - (l7 * l14);
  1646. var l31 = (l5 * l16) - (l8 * l13);
  1647. var l32 = (l5 * l15) - (l7 * l13);
  1648. var l33 = (l5 * l14) - (l6 * l13);
  1649. var l34 = (l7 * l12) - (l8 * l11);
  1650. var l35 = (l6 * l12) - (l8 * l10);
  1651. var l36 = (l6 * l11) - (l7 * l10);
  1652. var l37 = (l5 * l12) - (l8 * l9);
  1653. var l38 = (l5 * l11) - (l7 * l9);
  1654. var l39 = (l5 * l10) - (l6 * l9);
  1655. other.m[0] = l23 * l27;
  1656. other.m[4] = l24 * l27;
  1657. other.m[8] = l25 * l27;
  1658. other.m[12] = l26 * l27;
  1659. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1660. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1661. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1662. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1663. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1664. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1665. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1666. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1667. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1668. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1669. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1670. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1671. return this;
  1672. };
  1673. Matrix.prototype.setTranslation = function (vector3) {
  1674. this.m[12] = vector3.x;
  1675. this.m[13] = vector3.y;
  1676. this.m[14] = vector3.z;
  1677. return this;
  1678. };
  1679. Matrix.prototype.multiply = function (other) {
  1680. var result = new Matrix();
  1681. this.multiplyToRef(other, result);
  1682. return result;
  1683. };
  1684. Matrix.prototype.copyFrom = function (other) {
  1685. for (var index = 0; index < 16; index++) {
  1686. this.m[index] = other.m[index];
  1687. }
  1688. return this;
  1689. };
  1690. Matrix.prototype.copyToArray = function (array, offset) {
  1691. if (offset === void 0) { offset = 0; }
  1692. for (var index = 0; index < 16; index++) {
  1693. array[offset + index] = this.m[index];
  1694. }
  1695. return this;
  1696. };
  1697. Matrix.prototype.multiplyToRef = function (other, result) {
  1698. this.multiplyToArray(other, result.m, 0);
  1699. return this;
  1700. };
  1701. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1702. var tm0 = this.m[0];
  1703. var tm1 = this.m[1];
  1704. var tm2 = this.m[2];
  1705. var tm3 = this.m[3];
  1706. var tm4 = this.m[4];
  1707. var tm5 = this.m[5];
  1708. var tm6 = this.m[6];
  1709. var tm7 = this.m[7];
  1710. var tm8 = this.m[8];
  1711. var tm9 = this.m[9];
  1712. var tm10 = this.m[10];
  1713. var tm11 = this.m[11];
  1714. var tm12 = this.m[12];
  1715. var tm13 = this.m[13];
  1716. var tm14 = this.m[14];
  1717. var tm15 = this.m[15];
  1718. var om0 = other.m[0];
  1719. var om1 = other.m[1];
  1720. var om2 = other.m[2];
  1721. var om3 = other.m[3];
  1722. var om4 = other.m[4];
  1723. var om5 = other.m[5];
  1724. var om6 = other.m[6];
  1725. var om7 = other.m[7];
  1726. var om8 = other.m[8];
  1727. var om9 = other.m[9];
  1728. var om10 = other.m[10];
  1729. var om11 = other.m[11];
  1730. var om12 = other.m[12];
  1731. var om13 = other.m[13];
  1732. var om14 = other.m[14];
  1733. var om15 = other.m[15];
  1734. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1735. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1736. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1737. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1738. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1739. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1740. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1741. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1742. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1743. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1744. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1745. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1746. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1747. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1748. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1749. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1750. return this;
  1751. };
  1752. Matrix.prototype.equals = function (value) {
  1753. return value &&
  1754. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1755. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1756. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1757. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1758. };
  1759. Matrix.prototype.clone = function () {
  1760. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1761. };
  1762. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1763. translation.x = this.m[12];
  1764. translation.y = this.m[13];
  1765. translation.z = this.m[14];
  1766. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1767. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1768. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1769. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1770. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1771. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1772. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1773. rotation.x = 0;
  1774. rotation.y = 0;
  1775. rotation.z = 0;
  1776. rotation.w = 1;
  1777. return false;
  1778. }
  1779. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1780. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1781. return true;
  1782. };
  1783. // Statics
  1784. Matrix.FromArray = function (array, offset) {
  1785. var result = new Matrix();
  1786. if (!offset) {
  1787. offset = 0;
  1788. }
  1789. Matrix.FromArrayToRef(array, offset, result);
  1790. return result;
  1791. };
  1792. Matrix.FromArrayToRef = function (array, offset, result) {
  1793. for (var index = 0; index < 16; index++) {
  1794. result.m[index] = array[index + offset];
  1795. }
  1796. };
  1797. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = array[index + offset] * scale;
  1800. }
  1801. };
  1802. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1803. result.m[0] = initialM11;
  1804. result.m[1] = initialM12;
  1805. result.m[2] = initialM13;
  1806. result.m[3] = initialM14;
  1807. result.m[4] = initialM21;
  1808. result.m[5] = initialM22;
  1809. result.m[6] = initialM23;
  1810. result.m[7] = initialM24;
  1811. result.m[8] = initialM31;
  1812. result.m[9] = initialM32;
  1813. result.m[10] = initialM33;
  1814. result.m[11] = initialM34;
  1815. result.m[12] = initialM41;
  1816. result.m[13] = initialM42;
  1817. result.m[14] = initialM43;
  1818. result.m[15] = initialM44;
  1819. };
  1820. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1821. var result = new Matrix();
  1822. result.m[0] = initialM11;
  1823. result.m[1] = initialM12;
  1824. result.m[2] = initialM13;
  1825. result.m[3] = initialM14;
  1826. result.m[4] = initialM21;
  1827. result.m[5] = initialM22;
  1828. result.m[6] = initialM23;
  1829. result.m[7] = initialM24;
  1830. result.m[8] = initialM31;
  1831. result.m[9] = initialM32;
  1832. result.m[10] = initialM33;
  1833. result.m[11] = initialM34;
  1834. result.m[12] = initialM41;
  1835. result.m[13] = initialM42;
  1836. result.m[14] = initialM43;
  1837. result.m[15] = initialM44;
  1838. return result;
  1839. };
  1840. Matrix.Compose = function (scale, rotation, translation) {
  1841. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1842. var rotationMatrix = Matrix.Identity();
  1843. rotation.toRotationMatrix(rotationMatrix);
  1844. result = result.multiply(rotationMatrix);
  1845. result.setTranslation(translation);
  1846. return result;
  1847. };
  1848. Matrix.Identity = function () {
  1849. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1850. };
  1851. Matrix.IdentityToRef = function (result) {
  1852. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1853. };
  1854. Matrix.Zero = function () {
  1855. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1856. };
  1857. Matrix.RotationX = function (angle) {
  1858. var result = new Matrix();
  1859. Matrix.RotationXToRef(angle, result);
  1860. return result;
  1861. };
  1862. Matrix.Invert = function (source) {
  1863. var result = new Matrix();
  1864. source.invertToRef(result);
  1865. return result;
  1866. };
  1867. Matrix.RotationXToRef = function (angle, result) {
  1868. var s = Math.sin(angle);
  1869. var c = Math.cos(angle);
  1870. result.m[0] = 1.0;
  1871. result.m[15] = 1.0;
  1872. result.m[5] = c;
  1873. result.m[10] = c;
  1874. result.m[9] = -s;
  1875. result.m[6] = s;
  1876. result.m[1] = 0;
  1877. result.m[2] = 0;
  1878. result.m[3] = 0;
  1879. result.m[4] = 0;
  1880. result.m[7] = 0;
  1881. result.m[8] = 0;
  1882. result.m[11] = 0;
  1883. result.m[12] = 0;
  1884. result.m[13] = 0;
  1885. result.m[14] = 0;
  1886. };
  1887. Matrix.RotationY = function (angle) {
  1888. var result = new Matrix();
  1889. Matrix.RotationYToRef(angle, result);
  1890. return result;
  1891. };
  1892. Matrix.RotationYToRef = function (angle, result) {
  1893. var s = Math.sin(angle);
  1894. var c = Math.cos(angle);
  1895. result.m[5] = 1.0;
  1896. result.m[15] = 1.0;
  1897. result.m[0] = c;
  1898. result.m[2] = -s;
  1899. result.m[8] = s;
  1900. result.m[10] = c;
  1901. result.m[1] = 0;
  1902. result.m[3] = 0;
  1903. result.m[4] = 0;
  1904. result.m[6] = 0;
  1905. result.m[7] = 0;
  1906. result.m[9] = 0;
  1907. result.m[11] = 0;
  1908. result.m[12] = 0;
  1909. result.m[13] = 0;
  1910. result.m[14] = 0;
  1911. };
  1912. Matrix.RotationZ = function (angle) {
  1913. var result = new Matrix();
  1914. Matrix.RotationZToRef(angle, result);
  1915. return result;
  1916. };
  1917. Matrix.RotationZToRef = function (angle, result) {
  1918. var s = Math.sin(angle);
  1919. var c = Math.cos(angle);
  1920. result.m[10] = 1.0;
  1921. result.m[15] = 1.0;
  1922. result.m[0] = c;
  1923. result.m[1] = s;
  1924. result.m[4] = -s;
  1925. result.m[5] = c;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[6] = 0;
  1929. result.m[7] = 0;
  1930. result.m[8] = 0;
  1931. result.m[9] = 0;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. };
  1937. Matrix.RotationAxis = function (axis, angle) {
  1938. var result = Matrix.Zero();
  1939. Matrix.RotationAxisToRef(axis, angle, result);
  1940. return result;
  1941. };
  1942. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1943. var s = Math.sin(-angle);
  1944. var c = Math.cos(-angle);
  1945. var c1 = 1 - c;
  1946. axis.normalize();
  1947. result.m[0] = (axis.x * axis.x) * c1 + c;
  1948. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1949. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1950. result.m[3] = 0.0;
  1951. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1952. result.m[5] = (axis.y * axis.y) * c1 + c;
  1953. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1954. result.m[7] = 0.0;
  1955. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1956. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1957. result.m[10] = (axis.z * axis.z) * c1 + c;
  1958. result.m[11] = 0.0;
  1959. result.m[15] = 1.0;
  1960. };
  1961. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1962. var result = new Matrix();
  1963. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1964. return result;
  1965. };
  1966. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1967. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1968. this._tempQuaternion.toRotationMatrix(result);
  1969. };
  1970. Matrix.Scaling = function (x, y, z) {
  1971. var result = Matrix.Zero();
  1972. Matrix.ScalingToRef(x, y, z, result);
  1973. return result;
  1974. };
  1975. Matrix.ScalingToRef = function (x, y, z, result) {
  1976. result.m[0] = x;
  1977. result.m[1] = 0;
  1978. result.m[2] = 0;
  1979. result.m[3] = 0;
  1980. result.m[4] = 0;
  1981. result.m[5] = y;
  1982. result.m[6] = 0;
  1983. result.m[7] = 0;
  1984. result.m[8] = 0;
  1985. result.m[9] = 0;
  1986. result.m[10] = z;
  1987. result.m[11] = 0;
  1988. result.m[12] = 0;
  1989. result.m[13] = 0;
  1990. result.m[14] = 0;
  1991. result.m[15] = 1.0;
  1992. };
  1993. Matrix.Translation = function (x, y, z) {
  1994. var result = Matrix.Identity();
  1995. Matrix.TranslationToRef(x, y, z, result);
  1996. return result;
  1997. };
  1998. Matrix.TranslationToRef = function (x, y, z, result) {
  1999. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2000. };
  2001. Matrix.Lerp = function (startValue, endValue, gradient) {
  2002. var startScale = new Vector3(0, 0, 0);
  2003. var startRotation = new Quaternion();
  2004. var startTranslation = new Vector3(0, 0, 0);
  2005. startValue.decompose(startScale, startRotation, startTranslation);
  2006. var endScale = new Vector3(0, 0, 0);
  2007. var endRotation = new Quaternion();
  2008. var endTranslation = new Vector3(0, 0, 0);
  2009. endValue.decompose(endScale, endRotation, endTranslation);
  2010. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2011. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2012. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2013. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2014. };
  2015. Matrix.LookAtLH = function (eye, target, up) {
  2016. var result = Matrix.Zero();
  2017. Matrix.LookAtLHToRef(eye, target, up, result);
  2018. return result;
  2019. };
  2020. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2021. // Z axis
  2022. target.subtractToRef(eye, this._zAxis);
  2023. this._zAxis.normalize();
  2024. // X axis
  2025. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2026. if (this._xAxis.lengthSquared() === 0) {
  2027. this._xAxis.x = 1.0;
  2028. }
  2029. else {
  2030. this._xAxis.normalize();
  2031. }
  2032. // Y axis
  2033. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2034. this._yAxis.normalize();
  2035. // Eye angles
  2036. var ex = -Vector3.Dot(this._xAxis, eye);
  2037. var ey = -Vector3.Dot(this._yAxis, eye);
  2038. var ez = -Vector3.Dot(this._zAxis, eye);
  2039. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2040. };
  2041. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2042. var matrix = Matrix.Zero();
  2043. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2044. return matrix;
  2045. };
  2046. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2047. var hw = 2.0 / width;
  2048. var hh = 2.0 / height;
  2049. var id = 1.0 / (zfar - znear);
  2050. var nid = znear / (znear - zfar);
  2051. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2052. };
  2053. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2054. var matrix = Matrix.Zero();
  2055. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2056. return matrix;
  2057. };
  2058. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2059. result.m[0] = 2.0 / (right - left);
  2060. result.m[1] = result.m[2] = result.m[3] = 0;
  2061. result.m[5] = 2.0 / (top - bottom);
  2062. result.m[4] = result.m[6] = result.m[7] = 0;
  2063. result.m[10] = -1.0 / (znear - zfar);
  2064. result.m[8] = result.m[9] = result.m[11] = 0;
  2065. result.m[12] = (left + right) / (left - right);
  2066. result.m[13] = (top + bottom) / (bottom - top);
  2067. result.m[14] = znear / (znear - zfar);
  2068. result.m[15] = 1.0;
  2069. };
  2070. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2071. var matrix = Matrix.Zero();
  2072. matrix.m[0] = (2.0 * znear) / width;
  2073. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2074. matrix.m[5] = (2.0 * znear) / height;
  2075. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2076. matrix.m[10] = -zfar / (znear - zfar);
  2077. matrix.m[8] = matrix.m[9] = 0.0;
  2078. matrix.m[11] = 1.0;
  2079. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2080. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2081. return matrix;
  2082. };
  2083. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2084. var matrix = Matrix.Zero();
  2085. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2086. return matrix;
  2087. };
  2088. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2089. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2090. var tan = 1.0 / (Math.tan(fov * 0.5));
  2091. if (isVerticalFovFixed) {
  2092. result.m[0] = tan / aspect;
  2093. }
  2094. else {
  2095. result.m[0] = tan;
  2096. }
  2097. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2098. if (isVerticalFovFixed) {
  2099. result.m[5] = tan;
  2100. }
  2101. else {
  2102. result.m[5] = tan * aspect;
  2103. }
  2104. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2105. result.m[8] = result.m[9] = 0.0;
  2106. result.m[10] = -zfar / (znear - zfar);
  2107. result.m[11] = 1.0;
  2108. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2109. result.m[14] = (znear * zfar) / (znear - zfar);
  2110. };
  2111. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2112. var cw = viewport.width;
  2113. var ch = viewport.height;
  2114. var cx = viewport.x;
  2115. var cy = viewport.y;
  2116. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2117. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2118. };
  2119. Matrix.GetAsMatrix2x2 = function (matrix) {
  2120. return new Float32Array([
  2121. matrix.m[0], matrix.m[1],
  2122. matrix.m[4], matrix.m[5]
  2123. ]);
  2124. };
  2125. Matrix.GetAsMatrix3x3 = function (matrix) {
  2126. return new Float32Array([
  2127. matrix.m[0], matrix.m[1], matrix.m[2],
  2128. matrix.m[4], matrix.m[5], matrix.m[6],
  2129. matrix.m[8], matrix.m[9], matrix.m[10]
  2130. ]);
  2131. };
  2132. Matrix.Transpose = function (matrix) {
  2133. var result = new Matrix();
  2134. result.m[0] = matrix.m[0];
  2135. result.m[1] = matrix.m[4];
  2136. result.m[2] = matrix.m[8];
  2137. result.m[3] = matrix.m[12];
  2138. result.m[4] = matrix.m[1];
  2139. result.m[5] = matrix.m[5];
  2140. result.m[6] = matrix.m[9];
  2141. result.m[7] = matrix.m[13];
  2142. result.m[8] = matrix.m[2];
  2143. result.m[9] = matrix.m[6];
  2144. result.m[10] = matrix.m[10];
  2145. result.m[11] = matrix.m[14];
  2146. result.m[12] = matrix.m[3];
  2147. result.m[13] = matrix.m[7];
  2148. result.m[14] = matrix.m[11];
  2149. result.m[15] = matrix.m[15];
  2150. return result;
  2151. };
  2152. Matrix.Reflection = function (plane) {
  2153. var matrix = new Matrix();
  2154. Matrix.ReflectionToRef(plane, matrix);
  2155. return matrix;
  2156. };
  2157. Matrix.ReflectionToRef = function (plane, result) {
  2158. plane.normalize();
  2159. var x = plane.normal.x;
  2160. var y = plane.normal.y;
  2161. var z = plane.normal.z;
  2162. var temp = -2 * x;
  2163. var temp2 = -2 * y;
  2164. var temp3 = -2 * z;
  2165. result.m[0] = (temp * x) + 1;
  2166. result.m[1] = temp2 * x;
  2167. result.m[2] = temp3 * x;
  2168. result.m[3] = 0.0;
  2169. result.m[4] = temp * y;
  2170. result.m[5] = (temp2 * y) + 1;
  2171. result.m[6] = temp3 * y;
  2172. result.m[7] = 0.0;
  2173. result.m[8] = temp * z;
  2174. result.m[9] = temp2 * z;
  2175. result.m[10] = (temp3 * z) + 1;
  2176. result.m[11] = 0.0;
  2177. result.m[12] = temp * plane.d;
  2178. result.m[13] = temp2 * plane.d;
  2179. result.m[14] = temp3 * plane.d;
  2180. result.m[15] = 1.0;
  2181. };
  2182. Matrix._tempQuaternion = new Quaternion();
  2183. Matrix._xAxis = Vector3.Zero();
  2184. Matrix._yAxis = Vector3.Zero();
  2185. Matrix._zAxis = Vector3.Zero();
  2186. return Matrix;
  2187. })();
  2188. BABYLON.Matrix = Matrix;
  2189. var Plane = (function () {
  2190. function Plane(a, b, c, d) {
  2191. this.normal = new Vector3(a, b, c);
  2192. this.d = d;
  2193. }
  2194. Plane.prototype.asArray = function () {
  2195. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2196. };
  2197. // Methods
  2198. Plane.prototype.clone = function () {
  2199. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2200. };
  2201. Plane.prototype.normalize = function () {
  2202. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2203. var magnitude = 0;
  2204. if (norm !== 0) {
  2205. magnitude = 1.0 / norm;
  2206. }
  2207. this.normal.x *= magnitude;
  2208. this.normal.y *= magnitude;
  2209. this.normal.z *= magnitude;
  2210. this.d *= magnitude;
  2211. return this;
  2212. };
  2213. Plane.prototype.transform = function (transformation) {
  2214. var transposedMatrix = Matrix.Transpose(transformation);
  2215. var x = this.normal.x;
  2216. var y = this.normal.y;
  2217. var z = this.normal.z;
  2218. var d = this.d;
  2219. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2220. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2221. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2222. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2223. return new Plane(normalX, normalY, normalZ, finalD);
  2224. };
  2225. Plane.prototype.dotCoordinate = function (point) {
  2226. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2227. };
  2228. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2229. var x1 = point2.x - point1.x;
  2230. var y1 = point2.y - point1.y;
  2231. var z1 = point2.z - point1.z;
  2232. var x2 = point3.x - point1.x;
  2233. var y2 = point3.y - point1.y;
  2234. var z2 = point3.z - point1.z;
  2235. var yz = (y1 * z2) - (z1 * y2);
  2236. var xz = (z1 * x2) - (x1 * z2);
  2237. var xy = (x1 * y2) - (y1 * x2);
  2238. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2239. var invPyth;
  2240. if (pyth !== 0) {
  2241. invPyth = 1.0 / pyth;
  2242. }
  2243. else {
  2244. invPyth = 0;
  2245. }
  2246. this.normal.x = yz * invPyth;
  2247. this.normal.y = xz * invPyth;
  2248. this.normal.z = xy * invPyth;
  2249. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2250. return this;
  2251. };
  2252. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2253. var dot = Vector3.Dot(this.normal, direction);
  2254. return (dot <= epsilon);
  2255. };
  2256. Plane.prototype.signedDistanceTo = function (point) {
  2257. return Vector3.Dot(point, this.normal) + this.d;
  2258. };
  2259. // Statics
  2260. Plane.FromArray = function (array) {
  2261. return new Plane(array[0], array[1], array[2], array[3]);
  2262. };
  2263. Plane.FromPoints = function (point1, point2, point3) {
  2264. var result = new Plane(0, 0, 0, 0);
  2265. result.copyFromPoints(point1, point2, point3);
  2266. return result;
  2267. };
  2268. Plane.FromPositionAndNormal = function (origin, normal) {
  2269. var result = new Plane(0, 0, 0, 0);
  2270. normal.normalize();
  2271. result.normal = normal;
  2272. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2273. return result;
  2274. };
  2275. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2276. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2277. return Vector3.Dot(point, normal) + d;
  2278. };
  2279. return Plane;
  2280. })();
  2281. BABYLON.Plane = Plane;
  2282. var Viewport = (function () {
  2283. function Viewport(x, y, width, height) {
  2284. this.x = x;
  2285. this.y = y;
  2286. this.width = width;
  2287. this.height = height;
  2288. }
  2289. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2290. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2291. };
  2292. return Viewport;
  2293. })();
  2294. BABYLON.Viewport = Viewport;
  2295. var Frustum = (function () {
  2296. function Frustum() {
  2297. }
  2298. Frustum.GetPlanes = function (transform) {
  2299. var frustumPlanes = [];
  2300. for (var index = 0; index < 6; index++) {
  2301. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2302. }
  2303. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2304. return frustumPlanes;
  2305. };
  2306. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2307. // Near
  2308. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2309. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2310. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2311. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2312. frustumPlanes[0].normalize();
  2313. // Far
  2314. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2315. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2316. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2317. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2318. frustumPlanes[1].normalize();
  2319. // Left
  2320. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2321. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2322. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2323. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2324. frustumPlanes[2].normalize();
  2325. // Right
  2326. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2327. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2328. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2329. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2330. frustumPlanes[3].normalize();
  2331. // Top
  2332. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2333. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2334. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2335. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2336. frustumPlanes[4].normalize();
  2337. // Bottom
  2338. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2339. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2340. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2341. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2342. frustumPlanes[5].normalize();
  2343. };
  2344. return Frustum;
  2345. })();
  2346. BABYLON.Frustum = Frustum;
  2347. (function (Space) {
  2348. Space[Space["LOCAL"] = 0] = "LOCAL";
  2349. Space[Space["WORLD"] = 1] = "WORLD";
  2350. })(BABYLON.Space || (BABYLON.Space = {}));
  2351. var Space = BABYLON.Space;
  2352. var Axis = (function () {
  2353. function Axis() {
  2354. }
  2355. Axis.X = new Vector3(1, 0, 0);
  2356. Axis.Y = new Vector3(0, 1, 0);
  2357. Axis.Z = new Vector3(0, 0, 1);
  2358. return Axis;
  2359. })();
  2360. BABYLON.Axis = Axis;
  2361. ;
  2362. var BezierCurve = (function () {
  2363. function BezierCurve() {
  2364. }
  2365. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2366. // Extract X (which is equal to time here)
  2367. var f0 = 1 - 3 * x2 + 3 * x1;
  2368. var f1 = 3 * x2 - 6 * x1;
  2369. var f2 = 3 * x1;
  2370. var refinedT = t;
  2371. for (var i = 0; i < 5; i++) {
  2372. var refinedT2 = refinedT * refinedT;
  2373. var refinedT3 = refinedT2 * refinedT;
  2374. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2375. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2376. refinedT -= (x - t) * slope;
  2377. refinedT = Math.min(1, Math.max(0, refinedT));
  2378. }
  2379. // Resolve cubic bezier for the given x
  2380. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2381. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2382. Math.pow(refinedT, 3);
  2383. };
  2384. return BezierCurve;
  2385. })();
  2386. BABYLON.BezierCurve = BezierCurve;
  2387. (function (Orientation) {
  2388. Orientation[Orientation["CW"] = 0] = "CW";
  2389. Orientation[Orientation["CCW"] = 1] = "CCW";
  2390. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2391. var Orientation = BABYLON.Orientation;
  2392. var Angle = (function () {
  2393. function Angle(radians) {
  2394. var _this = this;
  2395. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2396. this.radians = function () { return _this._radians; };
  2397. this._radians = radians;
  2398. if (this._radians < 0)
  2399. this._radians += (2 * Math.PI);
  2400. }
  2401. Angle.BetweenTwoPoints = function (a, b) {
  2402. var delta = b.subtract(a);
  2403. var theta = Math.atan2(delta.y, delta.x);
  2404. return new Angle(theta);
  2405. };
  2406. Angle.FromRadians = function (radians) {
  2407. return new Angle(radians);
  2408. };
  2409. Angle.FromDegrees = function (degrees) {
  2410. return new Angle(degrees * Math.PI / 180);
  2411. };
  2412. return Angle;
  2413. })();
  2414. BABYLON.Angle = Angle;
  2415. var Arc2 = (function () {
  2416. function Arc2(startPoint, midPoint, endPoint) {
  2417. this.startPoint = startPoint;
  2418. this.midPoint = midPoint;
  2419. this.endPoint = endPoint;
  2420. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2421. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2422. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2423. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2424. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2425. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2426. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2427. var a1 = this.startAngle.degrees();
  2428. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2429. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2430. // angles correction
  2431. if (a2 - a1 > +180.0)
  2432. a2 -= 360.0;
  2433. if (a2 - a1 < -180.0)
  2434. a2 += 360.0;
  2435. if (a3 - a2 > +180.0)
  2436. a3 -= 360.0;
  2437. if (a3 - a2 < -180.0)
  2438. a3 += 360.0;
  2439. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2440. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2441. }
  2442. return Arc2;
  2443. })();
  2444. BABYLON.Arc2 = Arc2;
  2445. var Path2 = (function () {
  2446. function Path2(x, y) {
  2447. this._points = new Array();
  2448. this._length = 0;
  2449. this.closed = false;
  2450. this._points.push(new Vector2(x, y));
  2451. }
  2452. Path2.prototype.addLineTo = function (x, y) {
  2453. if (closed) {
  2454. //Tools.Error("cannot add lines to closed paths");
  2455. return this;
  2456. }
  2457. var newPoint = new Vector2(x, y);
  2458. var previousPoint = this._points[this._points.length - 1];
  2459. this._points.push(newPoint);
  2460. this._length += newPoint.subtract(previousPoint).length();
  2461. return this;
  2462. };
  2463. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2464. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2465. if (closed) {
  2466. //Tools.Error("cannot add arcs to closed paths");
  2467. return this;
  2468. }
  2469. var startPoint = this._points[this._points.length - 1];
  2470. var midPoint = new Vector2(midX, midY);
  2471. var endPoint = new Vector2(endX, endY);
  2472. var arc = new Arc2(startPoint, midPoint, endPoint);
  2473. var increment = arc.angle.radians() / numberOfSegments;
  2474. if (arc.orientation === Orientation.CW)
  2475. increment *= -1;
  2476. var currentAngle = arc.startAngle.radians() + increment;
  2477. for (var i = 0; i < numberOfSegments; i++) {
  2478. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2479. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2480. this.addLineTo(x, y);
  2481. currentAngle += increment;
  2482. }
  2483. return this;
  2484. };
  2485. Path2.prototype.close = function () {
  2486. this.closed = true;
  2487. return this;
  2488. };
  2489. Path2.prototype.length = function () {
  2490. var result = this._length;
  2491. if (!this.closed) {
  2492. var lastPoint = this._points[this._points.length - 1];
  2493. var firstPoint = this._points[0];
  2494. result += (firstPoint.subtract(lastPoint).length());
  2495. }
  2496. return result;
  2497. };
  2498. Path2.prototype.getPoints = function () {
  2499. return this._points;
  2500. };
  2501. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2502. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2503. //Tools.Error("normalized length position should be between 0 and 1.");
  2504. return Vector2.Zero();
  2505. }
  2506. var lengthPosition = normalizedLengthPosition * this.length();
  2507. var previousOffset = 0;
  2508. for (var i = 0; i < this._points.length; i++) {
  2509. var j = (i + 1) % this._points.length;
  2510. var a = this._points[i];
  2511. var b = this._points[j];
  2512. var bToA = b.subtract(a);
  2513. var nextOffset = (bToA.length() + previousOffset);
  2514. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2515. var dir = bToA.normalize();
  2516. var localOffset = lengthPosition - previousOffset;
  2517. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2518. }
  2519. previousOffset = nextOffset;
  2520. }
  2521. //Tools.Error("internal error");
  2522. return Vector2.Zero();
  2523. };
  2524. Path2.StartingAt = function (x, y) {
  2525. return new Path2(x, y);
  2526. };
  2527. return Path2;
  2528. })();
  2529. BABYLON.Path2 = Path2;
  2530. var Path3D = (function () {
  2531. /**
  2532. * new Path3D(path, normal, raw)
  2533. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2534. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2535. * path : an array of Vector3, the curve axis of the Path3D
  2536. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2537. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2538. */
  2539. function Path3D(path, firstNormal, raw) {
  2540. this.path = path;
  2541. this._curve = new Array();
  2542. this._distances = new Array();
  2543. this._tangents = new Array();
  2544. this._normals = new Array();
  2545. this._binormals = new Array();
  2546. for (var p = 0; p < path.length; p++) {
  2547. this._curve[p] = path[p].clone(); // hard copy
  2548. }
  2549. this._raw = raw || false;
  2550. this._compute(firstNormal);
  2551. }
  2552. /**
  2553. * Returns the Path3D array of successive Vector3 designing its curve.
  2554. */
  2555. Path3D.prototype.getCurve = function () {
  2556. return this._curve;
  2557. };
  2558. /**
  2559. * Returns an array populated with tangent vectors on each Path3D curve point.
  2560. */
  2561. Path3D.prototype.getTangents = function () {
  2562. return this._tangents;
  2563. };
  2564. /**
  2565. * Returns an array populated with normal vectors on each Path3D curve point.
  2566. */
  2567. Path3D.prototype.getNormals = function () {
  2568. return this._normals;
  2569. };
  2570. /**
  2571. * Returns an array populated with binormal vectors on each Path3D curve point.
  2572. */
  2573. Path3D.prototype.getBinormals = function () {
  2574. return this._binormals;
  2575. };
  2576. /**
  2577. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2578. */
  2579. Path3D.prototype.getDistances = function () {
  2580. return this._distances;
  2581. };
  2582. /**
  2583. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2584. * Returns the same object updated.
  2585. */
  2586. Path3D.prototype.update = function (path, firstNormal) {
  2587. for (var p = 0; p < path.length; p++) {
  2588. this._curve[p].x = path[p].x;
  2589. this._curve[p].y = path[p].y;
  2590. this._curve[p].z = path[p].z;
  2591. }
  2592. this._compute(firstNormal);
  2593. return this;
  2594. };
  2595. // private function compute() : computes tangents, normals and binormals
  2596. Path3D.prototype._compute = function (firstNormal) {
  2597. var l = this._curve.length;
  2598. // first and last tangents
  2599. this._tangents[0] = this._getFirstNonNullVector(0);
  2600. if (!this._raw) {
  2601. this._tangents[0].normalize();
  2602. }
  2603. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2604. if (!this._raw) {
  2605. this._tangents[l - 1].normalize();
  2606. }
  2607. // normals and binormals at first point : arbitrary vector with _normalVector()
  2608. var tg0 = this._tangents[0];
  2609. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2610. this._normals[0] = pp0;
  2611. if (!this._raw) {
  2612. this._normals[0].normalize();
  2613. }
  2614. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2615. if (!this._raw) {
  2616. this._binormals[0].normalize();
  2617. }
  2618. this._distances[0] = 0;
  2619. // normals and binormals : next points
  2620. var prev; // previous vector (segment)
  2621. var cur; // current vector (segment)
  2622. var curTang; // current tangent
  2623. // previous normal
  2624. var prevBinor; // previous binormal
  2625. for (var i = 1; i < l; i++) {
  2626. // tangents
  2627. prev = this._getLastNonNullVector(i);
  2628. if (i < l - 1) {
  2629. cur = this._getFirstNonNullVector(i);
  2630. this._tangents[i] = prev.add(cur);
  2631. this._tangents[i].normalize();
  2632. }
  2633. this._distances[i] = this._distances[i - 1] + prev.length();
  2634. // normals and binormals
  2635. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2636. curTang = this._tangents[i];
  2637. prevBinor = this._binormals[i - 1];
  2638. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2639. if (!this._raw) {
  2640. this._normals[i].normalize();
  2641. }
  2642. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2643. if (!this._raw) {
  2644. this._binormals[i].normalize();
  2645. }
  2646. }
  2647. };
  2648. // private function getFirstNonNullVector(index)
  2649. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2650. Path3D.prototype._getFirstNonNullVector = function (index) {
  2651. var i = 1;
  2652. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2653. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2654. i++;
  2655. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2656. }
  2657. return nNVector;
  2658. };
  2659. // private function getLastNonNullVector(index)
  2660. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2661. Path3D.prototype._getLastNonNullVector = function (index) {
  2662. var i = 1;
  2663. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2664. while (nLVector.length() === 0 && index > i + 1) {
  2665. i++;
  2666. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2667. }
  2668. return nLVector;
  2669. };
  2670. // private function normalVector(v0, vt, va) :
  2671. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2672. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2673. Path3D.prototype._normalVector = function (v0, vt, va) {
  2674. var normal0;
  2675. if (va === undefined || va === null) {
  2676. var point;
  2677. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2678. point = new Vector3(0, -1, 0);
  2679. }
  2680. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2681. point = new Vector3(1, 0, 0);
  2682. }
  2683. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2684. point = new Vector3(0, 0, 1);
  2685. }
  2686. normal0 = Vector3.Cross(vt, point);
  2687. }
  2688. else {
  2689. normal0 = Vector3.Cross(vt, va);
  2690. Vector3.CrossToRef(normal0, vt, normal0);
  2691. }
  2692. normal0.normalize();
  2693. return normal0;
  2694. };
  2695. return Path3D;
  2696. })();
  2697. BABYLON.Path3D = Path3D;
  2698. var Curve3 = (function () {
  2699. /**
  2700. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2701. * A Curve3 is designed from a series of successive Vector3.
  2702. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2703. */
  2704. function Curve3(points) {
  2705. this._length = 0;
  2706. this._points = points;
  2707. this._length = this._computeLength(points);
  2708. }
  2709. /**
  2710. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2711. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2712. * @param v1 (Vector3) the control point
  2713. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2714. * @param nbPoints (integer) the wanted number of points in the curve
  2715. */
  2716. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2717. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2718. var bez = new Array();
  2719. var equation = function (t, val0, val1, val2) {
  2720. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2721. return res;
  2722. };
  2723. for (var i = 0; i <= nbPoints; i++) {
  2724. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2725. }
  2726. return new Curve3(bez);
  2727. };
  2728. /**
  2729. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2730. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2731. * @param v1 (Vector3) the first control point
  2732. * @param v2 (Vector3) the second control point
  2733. * @param v3 (Vector3) the end point of the Cubic Bezier
  2734. * @param nbPoints (integer) the wanted number of points in the curve
  2735. */
  2736. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2737. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2738. var bez = new Array();
  2739. var equation = function (t, val0, val1, val2, val3) {
  2740. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2741. return res;
  2742. };
  2743. for (var i = 0; i <= nbPoints; i++) {
  2744. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2745. }
  2746. return new Curve3(bez);
  2747. };
  2748. /**
  2749. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2750. * @param p1 (Vector3) the origin point of the Hermite Spline
  2751. * @param t1 (Vector3) the tangent vector at the origin point
  2752. * @param p2 (Vector3) the end point of the Hermite Spline
  2753. * @param t2 (Vector3) the tangent vector at the end point
  2754. * @param nbPoints (integer) the wanted number of points in the curve
  2755. */
  2756. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2757. var hermite = new Array();
  2758. var step = 1 / nbPoints;
  2759. for (var i = 0; i <= nbPoints; i++) {
  2760. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2761. }
  2762. return new Curve3(hermite);
  2763. };
  2764. /**
  2765. * Returns the Curve3 stored array of successive Vector3
  2766. */
  2767. Curve3.prototype.getPoints = function () {
  2768. return this._points;
  2769. };
  2770. /**
  2771. * Returns the computed length (float) of the curve.
  2772. */
  2773. Curve3.prototype.length = function () {
  2774. return this._length;
  2775. };
  2776. /**
  2777. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2778. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2779. * curveA and curveB keep unchanged.
  2780. */
  2781. Curve3.prototype.continue = function (curve) {
  2782. var lastPoint = this._points[this._points.length - 1];
  2783. var continuedPoints = this._points.slice();
  2784. var curvePoints = curve.getPoints();
  2785. for (var i = 1; i < curvePoints.length; i++) {
  2786. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2787. }
  2788. var continuedCurve = new Curve3(continuedPoints);
  2789. return continuedCurve;
  2790. };
  2791. Curve3.prototype._computeLength = function (path) {
  2792. var l = 0;
  2793. for (var i = 1; i < path.length; i++) {
  2794. l += (path[i].subtract(path[i - 1])).length();
  2795. }
  2796. return l;
  2797. };
  2798. return Curve3;
  2799. })();
  2800. BABYLON.Curve3 = Curve3;
  2801. // SphericalHarmonics
  2802. var SphericalHarmonics = (function () {
  2803. function SphericalHarmonics() {
  2804. this.L00 = Vector3.Zero();
  2805. this.L1_1 = Vector3.Zero();
  2806. this.L10 = Vector3.Zero();
  2807. this.L11 = Vector3.Zero();
  2808. this.L2_2 = Vector3.Zero();
  2809. this.L2_1 = Vector3.Zero();
  2810. this.L20 = Vector3.Zero();
  2811. this.L21 = Vector3.Zero();
  2812. this.L22 = Vector3.Zero();
  2813. }
  2814. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2815. var colorVector = new Vector3(color.r, color.g, color.b);
  2816. var c = colorVector.scale(deltaSolidAngle);
  2817. this.L00 = this.L00.add(c.scale(0.282095));
  2818. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2819. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2820. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2821. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2822. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2823. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2824. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2825. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2826. };
  2827. SphericalHarmonics.prototype.scale = function (scale) {
  2828. this.L00 = this.L00.scale(scale);
  2829. this.L1_1 = this.L1_1.scale(scale);
  2830. this.L10 = this.L10.scale(scale);
  2831. this.L11 = this.L11.scale(scale);
  2832. this.L2_2 = this.L2_2.scale(scale);
  2833. this.L2_1 = this.L2_1.scale(scale);
  2834. this.L20 = this.L20.scale(scale);
  2835. this.L21 = this.L21.scale(scale);
  2836. this.L22 = this.L22.scale(scale);
  2837. };
  2838. return SphericalHarmonics;
  2839. })();
  2840. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2841. // SphericalPolynomial
  2842. var SphericalPolynomial = (function () {
  2843. function SphericalPolynomial() {
  2844. this.x = Vector3.Zero();
  2845. this.y = Vector3.Zero();
  2846. this.z = Vector3.Zero();
  2847. this.xx = Vector3.Zero();
  2848. this.yy = Vector3.Zero();
  2849. this.zz = Vector3.Zero();
  2850. this.xy = Vector3.Zero();
  2851. this.yz = Vector3.Zero();
  2852. this.zx = Vector3.Zero();
  2853. }
  2854. SphericalPolynomial.prototype.addAmbient = function (color) {
  2855. var colorVector = new Vector3(color.r, color.g, color.b);
  2856. this.xx = this.xx.add(colorVector);
  2857. this.yy = this.yy.add(colorVector);
  2858. this.zz = this.zz.add(colorVector);
  2859. };
  2860. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2861. var result = new SphericalPolynomial();
  2862. result.x = harmonics.L11.scale(1.02333);
  2863. result.y = harmonics.L1_1.scale(1.02333);
  2864. result.z = harmonics.L10.scale(1.02333);
  2865. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2866. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2867. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2868. result.yz = harmonics.L2_1.scale(0.858086);
  2869. result.zx = harmonics.L21.scale(0.858086);
  2870. result.xy = harmonics.L2_2.scale(0.858086);
  2871. return result;
  2872. };
  2873. return SphericalPolynomial;
  2874. })();
  2875. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2876. // Vertex formats
  2877. var PositionNormalVertex = (function () {
  2878. function PositionNormalVertex(position, normal) {
  2879. if (position === void 0) { position = Vector3.Zero(); }
  2880. if (normal === void 0) { normal = Vector3.Up(); }
  2881. this.position = position;
  2882. this.normal = normal;
  2883. }
  2884. PositionNormalVertex.prototype.clone = function () {
  2885. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2886. };
  2887. return PositionNormalVertex;
  2888. })();
  2889. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2890. var PositionNormalTextureVertex = (function () {
  2891. function PositionNormalTextureVertex(position, normal, uv) {
  2892. if (position === void 0) { position = Vector3.Zero(); }
  2893. if (normal === void 0) { normal = Vector3.Up(); }
  2894. if (uv === void 0) { uv = Vector2.Zero(); }
  2895. this.position = position;
  2896. this.normal = normal;
  2897. this.uv = uv;
  2898. }
  2899. PositionNormalTextureVertex.prototype.clone = function () {
  2900. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2901. };
  2902. return PositionNormalTextureVertex;
  2903. })();
  2904. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2905. // Temporary pre-allocated objects for engine internal use
  2906. // usage in any internal function :
  2907. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2908. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2909. var Tmp = (function () {
  2910. function Tmp() {
  2911. }
  2912. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2913. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2914. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2915. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2916. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2917. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2918. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2919. Matrix.Zero(), Matrix.Zero(),
  2920. Matrix.Zero(), Matrix.Zero(),
  2921. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2922. return Tmp;
  2923. })();
  2924. BABYLON.Tmp = Tmp;
  2925. })(BABYLON || (BABYLON = {}));
  2926. var BABYLON;
  2927. (function (BABYLON) {
  2928. function generateSerializableMember(type, sourceName) {
  2929. return function (target, propertyKey) {
  2930. if (!target.__serializableMembers) {
  2931. target.__serializableMembers = {};
  2932. }
  2933. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2934. };
  2935. }
  2936. function serialize(sourceName) {
  2937. return generateSerializableMember(0, sourceName); // value member
  2938. }
  2939. BABYLON.serialize = serialize;
  2940. function serializeAsTexture(sourceName) {
  2941. return generateSerializableMember(1, sourceName); // texture member
  2942. }
  2943. BABYLON.serializeAsTexture = serializeAsTexture;
  2944. function serializeAsColor3(sourceName) {
  2945. return generateSerializableMember(2, sourceName); // color3 member
  2946. }
  2947. BABYLON.serializeAsColor3 = serializeAsColor3;
  2948. function serializeAsFresnelParameters(sourceName) {
  2949. return generateSerializableMember(3, sourceName); // fresnel parameters member
  2950. }
  2951. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  2952. function serializeAsVector2(sourceName) {
  2953. return generateSerializableMember(4, sourceName); // vector2 member
  2954. }
  2955. BABYLON.serializeAsVector2 = serializeAsVector2;
  2956. function serializeAsVector3(sourceName) {
  2957. return generateSerializableMember(5, sourceName); // vector3 member
  2958. }
  2959. BABYLON.serializeAsVector3 = serializeAsVector3;
  2960. function serializeAsMeshReference(sourceName) {
  2961. return generateSerializableMember(6, sourceName); // mesh reference member
  2962. }
  2963. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  2964. var SerializationHelper = (function () {
  2965. function SerializationHelper() {
  2966. }
  2967. SerializationHelper.Serialize = function (entity, serializationObject) {
  2968. if (!serializationObject) {
  2969. serializationObject = {};
  2970. }
  2971. // Tags
  2972. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  2973. // Properties
  2974. for (var property in entity.__serializableMembers) {
  2975. var propertyDescriptor = entity.__serializableMembers[property];
  2976. var targetPropertyName = propertyDescriptor.sourceName || property;
  2977. var propertyType = propertyDescriptor.type;
  2978. var sourceProperty = entity[property];
  2979. if (sourceProperty !== undefined && sourceProperty !== null) {
  2980. switch (propertyType) {
  2981. case 0:
  2982. serializationObject[targetPropertyName] = sourceProperty;
  2983. break;
  2984. case 1:
  2985. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2986. break;
  2987. case 2:
  2988. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2989. break;
  2990. case 3:
  2991. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2992. break;
  2993. case 4:
  2994. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2995. break;
  2996. case 5:
  2997. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2998. break;
  2999. case 6:
  3000. serializationObject[targetPropertyName] = sourceProperty.id;
  3001. break;
  3002. }
  3003. }
  3004. }
  3005. return serializationObject;
  3006. };
  3007. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3008. var destination = creationFunction();
  3009. // Tags
  3010. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3011. // Properties
  3012. for (var property in destination.__serializableMembers) {
  3013. var propertyDescriptor = destination.__serializableMembers[property];
  3014. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3015. var propertyType = propertyDescriptor.type;
  3016. if (sourceProperty !== undefined && sourceProperty !== null) {
  3017. switch (propertyType) {
  3018. case 0:
  3019. destination[property] = sourceProperty;
  3020. break;
  3021. case 1:
  3022. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3023. break;
  3024. case 2:
  3025. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3026. break;
  3027. case 3:
  3028. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3029. break;
  3030. case 4:
  3031. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3032. break;
  3033. case 5:
  3034. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3035. break;
  3036. case 6:
  3037. destination[property] = scene.getLastMeshByID(sourceProperty);
  3038. break;
  3039. }
  3040. }
  3041. }
  3042. return destination;
  3043. };
  3044. SerializationHelper.Clone = function (creationFunction, source) {
  3045. var destination = creationFunction();
  3046. // Tags
  3047. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3048. // Properties
  3049. for (var property in destination.__serializableMembers) {
  3050. var propertyDescriptor = destination.__serializableMembers[property];
  3051. var sourceProperty = source[property];
  3052. var propertyType = propertyDescriptor.type;
  3053. if (sourceProperty !== undefined && sourceProperty !== null) {
  3054. switch (propertyType) {
  3055. case 0: // Value
  3056. case 6:
  3057. destination[property] = sourceProperty;
  3058. break;
  3059. case 1: // Texture
  3060. case 2: // Color3
  3061. case 3: // FresnelParameters
  3062. case 4: // Vector2
  3063. case 5:
  3064. destination[property] = sourceProperty.clone();
  3065. break;
  3066. }
  3067. }
  3068. }
  3069. return destination;
  3070. };
  3071. return SerializationHelper;
  3072. })();
  3073. BABYLON.SerializationHelper = SerializationHelper;
  3074. })(BABYLON || (BABYLON = {}));
  3075. var BABYLON;
  3076. (function (BABYLON) {
  3077. /**
  3078. * A class serves as a medium between the observable and its observers
  3079. */
  3080. var EventState = (function () {
  3081. /**
  3082. * If the callback of a given Observer set skipNextObervers to true the following observers will be ignored
  3083. */
  3084. function EventState(skipNextObervers) {
  3085. if (skipNextObervers === void 0) { skipNextObervers = false; }
  3086. this.skipNextObervers = skipNextObervers;
  3087. }
  3088. return EventState;
  3089. })();
  3090. BABYLON.EventState = EventState;
  3091. var Observer = (function () {
  3092. function Observer(callback, mask) {
  3093. this.callback = callback;
  3094. this.mask = mask;
  3095. }
  3096. return Observer;
  3097. })();
  3098. BABYLON.Observer = Observer;
  3099. var Observable = (function () {
  3100. function Observable() {
  3101. this._observers = new Array();
  3102. }
  3103. /**
  3104. * Create a new Observer with the specified callback
  3105. * @param callback the callback that will be executed for that Observer
  3106. * @param mash the mask used to filter observers
  3107. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  3108. */
  3109. Observable.prototype.add = function (callback, mask, insertFirst) {
  3110. if (mask === void 0) { mask = -1; }
  3111. if (insertFirst === void 0) { insertFirst = false; }
  3112. if (!callback) {
  3113. return null;
  3114. }
  3115. var observer = new Observer(callback, mask);
  3116. if (insertFirst) {
  3117. this._observers.unshift(observer);
  3118. }
  3119. else {
  3120. this._observers.push(observer);
  3121. }
  3122. return observer;
  3123. };
  3124. /**
  3125. * Remove an Observer from the Observable object
  3126. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3127. */
  3128. Observable.prototype.remove = function (observer) {
  3129. var index = this._observers.indexOf(observer);
  3130. if (index !== -1) {
  3131. this._observers.splice(index, 1);
  3132. return true;
  3133. }
  3134. return false;
  3135. };
  3136. /**
  3137. * Remove a callback from the Observable object
  3138. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3139. */
  3140. Observable.prototype.removeCallback = function (callback) {
  3141. for (var index = 0; index < this._observers.length; index++) {
  3142. if (this._observers[index].callback === callback) {
  3143. this._observers.splice(index, 1);
  3144. return true;
  3145. }
  3146. }
  3147. return false;
  3148. };
  3149. /**
  3150. * Notify all Observers by calling their respective callback with the given data
  3151. * @param eventData
  3152. * @param mask
  3153. */
  3154. Observable.prototype.notifyObservers = function (eventData, mask) {
  3155. if (mask === void 0) { mask = -1; }
  3156. var state = new EventState();
  3157. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3158. var obs = _a[_i];
  3159. if (obs.mask & mask) {
  3160. obs.callback(eventData, state);
  3161. }
  3162. if (state.skipNextObervers) {
  3163. break;
  3164. }
  3165. }
  3166. };
  3167. /**
  3168. * return true is the Observable has at least one Observer registered
  3169. */
  3170. Observable.prototype.hasObservers = function () {
  3171. return this._observers.length > 0;
  3172. };
  3173. /**
  3174. * Clear the list of observers
  3175. */
  3176. Observable.prototype.clear = function () {
  3177. this._observers = new Array();
  3178. };
  3179. /**
  3180. * Clone the current observable
  3181. */
  3182. Observable.prototype.clone = function () {
  3183. var result = new Observable();
  3184. result._observers = this._observers.slice(0);
  3185. return result;
  3186. };
  3187. return Observable;
  3188. })();
  3189. BABYLON.Observable = Observable;
  3190. })(BABYLON || (BABYLON = {}));
  3191. var BABYLON;
  3192. (function (BABYLON) {
  3193. var Database = (function () {
  3194. function Database(urlToScene, callbackManifestChecked) {
  3195. // Handling various flavors of prefixed version of IndexedDB
  3196. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3197. this.callbackManifestChecked = callbackManifestChecked;
  3198. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3199. this.db = null;
  3200. this.enableSceneOffline = false;
  3201. this.enableTexturesOffline = false;
  3202. this.manifestVersionFound = 0;
  3203. this.mustUpdateRessources = false;
  3204. this.hasReachedQuota = false;
  3205. if (!Database.IDBStorageEnabled) {
  3206. this.callbackManifestChecked(true);
  3207. }
  3208. else {
  3209. this.checkManifestFile();
  3210. }
  3211. }
  3212. Database.prototype.checkManifestFile = function () {
  3213. var _this = this;
  3214. function noManifestFile() {
  3215. that.enableSceneOffline = false;
  3216. that.enableTexturesOffline = false;
  3217. that.callbackManifestChecked(false);
  3218. }
  3219. var that = this;
  3220. var timeStampUsed = false;
  3221. var manifestURL = this.currentSceneUrl + ".manifest";
  3222. var xhr = new XMLHttpRequest();
  3223. if (navigator.onLine) {
  3224. // Adding a timestamp to by-pass browsers' cache
  3225. timeStampUsed = true;
  3226. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3227. }
  3228. xhr.open("GET", manifestURL, true);
  3229. xhr.addEventListener("load", function () {
  3230. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3231. try {
  3232. var manifestFile = JSON.parse(xhr.response);
  3233. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3234. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3235. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3236. _this.manifestVersionFound = manifestFile.version;
  3237. }
  3238. if (_this.callbackManifestChecked) {
  3239. _this.callbackManifestChecked(true);
  3240. }
  3241. }
  3242. catch (ex) {
  3243. noManifestFile();
  3244. }
  3245. }
  3246. else {
  3247. noManifestFile();
  3248. }
  3249. }, false);
  3250. xhr.addEventListener("error", function (event) {
  3251. if (timeStampUsed) {
  3252. timeStampUsed = false;
  3253. // Let's retry without the timeStamp
  3254. // It could fail when coupled with HTML5 Offline API
  3255. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3256. xhr.open("GET", retryManifestURL, true);
  3257. xhr.send();
  3258. }
  3259. else {
  3260. noManifestFile();
  3261. }
  3262. }, false);
  3263. try {
  3264. xhr.send();
  3265. }
  3266. catch (ex) {
  3267. BABYLON.Tools.Error("Error on XHR send request.");
  3268. that.callbackManifestChecked(false);
  3269. }
  3270. };
  3271. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3272. var _this = this;
  3273. function handleError() {
  3274. that.isSupported = false;
  3275. if (errorCallback)
  3276. errorCallback();
  3277. }
  3278. var that = this;
  3279. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3280. // Your browser doesn't support IndexedDB
  3281. this.isSupported = false;
  3282. if (errorCallback)
  3283. errorCallback();
  3284. }
  3285. else {
  3286. // If the DB hasn't been opened or created yet
  3287. if (!this.db) {
  3288. this.hasReachedQuota = false;
  3289. this.isSupported = true;
  3290. var request = this.idbFactory.open("babylonjs", 1);
  3291. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3292. request.onerror = function (event) {
  3293. handleError();
  3294. };
  3295. // executes when a version change transaction cannot complete due to other active transactions
  3296. request.onblocked = function (event) {
  3297. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3298. handleError();
  3299. };
  3300. // DB has been opened successfully
  3301. request.onsuccess = function (event) {
  3302. _this.db = request.result;
  3303. successCallback();
  3304. };
  3305. // Initialization of the DB. Creating Scenes & Textures stores
  3306. request.onupgradeneeded = function (event) {
  3307. _this.db = (event.target).result;
  3308. try {
  3309. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3310. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3311. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3312. }
  3313. catch (ex) {
  3314. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3315. handleError();
  3316. }
  3317. };
  3318. }
  3319. else {
  3320. if (successCallback)
  3321. successCallback();
  3322. }
  3323. }
  3324. };
  3325. Database.prototype.loadImageFromDB = function (url, image) {
  3326. var _this = this;
  3327. var completeURL = Database.ReturnFullUrlLocation(url);
  3328. var saveAndLoadImage = function () {
  3329. if (!_this.hasReachedQuota && _this.db !== null) {
  3330. // the texture is not yet in the DB, let's try to save it
  3331. _this._saveImageIntoDBAsync(completeURL, image);
  3332. }
  3333. else {
  3334. image.src = url;
  3335. }
  3336. };
  3337. if (!this.mustUpdateRessources) {
  3338. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3339. }
  3340. else {
  3341. saveAndLoadImage();
  3342. }
  3343. };
  3344. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3345. if (this.isSupported && this.db !== null) {
  3346. var texture;
  3347. var transaction = this.db.transaction(["textures"]);
  3348. transaction.onabort = function (event) {
  3349. image.src = url;
  3350. };
  3351. transaction.oncomplete = function (event) {
  3352. var blobTextureURL;
  3353. if (texture) {
  3354. var URL = window.URL || window.webkitURL;
  3355. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3356. image.onerror = function () {
  3357. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3358. image.src = url;
  3359. };
  3360. image.src = blobTextureURL;
  3361. }
  3362. else {
  3363. notInDBCallback();
  3364. }
  3365. };
  3366. var getRequest = transaction.objectStore("textures").get(url);
  3367. getRequest.onsuccess = function (event) {
  3368. texture = (event.target).result;
  3369. };
  3370. getRequest.onerror = function (event) {
  3371. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3372. image.src = url;
  3373. };
  3374. }
  3375. else {
  3376. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3377. image.src = url;
  3378. }
  3379. };
  3380. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3381. var _this = this;
  3382. if (this.isSupported) {
  3383. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3384. var generateBlobUrl = function () {
  3385. var blobTextureURL;
  3386. if (blob) {
  3387. var URL = window.URL || window.webkitURL;
  3388. try {
  3389. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3390. }
  3391. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3392. catch (ex) {
  3393. blobTextureURL = URL.createObjectURL(blob);
  3394. }
  3395. }
  3396. image.src = blobTextureURL;
  3397. };
  3398. if (Database.IsUASupportingBlobStorage) {
  3399. var xhr = new XMLHttpRequest(), blob;
  3400. xhr.open("GET", url, true);
  3401. xhr.responseType = "blob";
  3402. xhr.addEventListener("load", function () {
  3403. if (xhr.status === 200) {
  3404. // Blob as response (XHR2)
  3405. blob = xhr.response;
  3406. var transaction = _this.db.transaction(["textures"], "readwrite");
  3407. // the transaction could abort because of a QuotaExceededError error
  3408. transaction.onabort = function (event) {
  3409. try {
  3410. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3411. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3412. this.hasReachedQuota = true;
  3413. }
  3414. }
  3415. catch (ex) { }
  3416. generateBlobUrl();
  3417. };
  3418. transaction.oncomplete = function (event) {
  3419. generateBlobUrl();
  3420. };
  3421. var newTexture = { textureUrl: url, data: blob };
  3422. try {
  3423. // Put the blob into the dabase
  3424. var addRequest = transaction.objectStore("textures").put(newTexture);
  3425. addRequest.onsuccess = function (event) {
  3426. };
  3427. addRequest.onerror = function (event) {
  3428. generateBlobUrl();
  3429. };
  3430. }
  3431. catch (ex) {
  3432. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3433. if (ex.code === 25) {
  3434. Database.IsUASupportingBlobStorage = false;
  3435. }
  3436. image.src = url;
  3437. }
  3438. }
  3439. else {
  3440. image.src = url;
  3441. }
  3442. }, false);
  3443. xhr.addEventListener("error", function (event) {
  3444. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3445. image.src = url;
  3446. }, false);
  3447. xhr.send();
  3448. }
  3449. else {
  3450. image.src = url;
  3451. }
  3452. }
  3453. else {
  3454. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3455. image.src = url;
  3456. }
  3457. };
  3458. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3459. var _this = this;
  3460. var updateVersion = function (event) {
  3461. // the version is not yet in the DB or we need to update it
  3462. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3463. };
  3464. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3465. };
  3466. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3467. var _this = this;
  3468. if (this.isSupported) {
  3469. var version;
  3470. try {
  3471. var transaction = this.db.transaction(["versions"]);
  3472. transaction.oncomplete = function (event) {
  3473. if (version) {
  3474. // If the version in the JSON file is > than the version in DB
  3475. if (_this.manifestVersionFound > version.data) {
  3476. _this.mustUpdateRessources = true;
  3477. updateInDBCallback();
  3478. }
  3479. else {
  3480. callback(version.data);
  3481. }
  3482. }
  3483. else {
  3484. _this.mustUpdateRessources = true;
  3485. updateInDBCallback();
  3486. }
  3487. };
  3488. transaction.onabort = function (event) {
  3489. callback(-1);
  3490. };
  3491. var getRequest = transaction.objectStore("versions").get(url);
  3492. getRequest.onsuccess = function (event) {
  3493. version = (event.target).result;
  3494. };
  3495. getRequest.onerror = function (event) {
  3496. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3497. callback(-1);
  3498. };
  3499. }
  3500. catch (ex) {
  3501. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3502. callback(-1);
  3503. }
  3504. }
  3505. else {
  3506. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3507. callback(-1);
  3508. }
  3509. };
  3510. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3511. var _this = this;
  3512. if (this.isSupported && !this.hasReachedQuota) {
  3513. try {
  3514. // Open a transaction to the database
  3515. var transaction = this.db.transaction(["versions"], "readwrite");
  3516. // the transaction could abort because of a QuotaExceededError error
  3517. transaction.onabort = function (event) {
  3518. try {
  3519. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3520. _this.hasReachedQuota = true;
  3521. }
  3522. }
  3523. catch (ex) { }
  3524. callback(-1);
  3525. };
  3526. transaction.oncomplete = function (event) {
  3527. callback(_this.manifestVersionFound);
  3528. };
  3529. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3530. // Put the scene into the database
  3531. var addRequest = transaction.objectStore("versions").put(newVersion);
  3532. addRequest.onsuccess = function (event) {
  3533. };
  3534. addRequest.onerror = function (event) {
  3535. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3536. };
  3537. }
  3538. catch (ex) {
  3539. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3540. callback(-1);
  3541. }
  3542. }
  3543. else {
  3544. callback(-1);
  3545. }
  3546. };
  3547. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3548. var _this = this;
  3549. var completeUrl = Database.ReturnFullUrlLocation(url);
  3550. var saveAndLoadFile = function (event) {
  3551. // the scene is not yet in the DB, let's try to save it
  3552. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3553. };
  3554. this._checkVersionFromDB(completeUrl, function (version) {
  3555. if (version !== -1) {
  3556. if (!_this.mustUpdateRessources) {
  3557. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3558. }
  3559. else {
  3560. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3561. }
  3562. }
  3563. else {
  3564. errorCallback();
  3565. }
  3566. });
  3567. };
  3568. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3569. if (this.isSupported) {
  3570. var targetStore;
  3571. if (url.indexOf(".babylon") !== -1) {
  3572. targetStore = "scenes";
  3573. }
  3574. else {
  3575. targetStore = "textures";
  3576. }
  3577. var file;
  3578. var transaction = this.db.transaction([targetStore]);
  3579. transaction.oncomplete = function (event) {
  3580. if (file) {
  3581. callback(file.data);
  3582. }
  3583. else {
  3584. notInDBCallback();
  3585. }
  3586. };
  3587. transaction.onabort = function (event) {
  3588. notInDBCallback();
  3589. };
  3590. var getRequest = transaction.objectStore(targetStore).get(url);
  3591. getRequest.onsuccess = function (event) {
  3592. file = (event.target).result;
  3593. };
  3594. getRequest.onerror = function (event) {
  3595. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3596. notInDBCallback();
  3597. };
  3598. }
  3599. else {
  3600. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3601. callback();
  3602. }
  3603. };
  3604. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3605. var _this = this;
  3606. if (this.isSupported) {
  3607. var targetStore;
  3608. if (url.indexOf(".babylon") !== -1) {
  3609. targetStore = "scenes";
  3610. }
  3611. else {
  3612. targetStore = "textures";
  3613. }
  3614. // Create XHR
  3615. var xhr = new XMLHttpRequest(), fileData;
  3616. xhr.open("GET", url, true);
  3617. if (useArrayBuffer) {
  3618. xhr.responseType = "arraybuffer";
  3619. }
  3620. xhr.onprogress = progressCallback;
  3621. xhr.addEventListener("load", function () {
  3622. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3623. // Blob as response (XHR2)
  3624. //fileData = xhr.responseText;
  3625. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3626. if (!_this.hasReachedQuota) {
  3627. // Open a transaction to the database
  3628. var transaction = _this.db.transaction([targetStore], "readwrite");
  3629. // the transaction could abort because of a QuotaExceededError error
  3630. transaction.onabort = function (event) {
  3631. try {
  3632. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3633. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3634. this.hasReachedQuota = true;
  3635. }
  3636. }
  3637. catch (ex) { }
  3638. callback(fileData);
  3639. };
  3640. transaction.oncomplete = function (event) {
  3641. callback(fileData);
  3642. };
  3643. var newFile;
  3644. if (targetStore === "scenes") {
  3645. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3646. }
  3647. else {
  3648. newFile = { textureUrl: url, data: fileData };
  3649. }
  3650. try {
  3651. // Put the scene into the database
  3652. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3653. addRequest.onsuccess = function (event) {
  3654. };
  3655. addRequest.onerror = function (event) {
  3656. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3657. };
  3658. }
  3659. catch (ex) {
  3660. callback(fileData);
  3661. }
  3662. }
  3663. else {
  3664. callback(fileData);
  3665. }
  3666. }
  3667. else {
  3668. callback();
  3669. }
  3670. }, false);
  3671. xhr.addEventListener("error", function (event) {
  3672. BABYLON.Tools.Error("error on XHR request.");
  3673. callback();
  3674. }, false);
  3675. xhr.send();
  3676. }
  3677. else {
  3678. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3679. callback();
  3680. }
  3681. };
  3682. Database.IsUASupportingBlobStorage = true;
  3683. Database.IDBStorageEnabled = true;
  3684. Database.parseURL = function (url) {
  3685. var a = document.createElement('a');
  3686. a.href = url;
  3687. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3688. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3689. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3690. return absLocation;
  3691. };
  3692. Database.ReturnFullUrlLocation = function (url) {
  3693. if (url.indexOf("http:/") === -1) {
  3694. return (Database.parseURL(window.location.href) + url);
  3695. }
  3696. else {
  3697. return url;
  3698. }
  3699. };
  3700. return Database;
  3701. })();
  3702. BABYLON.Database = Database;
  3703. })(BABYLON || (BABYLON = {}));
  3704. var BABYLON;
  3705. (function (BABYLON) {
  3706. var Internals;
  3707. (function (Internals) {
  3708. /*
  3709. * Based on jsTGALoader - Javascript loader for TGA file
  3710. * By Vincent Thibault
  3711. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3712. */
  3713. var TGATools = (function () {
  3714. function TGATools() {
  3715. }
  3716. TGATools.GetTGAHeader = function (data) {
  3717. var offset = 0;
  3718. var header = {
  3719. id_length: data[offset++],
  3720. colormap_type: data[offset++],
  3721. image_type: data[offset++],
  3722. colormap_index: data[offset++] | data[offset++] << 8,
  3723. colormap_length: data[offset++] | data[offset++] << 8,
  3724. colormap_size: data[offset++],
  3725. origin: [
  3726. data[offset++] | data[offset++] << 8,
  3727. data[offset++] | data[offset++] << 8
  3728. ],
  3729. width: data[offset++] | data[offset++] << 8,
  3730. height: data[offset++] | data[offset++] << 8,
  3731. pixel_size: data[offset++],
  3732. flags: data[offset++]
  3733. };
  3734. return header;
  3735. };
  3736. TGATools.UploadContent = function (gl, data) {
  3737. // Not enough data to contain header ?
  3738. if (data.length < 19) {
  3739. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3740. return;
  3741. }
  3742. // Read Header
  3743. var offset = 18;
  3744. var header = TGATools.GetTGAHeader(data);
  3745. // Assume it's a valid Targa file.
  3746. if (header.id_length + offset > data.length) {
  3747. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3748. return;
  3749. }
  3750. // Skip not needed data
  3751. offset += header.id_length;
  3752. var use_rle = false;
  3753. var use_pal = false;
  3754. var use_rgb = false;
  3755. var use_grey = false;
  3756. // Get some informations.
  3757. switch (header.image_type) {
  3758. case TGATools._TYPE_RLE_INDEXED:
  3759. use_rle = true;
  3760. case TGATools._TYPE_INDEXED:
  3761. use_pal = true;
  3762. break;
  3763. case TGATools._TYPE_RLE_RGB:
  3764. use_rle = true;
  3765. case TGATools._TYPE_RGB:
  3766. use_rgb = true;
  3767. break;
  3768. case TGATools._TYPE_RLE_GREY:
  3769. use_rle = true;
  3770. case TGATools._TYPE_GREY:
  3771. use_grey = true;
  3772. break;
  3773. }
  3774. var pixel_data;
  3775. var numAlphaBits = header.flags & 0xf;
  3776. var pixel_size = header.pixel_size >> 3;
  3777. var pixel_total = header.width * header.height * pixel_size;
  3778. // Read palettes
  3779. var palettes;
  3780. if (use_pal) {
  3781. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3782. }
  3783. // Read LRE
  3784. if (use_rle) {
  3785. pixel_data = new Uint8Array(pixel_total);
  3786. var c, count, i;
  3787. var localOffset = 0;
  3788. var pixels = new Uint8Array(pixel_size);
  3789. while (offset < pixel_total && localOffset < pixel_total) {
  3790. c = data[offset++];
  3791. count = (c & 0x7f) + 1;
  3792. // RLE pixels
  3793. if (c & 0x80) {
  3794. // Bind pixel tmp array
  3795. for (i = 0; i < pixel_size; ++i) {
  3796. pixels[i] = data[offset++];
  3797. }
  3798. // Copy pixel array
  3799. for (i = 0; i < count; ++i) {
  3800. pixel_data.set(pixels, localOffset + i * pixel_size);
  3801. }
  3802. localOffset += pixel_size * count;
  3803. }
  3804. else {
  3805. count *= pixel_size;
  3806. for (i = 0; i < count; ++i) {
  3807. pixel_data[localOffset + i] = data[offset++];
  3808. }
  3809. localOffset += count;
  3810. }
  3811. }
  3812. }
  3813. else {
  3814. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3815. }
  3816. // Load to texture
  3817. var x_start, y_start, x_step, y_step, y_end, x_end;
  3818. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3819. default:
  3820. case TGATools._ORIGIN_UL:
  3821. x_start = 0;
  3822. x_step = 1;
  3823. x_end = header.width;
  3824. y_start = 0;
  3825. y_step = 1;
  3826. y_end = header.height;
  3827. break;
  3828. case TGATools._ORIGIN_BL:
  3829. x_start = 0;
  3830. x_step = 1;
  3831. x_end = header.width;
  3832. y_start = header.height - 1;
  3833. y_step = -1;
  3834. y_end = -1;
  3835. break;
  3836. case TGATools._ORIGIN_UR:
  3837. x_start = header.width - 1;
  3838. x_step = -1;
  3839. x_end = -1;
  3840. y_start = 0;
  3841. y_step = 1;
  3842. y_end = header.height;
  3843. break;
  3844. case TGATools._ORIGIN_BR:
  3845. x_start = header.width - 1;
  3846. x_step = -1;
  3847. x_end = -1;
  3848. y_start = header.height - 1;
  3849. y_step = -1;
  3850. y_end = -1;
  3851. break;
  3852. }
  3853. // Load the specify method
  3854. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3855. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3856. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3857. };
  3858. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3859. var image = pixel_data, colormap = palettes;
  3860. var width = header.width, height = header.height;
  3861. var color, i = 0, x, y;
  3862. var imageData = new Uint8Array(width * height * 4);
  3863. for (y = y_start; y !== y_end; y += y_step) {
  3864. for (x = x_start; x !== x_end; x += x_step, i++) {
  3865. color = image[i];
  3866. imageData[(x + width * y) * 4 + 3] = 255;
  3867. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3868. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3869. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3870. }
  3871. }
  3872. return imageData;
  3873. };
  3874. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3875. var image = pixel_data;
  3876. var width = header.width, height = header.height;
  3877. var color, i = 0, x, y;
  3878. var imageData = new Uint8Array(width * height * 4);
  3879. for (y = y_start; y !== y_end; y += y_step) {
  3880. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3881. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3882. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3883. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3884. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3885. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3886. }
  3887. }
  3888. return imageData;
  3889. };
  3890. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3891. var image = pixel_data;
  3892. var width = header.width, height = header.height;
  3893. var i = 0, x, y;
  3894. var imageData = new Uint8Array(width * height * 4);
  3895. for (y = y_start; y !== y_end; y += y_step) {
  3896. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3897. imageData[(x + width * y) * 4 + 3] = 255;
  3898. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3899. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3900. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3901. }
  3902. }
  3903. return imageData;
  3904. };
  3905. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3906. var image = pixel_data;
  3907. var width = header.width, height = header.height;
  3908. var i = 0, x, y;
  3909. var imageData = new Uint8Array(width * height * 4);
  3910. for (y = y_start; y !== y_end; y += y_step) {
  3911. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3912. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3913. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3914. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3915. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3916. }
  3917. }
  3918. return imageData;
  3919. };
  3920. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3921. var image = pixel_data;
  3922. var width = header.width, height = header.height;
  3923. var color, i = 0, x, y;
  3924. var imageData = new Uint8Array(width * height * 4);
  3925. for (y = y_start; y !== y_end; y += y_step) {
  3926. for (x = x_start; x !== x_end; x += x_step, i++) {
  3927. color = image[i];
  3928. imageData[(x + width * y) * 4 + 0] = color;
  3929. imageData[(x + width * y) * 4 + 1] = color;
  3930. imageData[(x + width * y) * 4 + 2] = color;
  3931. imageData[(x + width * y) * 4 + 3] = 255;
  3932. }
  3933. }
  3934. return imageData;
  3935. };
  3936. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3937. var image = pixel_data;
  3938. var width = header.width, height = header.height;
  3939. var i = 0, x, y;
  3940. var imageData = new Uint8Array(width * height * 4);
  3941. for (y = y_start; y !== y_end; y += y_step) {
  3942. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3943. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3944. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3945. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3946. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3947. }
  3948. }
  3949. return imageData;
  3950. };
  3951. TGATools._TYPE_NO_DATA = 0;
  3952. TGATools._TYPE_INDEXED = 1;
  3953. TGATools._TYPE_RGB = 2;
  3954. TGATools._TYPE_GREY = 3;
  3955. TGATools._TYPE_RLE_INDEXED = 9;
  3956. TGATools._TYPE_RLE_RGB = 10;
  3957. TGATools._TYPE_RLE_GREY = 11;
  3958. TGATools._ORIGIN_MASK = 0x30;
  3959. TGATools._ORIGIN_SHIFT = 0x04;
  3960. TGATools._ORIGIN_BL = 0x00;
  3961. TGATools._ORIGIN_BR = 0x01;
  3962. TGATools._ORIGIN_UL = 0x02;
  3963. TGATools._ORIGIN_UR = 0x03;
  3964. return TGATools;
  3965. })();
  3966. Internals.TGATools = TGATools;
  3967. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3968. })(BABYLON || (BABYLON = {}));
  3969. var BABYLON;
  3970. (function (BABYLON) {
  3971. var SmartArray = (function () {
  3972. function SmartArray(capacity) {
  3973. this.length = 0;
  3974. this._duplicateId = 0;
  3975. this.data = new Array(capacity);
  3976. this._id = SmartArray._GlobalId++;
  3977. }
  3978. SmartArray.prototype.push = function (value) {
  3979. this.data[this.length++] = value;
  3980. if (this.length > this.data.length) {
  3981. this.data.length *= 2;
  3982. }
  3983. if (!value.__smartArrayFlags) {
  3984. value.__smartArrayFlags = {};
  3985. }
  3986. value.__smartArrayFlags[this._id] = this._duplicateId;
  3987. };
  3988. SmartArray.prototype.pushNoDuplicate = function (value) {
  3989. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3990. return;
  3991. }
  3992. this.push(value);
  3993. };
  3994. SmartArray.prototype.sort = function (compareFn) {
  3995. this.data.sort(compareFn);
  3996. };
  3997. SmartArray.prototype.reset = function () {
  3998. this.length = 0;
  3999. this._duplicateId++;
  4000. };
  4001. SmartArray.prototype.concat = function (array) {
  4002. if (array.length === 0) {
  4003. return;
  4004. }
  4005. if (this.length + array.length > this.data.length) {
  4006. this.data.length = (this.length + array.length) * 2;
  4007. }
  4008. for (var index = 0; index < array.length; index++) {
  4009. this.data[this.length++] = (array.data || array)[index];
  4010. }
  4011. };
  4012. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4013. if (array.length === 0) {
  4014. return;
  4015. }
  4016. if (this.length + array.length > this.data.length) {
  4017. this.data.length = (this.length + array.length) * 2;
  4018. }
  4019. for (var index = 0; index < array.length; index++) {
  4020. var item = (array.data || array)[index];
  4021. this.pushNoDuplicate(item);
  4022. }
  4023. };
  4024. SmartArray.prototype.indexOf = function (value) {
  4025. var position = this.data.indexOf(value);
  4026. if (position >= this.length) {
  4027. return -1;
  4028. }
  4029. return position;
  4030. };
  4031. // Statics
  4032. SmartArray._GlobalId = 0;
  4033. return SmartArray;
  4034. })();
  4035. BABYLON.SmartArray = SmartArray;
  4036. })(BABYLON || (BABYLON = {}));
  4037. var BABYLON;
  4038. (function (BABYLON) {
  4039. var SmartCollection = (function () {
  4040. function SmartCollection(capacity) {
  4041. if (capacity === void 0) { capacity = 10; }
  4042. this.count = 0;
  4043. this._initialCapacity = capacity;
  4044. this.items = {};
  4045. this._keys = new Array(this._initialCapacity);
  4046. }
  4047. SmartCollection.prototype.add = function (key, item) {
  4048. if (this.items[key] != undefined) {
  4049. return -1;
  4050. }
  4051. this.items[key] = item;
  4052. //literal keys are always strings, but we keep source type of key in _keys array
  4053. this._keys[this.count++] = key;
  4054. if (this.count > this._keys.length) {
  4055. this._keys.length *= 2;
  4056. }
  4057. return this.count;
  4058. };
  4059. SmartCollection.prototype.remove = function (key) {
  4060. if (this.items[key] == undefined) {
  4061. return -1;
  4062. }
  4063. return this.removeItemOfIndex(this.indexOf(key));
  4064. };
  4065. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4066. if (index < this.count && index > -1) {
  4067. delete this.items[this._keys[index]];
  4068. //here, shifting by hand is better optimised than .splice
  4069. while (index < this.count) {
  4070. this._keys[index] = this._keys[index + 1];
  4071. index++;
  4072. }
  4073. }
  4074. else {
  4075. return -1;
  4076. }
  4077. return --this.count;
  4078. };
  4079. SmartCollection.prototype.indexOf = function (key) {
  4080. for (var i = 0; i !== this.count; i++) {
  4081. if (this._keys[i] === key) {
  4082. return i;
  4083. }
  4084. }
  4085. return -1;
  4086. };
  4087. SmartCollection.prototype.item = function (key) {
  4088. return this.items[key];
  4089. };
  4090. SmartCollection.prototype.getAllKeys = function () {
  4091. if (this.count > 0) {
  4092. var keys = new Array(this.count);
  4093. for (var i = 0; i < this.count; i++) {
  4094. keys[i] = this._keys[i];
  4095. }
  4096. return keys;
  4097. }
  4098. else {
  4099. return undefined;
  4100. }
  4101. };
  4102. SmartCollection.prototype.getKeyByIndex = function (index) {
  4103. if (index < this.count && index > -1) {
  4104. return this._keys[index];
  4105. }
  4106. else {
  4107. return undefined;
  4108. }
  4109. };
  4110. SmartCollection.prototype.getItemByIndex = function (index) {
  4111. if (index < this.count && index > -1) {
  4112. return this.items[this._keys[index]];
  4113. }
  4114. else {
  4115. return undefined;
  4116. }
  4117. };
  4118. SmartCollection.prototype.empty = function () {
  4119. if (this.count > 0) {
  4120. this.count = 0;
  4121. this.items = {};
  4122. this._keys = new Array(this._initialCapacity);
  4123. }
  4124. };
  4125. SmartCollection.prototype.forEach = function (block) {
  4126. var key;
  4127. for (key in this.items) {
  4128. if (this.items.hasOwnProperty(key)) {
  4129. block(this.items[key]);
  4130. }
  4131. }
  4132. };
  4133. return SmartCollection;
  4134. })();
  4135. BABYLON.SmartCollection = SmartCollection;
  4136. })(BABYLON || (BABYLON = {}));
  4137. var BABYLON;
  4138. (function (BABYLON) {
  4139. // Screenshots
  4140. var screenshotCanvas;
  4141. var cloneValue = function (source, destinationObject) {
  4142. if (!source)
  4143. return null;
  4144. if (source instanceof BABYLON.Mesh) {
  4145. return null;
  4146. }
  4147. if (source instanceof BABYLON.SubMesh) {
  4148. return source.clone(destinationObject);
  4149. }
  4150. else if (source.clone) {
  4151. return source.clone();
  4152. }
  4153. return null;
  4154. };
  4155. var Tools = (function () {
  4156. function Tools() {
  4157. }
  4158. Tools.Instantiate = function (className) {
  4159. var arr = className.split(".");
  4160. var fn = (window || this);
  4161. for (var i = 0, len = arr.length; i < len; i++) {
  4162. fn = fn[arr[i]];
  4163. }
  4164. if (typeof fn !== "function") {
  4165. return null;
  4166. }
  4167. return fn;
  4168. };
  4169. Tools.SetImmediate = function (action) {
  4170. if (window.setImmediate) {
  4171. window.setImmediate(action);
  4172. }
  4173. else {
  4174. setTimeout(action, 1);
  4175. }
  4176. };
  4177. Tools.IsExponentOfTwo = function (value) {
  4178. var count = 1;
  4179. do {
  4180. count *= 2;
  4181. } while (count < value);
  4182. return count === value;
  4183. };
  4184. Tools.GetExponentOfTwo = function (value, max) {
  4185. var count = 1;
  4186. do {
  4187. count *= 2;
  4188. } while (count < value);
  4189. if (count > max)
  4190. count = max;
  4191. return count;
  4192. };
  4193. Tools.GetFilename = function (path) {
  4194. var index = path.lastIndexOf("/");
  4195. if (index < 0)
  4196. return path;
  4197. return path.substring(index + 1);
  4198. };
  4199. Tools.GetDOMTextContent = function (element) {
  4200. var result = "";
  4201. var child = element.firstChild;
  4202. while (child) {
  4203. if (child.nodeType === 3) {
  4204. result += child.textContent;
  4205. }
  4206. child = child.nextSibling;
  4207. }
  4208. return result;
  4209. };
  4210. Tools.ToDegrees = function (angle) {
  4211. return angle * 180 / Math.PI;
  4212. };
  4213. Tools.ToRadians = function (angle) {
  4214. return angle * Math.PI / 180;
  4215. };
  4216. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4217. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4218. var output = "";
  4219. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4220. var i = 0;
  4221. var bytes = new Uint8Array(buffer);
  4222. while (i < bytes.length) {
  4223. chr1 = bytes[i++];
  4224. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4225. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4226. enc1 = chr1 >> 2;
  4227. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4228. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4229. enc4 = chr3 & 63;
  4230. if (isNaN(chr2)) {
  4231. enc3 = enc4 = 64;
  4232. }
  4233. else if (isNaN(chr3)) {
  4234. enc4 = 64;
  4235. }
  4236. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4237. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4238. }
  4239. return "data:image/png;base64," + output;
  4240. };
  4241. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4242. if (bias === void 0) { bias = null; }
  4243. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4244. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4245. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4246. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4247. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4248. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4249. }
  4250. if (bias) {
  4251. minimum.x -= minimum.x * bias.x + bias.y;
  4252. minimum.y -= minimum.y * bias.x + bias.y;
  4253. minimum.z -= minimum.z * bias.x + bias.y;
  4254. maximum.x += maximum.x * bias.x + bias.y;
  4255. maximum.y += maximum.y * bias.x + bias.y;
  4256. maximum.z += maximum.z * bias.x + bias.y;
  4257. }
  4258. return {
  4259. minimum: minimum,
  4260. maximum: maximum
  4261. };
  4262. };
  4263. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  4264. if (bias === void 0) { bias = null; }
  4265. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4266. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4267. for (var index = start; index < start + count; index++) {
  4268. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4269. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4270. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4271. }
  4272. if (bias) {
  4273. minimum.x -= minimum.x * bias.x + bias.y;
  4274. minimum.y -= minimum.y * bias.x + bias.y;
  4275. minimum.z -= minimum.z * bias.x + bias.y;
  4276. maximum.x += maximum.x * bias.x + bias.y;
  4277. maximum.y += maximum.y * bias.x + bias.y;
  4278. maximum.z += maximum.z * bias.x + bias.y;
  4279. }
  4280. return {
  4281. minimum: minimum,
  4282. maximum: maximum
  4283. };
  4284. };
  4285. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4286. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4287. return undefined;
  4288. return Array.isArray(obj) ? obj : [obj];
  4289. };
  4290. // Misc.
  4291. Tools.GetPointerPrefix = function () {
  4292. var eventPrefix = "pointer";
  4293. // Check if pointer events are supported
  4294. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4295. eventPrefix = "mouse";
  4296. }
  4297. return eventPrefix;
  4298. };
  4299. Tools.QueueNewFrame = function (func) {
  4300. if (window.requestAnimationFrame)
  4301. window.requestAnimationFrame(func);
  4302. else if (window.msRequestAnimationFrame)
  4303. window.msRequestAnimationFrame(func);
  4304. else if (window.webkitRequestAnimationFrame)
  4305. window.webkitRequestAnimationFrame(func);
  4306. else if (window.mozRequestAnimationFrame)
  4307. window.mozRequestAnimationFrame(func);
  4308. else if (window.oRequestAnimationFrame)
  4309. window.oRequestAnimationFrame(func);
  4310. else {
  4311. window.setTimeout(func, 16);
  4312. }
  4313. };
  4314. Tools.RequestFullscreen = function (element) {
  4315. if (element.requestFullscreen)
  4316. element.requestFullscreen();
  4317. else if (element.msRequestFullscreen)
  4318. element.msRequestFullscreen();
  4319. else if (element.webkitRequestFullscreen)
  4320. element.webkitRequestFullscreen();
  4321. else if (element.mozRequestFullScreen)
  4322. element.mozRequestFullScreen();
  4323. };
  4324. Tools.ExitFullscreen = function () {
  4325. if (document.exitFullscreen) {
  4326. document.exitFullscreen();
  4327. }
  4328. else if (document.mozCancelFullScreen) {
  4329. document.mozCancelFullScreen();
  4330. }
  4331. else if (document.webkitCancelFullScreen) {
  4332. document.webkitCancelFullScreen();
  4333. }
  4334. else if (document.msCancelFullScreen) {
  4335. document.msCancelFullScreen();
  4336. }
  4337. };
  4338. // External files
  4339. Tools.CleanUrl = function (url) {
  4340. url = url.replace(/#/mg, "%23");
  4341. return url;
  4342. };
  4343. Tools.LoadImage = function (url, onload, onerror, database) {
  4344. if (url instanceof ArrayBuffer) {
  4345. url = Tools.EncodeArrayBufferTobase64(url);
  4346. }
  4347. url = Tools.CleanUrl(url);
  4348. var img = new Image();
  4349. if (url.substr(0, 5) !== "data:") {
  4350. if (Tools.CorsBehavior) {
  4351. switch (typeof (Tools.CorsBehavior)) {
  4352. case "function":
  4353. var result = Tools.CorsBehavior(url);
  4354. if (result) {
  4355. img.crossOrigin = result;
  4356. }
  4357. break;
  4358. case "string":
  4359. default:
  4360. img.crossOrigin = Tools.CorsBehavior;
  4361. break;
  4362. }
  4363. }
  4364. }
  4365. img.onload = function () {
  4366. onload(img);
  4367. };
  4368. img.onerror = function (err) {
  4369. Tools.Error("Error while trying to load texture: " + url);
  4370. if (Tools.UseFallbackTexture) {
  4371. 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";
  4372. onload(img);
  4373. }
  4374. else {
  4375. onerror();
  4376. }
  4377. };
  4378. var noIndexedDB = function () {
  4379. img.src = url;
  4380. };
  4381. var loadFromIndexedDB = function () {
  4382. database.loadImageFromDB(url, img);
  4383. };
  4384. //ANY database to do!
  4385. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4386. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4387. }
  4388. else {
  4389. if (url.indexOf("file:") === -1) {
  4390. noIndexedDB();
  4391. }
  4392. else {
  4393. try {
  4394. var textureName = url.substring(5);
  4395. var blobURL;
  4396. try {
  4397. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4398. }
  4399. catch (ex) {
  4400. // Chrome doesn't support oneTimeOnly parameter
  4401. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4402. }
  4403. img.src = blobURL;
  4404. }
  4405. catch (e) {
  4406. img.src = null;
  4407. }
  4408. }
  4409. }
  4410. return img;
  4411. };
  4412. //ANY
  4413. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4414. url = Tools.CleanUrl(url);
  4415. var noIndexedDB = function () {
  4416. var request = new XMLHttpRequest();
  4417. var loadUrl = Tools.BaseUrl + url;
  4418. request.open('GET', loadUrl, true);
  4419. if (useArrayBuffer) {
  4420. request.responseType = "arraybuffer";
  4421. }
  4422. request.onprogress = progressCallBack;
  4423. request.onreadystatechange = function () {
  4424. if (request.readyState === 4) {
  4425. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4426. callback(!useArrayBuffer ? request.responseText : request.response);
  4427. }
  4428. else {
  4429. if (onError) {
  4430. onError();
  4431. }
  4432. else {
  4433. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4434. }
  4435. }
  4436. }
  4437. };
  4438. request.send(null);
  4439. };
  4440. var loadFromIndexedDB = function () {
  4441. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4442. };
  4443. if (url.indexOf("file:") !== -1) {
  4444. var fileName = url.substring(5).toLowerCase();
  4445. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4446. }
  4447. else {
  4448. // Caching all files
  4449. if (database && database.enableSceneOffline) {
  4450. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4451. }
  4452. else {
  4453. noIndexedDB();
  4454. }
  4455. }
  4456. };
  4457. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4458. var reader = new FileReader();
  4459. reader.onload = function (e) {
  4460. //target doesn't have result from ts 1.3
  4461. callback(e.target['result']);
  4462. };
  4463. reader.onprogress = progressCallback;
  4464. reader.readAsDataURL(fileToLoad);
  4465. };
  4466. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4467. var reader = new FileReader();
  4468. reader.onerror = function (e) {
  4469. Tools.Log("Error while reading file: " + fileToLoad.name);
  4470. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4471. };
  4472. reader.onload = function (e) {
  4473. //target doesn't have result from ts 1.3
  4474. callback(e.target['result']);
  4475. };
  4476. reader.onprogress = progressCallBack;
  4477. if (!useArrayBuffer) {
  4478. // Asynchronous read
  4479. reader.readAsText(fileToLoad);
  4480. }
  4481. else {
  4482. reader.readAsArrayBuffer(fileToLoad);
  4483. }
  4484. };
  4485. //returns a downloadable url to a file content.
  4486. Tools.FileAsURL = function (content) {
  4487. var fileBlob = new Blob([content]);
  4488. var url = window.URL || window.webkitURL;
  4489. var link = url.createObjectURL(fileBlob);
  4490. return link;
  4491. };
  4492. // Misc.
  4493. Tools.Format = function (value, decimals) {
  4494. if (decimals === void 0) { decimals = 2; }
  4495. return value.toFixed(decimals);
  4496. };
  4497. Tools.CheckExtends = function (v, min, max) {
  4498. if (v.x < min.x)
  4499. min.x = v.x;
  4500. if (v.y < min.y)
  4501. min.y = v.y;
  4502. if (v.z < min.z)
  4503. min.z = v.z;
  4504. if (v.x > max.x)
  4505. max.x = v.x;
  4506. if (v.y > max.y)
  4507. max.y = v.y;
  4508. if (v.z > max.z)
  4509. max.z = v.z;
  4510. };
  4511. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4512. for (var prop in source) {
  4513. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4514. continue;
  4515. }
  4516. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4517. continue;
  4518. }
  4519. var sourceValue = source[prop];
  4520. var typeOfSourceValue = typeof sourceValue;
  4521. if (typeOfSourceValue === "function") {
  4522. continue;
  4523. }
  4524. if (typeOfSourceValue === "object") {
  4525. if (sourceValue instanceof Array) {
  4526. destination[prop] = [];
  4527. if (sourceValue.length > 0) {
  4528. if (typeof sourceValue[0] == "object") {
  4529. for (var index = 0; index < sourceValue.length; index++) {
  4530. var clonedValue = cloneValue(sourceValue[index], destination);
  4531. if (destination[prop].indexOf(clonedValue) === -1) {
  4532. destination[prop].push(clonedValue);
  4533. }
  4534. }
  4535. }
  4536. else {
  4537. destination[prop] = sourceValue.slice(0);
  4538. }
  4539. }
  4540. }
  4541. else {
  4542. destination[prop] = cloneValue(sourceValue, destination);
  4543. }
  4544. }
  4545. else {
  4546. destination[prop] = sourceValue;
  4547. }
  4548. }
  4549. };
  4550. Tools.IsEmpty = function (obj) {
  4551. for (var i in obj) {
  4552. return false;
  4553. }
  4554. return true;
  4555. };
  4556. Tools.RegisterTopRootEvents = function (events) {
  4557. for (var index = 0; index < events.length; index++) {
  4558. var event = events[index];
  4559. window.addEventListener(event.name, event.handler, false);
  4560. try {
  4561. if (window.parent) {
  4562. window.parent.addEventListener(event.name, event.handler, false);
  4563. }
  4564. }
  4565. catch (e) {
  4566. }
  4567. }
  4568. };
  4569. Tools.UnregisterTopRootEvents = function (events) {
  4570. for (var index = 0; index < events.length; index++) {
  4571. var event = events[index];
  4572. window.removeEventListener(event.name, event.handler);
  4573. try {
  4574. if (window.parent) {
  4575. window.parent.removeEventListener(event.name, event.handler);
  4576. }
  4577. }
  4578. catch (e) {
  4579. }
  4580. }
  4581. };
  4582. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4583. // Read the contents of the framebuffer
  4584. var numberOfChannelsByLine = width * 4;
  4585. var halfHeight = height / 2;
  4586. //Reading datas from WebGL
  4587. var data = engine.readPixels(0, 0, width, height);
  4588. //To flip image on Y axis.
  4589. for (var i = 0; i < halfHeight; i++) {
  4590. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4591. var currentCell = j + i * numberOfChannelsByLine;
  4592. var targetLine = height - i - 1;
  4593. var targetCell = j + targetLine * numberOfChannelsByLine;
  4594. var temp = data[currentCell];
  4595. data[currentCell] = data[targetCell];
  4596. data[targetCell] = temp;
  4597. }
  4598. }
  4599. // Create a 2D canvas to store the result
  4600. if (!screenshotCanvas) {
  4601. screenshotCanvas = document.createElement('canvas');
  4602. }
  4603. screenshotCanvas.width = width;
  4604. screenshotCanvas.height = height;
  4605. var context = screenshotCanvas.getContext('2d');
  4606. // Copy the pixels to a 2D canvas
  4607. var imageData = context.createImageData(width, height);
  4608. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4609. var castData = imageData.data;
  4610. castData.set(data);
  4611. context.putImageData(imageData, 0, 0);
  4612. var base64Image = screenshotCanvas.toDataURL();
  4613. if (successCallback) {
  4614. successCallback(base64Image);
  4615. }
  4616. else {
  4617. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4618. if (("download" in document.createElement("a"))) {
  4619. var a = window.document.createElement("a");
  4620. a.href = base64Image;
  4621. var date = new Date();
  4622. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4623. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4624. window.document.body.appendChild(a);
  4625. a.addEventListener("click", function () {
  4626. a.parentElement.removeChild(a);
  4627. });
  4628. a.click();
  4629. }
  4630. else {
  4631. var newWindow = window.open("");
  4632. var img = newWindow.document.createElement("img");
  4633. img.src = base64Image;
  4634. newWindow.document.body.appendChild(img);
  4635. }
  4636. }
  4637. };
  4638. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4639. var width;
  4640. var height;
  4641. //If a precision value is specified
  4642. if (size.precision) {
  4643. width = Math.round(engine.getRenderWidth() * size.precision);
  4644. height = Math.round(width / engine.getAspectRatio(camera));
  4645. size = { width: width, height: height };
  4646. }
  4647. else if (size.width && size.height) {
  4648. width = size.width;
  4649. height = size.height;
  4650. }
  4651. else if (size.width && !size.height) {
  4652. width = size.width;
  4653. height = Math.round(width / engine.getAspectRatio(camera));
  4654. size = { width: width, height: height };
  4655. }
  4656. else if (size.height && !size.width) {
  4657. height = size.height;
  4658. width = Math.round(height * engine.getAspectRatio(camera));
  4659. size = { width: width, height: height };
  4660. }
  4661. else if (!isNaN(size)) {
  4662. height = size;
  4663. width = size;
  4664. }
  4665. else {
  4666. Tools.Error("Invalid 'size' parameter !");
  4667. return;
  4668. }
  4669. var scene = camera.getScene();
  4670. var previousCamera = null;
  4671. if (scene.activeCamera !== camera) {
  4672. previousCamera = scene.activeCamera;
  4673. scene.activeCamera = camera;
  4674. }
  4675. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4676. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4677. texture.renderList = scene.meshes;
  4678. texture.onAfterRender = function () {
  4679. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4680. };
  4681. scene.incrementRenderId();
  4682. texture.render(true);
  4683. texture.dispose();
  4684. if (previousCamera) {
  4685. scene.activeCamera = previousCamera;
  4686. }
  4687. camera.getProjectionMatrix(true); // Force cache refresh;
  4688. };
  4689. // XHR response validator for local file scenario
  4690. Tools.ValidateXHRData = function (xhr, dataType) {
  4691. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4692. if (dataType === void 0) { dataType = 7; }
  4693. try {
  4694. if (dataType & 1) {
  4695. if (xhr.responseText && xhr.responseText.length > 0) {
  4696. return true;
  4697. }
  4698. else if (dataType === 1) {
  4699. return false;
  4700. }
  4701. }
  4702. if (dataType & 2) {
  4703. // Check header width and height since there is no "TGA" magic number
  4704. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4705. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4706. return true;
  4707. }
  4708. else if (dataType === 2) {
  4709. return false;
  4710. }
  4711. }
  4712. if (dataType & 4) {
  4713. // Check for the "DDS" magic number
  4714. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4715. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4716. return true;
  4717. }
  4718. else {
  4719. return false;
  4720. }
  4721. }
  4722. }
  4723. catch (e) {
  4724. }
  4725. return false;
  4726. };
  4727. Object.defineProperty(Tools, "NoneLogLevel", {
  4728. get: function () {
  4729. return Tools._NoneLogLevel;
  4730. },
  4731. enumerable: true,
  4732. configurable: true
  4733. });
  4734. Object.defineProperty(Tools, "MessageLogLevel", {
  4735. get: function () {
  4736. return Tools._MessageLogLevel;
  4737. },
  4738. enumerable: true,
  4739. configurable: true
  4740. });
  4741. Object.defineProperty(Tools, "WarningLogLevel", {
  4742. get: function () {
  4743. return Tools._WarningLogLevel;
  4744. },
  4745. enumerable: true,
  4746. configurable: true
  4747. });
  4748. Object.defineProperty(Tools, "ErrorLogLevel", {
  4749. get: function () {
  4750. return Tools._ErrorLogLevel;
  4751. },
  4752. enumerable: true,
  4753. configurable: true
  4754. });
  4755. Object.defineProperty(Tools, "AllLogLevel", {
  4756. get: function () {
  4757. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4758. },
  4759. enumerable: true,
  4760. configurable: true
  4761. });
  4762. Tools._AddLogEntry = function (entry) {
  4763. Tools._LogCache = entry + Tools._LogCache;
  4764. if (Tools.OnNewCacheEntry) {
  4765. Tools.OnNewCacheEntry(entry);
  4766. }
  4767. };
  4768. Tools._FormatMessage = function (message) {
  4769. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4770. var date = new Date();
  4771. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4772. };
  4773. Tools._LogDisabled = function (message) {
  4774. // nothing to do
  4775. };
  4776. Tools._LogEnabled = function (message) {
  4777. var formattedMessage = Tools._FormatMessage(message);
  4778. console.log("BJS - " + formattedMessage);
  4779. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4780. Tools._AddLogEntry(entry);
  4781. };
  4782. Tools._WarnDisabled = function (message) {
  4783. // nothing to do
  4784. };
  4785. Tools._WarnEnabled = function (message) {
  4786. var formattedMessage = Tools._FormatMessage(message);
  4787. console.warn("BJS - " + formattedMessage);
  4788. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4789. Tools._AddLogEntry(entry);
  4790. };
  4791. Tools._ErrorDisabled = function (message) {
  4792. // nothing to do
  4793. };
  4794. Tools._ErrorEnabled = function (message) {
  4795. Tools.errorsCount++;
  4796. var formattedMessage = Tools._FormatMessage(message);
  4797. console.error("BJS - " + formattedMessage);
  4798. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4799. Tools._AddLogEntry(entry);
  4800. };
  4801. Object.defineProperty(Tools, "LogCache", {
  4802. get: function () {
  4803. return Tools._LogCache;
  4804. },
  4805. enumerable: true,
  4806. configurable: true
  4807. });
  4808. Tools.ClearLogCache = function () {
  4809. Tools._LogCache = "";
  4810. Tools.errorsCount = 0;
  4811. };
  4812. Object.defineProperty(Tools, "LogLevels", {
  4813. set: function (level) {
  4814. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4815. Tools.Log = Tools._LogEnabled;
  4816. }
  4817. else {
  4818. Tools.Log = Tools._LogDisabled;
  4819. }
  4820. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4821. Tools.Warn = Tools._WarnEnabled;
  4822. }
  4823. else {
  4824. Tools.Warn = Tools._WarnDisabled;
  4825. }
  4826. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4827. Tools.Error = Tools._ErrorEnabled;
  4828. }
  4829. else {
  4830. Tools.Error = Tools._ErrorDisabled;
  4831. }
  4832. },
  4833. enumerable: true,
  4834. configurable: true
  4835. });
  4836. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4837. get: function () {
  4838. return Tools._PerformanceNoneLogLevel;
  4839. },
  4840. enumerable: true,
  4841. configurable: true
  4842. });
  4843. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4844. get: function () {
  4845. return Tools._PerformanceUserMarkLogLevel;
  4846. },
  4847. enumerable: true,
  4848. configurable: true
  4849. });
  4850. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4851. get: function () {
  4852. return Tools._PerformanceConsoleLogLevel;
  4853. },
  4854. enumerable: true,
  4855. configurable: true
  4856. });
  4857. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4858. set: function (level) {
  4859. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4860. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4861. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4862. return;
  4863. }
  4864. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4865. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4866. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4867. return;
  4868. }
  4869. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4870. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4871. },
  4872. enumerable: true,
  4873. configurable: true
  4874. });
  4875. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4876. };
  4877. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4878. };
  4879. Tools._StartUserMark = function (counterName, condition) {
  4880. if (condition === void 0) { condition = true; }
  4881. if (!condition || !Tools._performance.mark) {
  4882. return;
  4883. }
  4884. Tools._performance.mark(counterName + "-Begin");
  4885. };
  4886. Tools._EndUserMark = function (counterName, condition) {
  4887. if (condition === void 0) { condition = true; }
  4888. if (!condition || !Tools._performance.mark) {
  4889. return;
  4890. }
  4891. Tools._performance.mark(counterName + "-End");
  4892. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4893. };
  4894. Tools._StartPerformanceConsole = function (counterName, condition) {
  4895. if (condition === void 0) { condition = true; }
  4896. if (!condition) {
  4897. return;
  4898. }
  4899. Tools._StartUserMark(counterName, condition);
  4900. if (console.time) {
  4901. console.time(counterName);
  4902. }
  4903. };
  4904. Tools._EndPerformanceConsole = function (counterName, condition) {
  4905. if (condition === void 0) { condition = true; }
  4906. if (!condition) {
  4907. return;
  4908. }
  4909. Tools._EndUserMark(counterName, condition);
  4910. if (console.time) {
  4911. console.timeEnd(counterName);
  4912. }
  4913. };
  4914. Object.defineProperty(Tools, "Now", {
  4915. get: function () {
  4916. if (window.performance && window.performance.now) {
  4917. return window.performance.now();
  4918. }
  4919. return new Date().getTime();
  4920. },
  4921. enumerable: true,
  4922. configurable: true
  4923. });
  4924. Tools.BaseUrl = "";
  4925. Tools.CorsBehavior = "anonymous";
  4926. Tools.UseFallbackTexture = true;
  4927. // Logs
  4928. Tools._NoneLogLevel = 0;
  4929. Tools._MessageLogLevel = 1;
  4930. Tools._WarningLogLevel = 2;
  4931. Tools._ErrorLogLevel = 4;
  4932. Tools._LogCache = "";
  4933. Tools.errorsCount = 0;
  4934. Tools.Log = Tools._LogEnabled;
  4935. Tools.Warn = Tools._WarnEnabled;
  4936. Tools.Error = Tools._ErrorEnabled;
  4937. // Performances
  4938. Tools._PerformanceNoneLogLevel = 0;
  4939. Tools._PerformanceUserMarkLogLevel = 1;
  4940. Tools._PerformanceConsoleLogLevel = 2;
  4941. Tools._performance = window.performance;
  4942. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4943. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4944. return Tools;
  4945. })();
  4946. BABYLON.Tools = Tools;
  4947. /**
  4948. * An implementation of a loop for asynchronous functions.
  4949. */
  4950. var AsyncLoop = (function () {
  4951. /**
  4952. * Constroctor.
  4953. * @param iterations the number of iterations.
  4954. * @param _fn the function to run each iteration
  4955. * @param _successCallback the callback that will be called upon succesful execution
  4956. * @param offset starting offset.
  4957. */
  4958. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4959. if (offset === void 0) { offset = 0; }
  4960. this.iterations = iterations;
  4961. this._fn = _fn;
  4962. this._successCallback = _successCallback;
  4963. this.index = offset - 1;
  4964. this._done = false;
  4965. }
  4966. /**
  4967. * Execute the next iteration. Must be called after the last iteration was finished.
  4968. */
  4969. AsyncLoop.prototype.executeNext = function () {
  4970. if (!this._done) {
  4971. if (this.index + 1 < this.iterations) {
  4972. ++this.index;
  4973. this._fn(this);
  4974. }
  4975. else {
  4976. this.breakLoop();
  4977. }
  4978. }
  4979. };
  4980. /**
  4981. * Break the loop and run the success callback.
  4982. */
  4983. AsyncLoop.prototype.breakLoop = function () {
  4984. this._done = true;
  4985. this._successCallback();
  4986. };
  4987. /**
  4988. * Helper function
  4989. */
  4990. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4991. if (offset === void 0) { offset = 0; }
  4992. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4993. loop.executeNext();
  4994. return loop;
  4995. };
  4996. /**
  4997. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4998. * @param iterations total number of iterations
  4999. * @param syncedIterations number of synchronous iterations in each async iteration.
  5000. * @param fn the function to call each iteration.
  5001. * @param callback a success call back that will be called when iterating stops.
  5002. * @param breakFunction a break condition (optional)
  5003. * @param timeout timeout settings for the setTimeout function. default - 0.
  5004. * @constructor
  5005. */
  5006. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5007. if (timeout === void 0) { timeout = 0; }
  5008. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5009. if (breakFunction && breakFunction())
  5010. loop.breakLoop();
  5011. else {
  5012. setTimeout(function () {
  5013. for (var i = 0; i < syncedIterations; ++i) {
  5014. var iteration = (loop.index * syncedIterations) + i;
  5015. if (iteration >= iterations)
  5016. break;
  5017. fn(iteration);
  5018. if (breakFunction && breakFunction()) {
  5019. loop.breakLoop();
  5020. break;
  5021. }
  5022. }
  5023. loop.executeNext();
  5024. }, timeout);
  5025. }
  5026. }, callback);
  5027. };
  5028. return AsyncLoop;
  5029. })();
  5030. BABYLON.AsyncLoop = AsyncLoop;
  5031. })(BABYLON || (BABYLON = {}));
  5032. var BABYLON;
  5033. (function (BABYLON) {
  5034. var Internals;
  5035. (function (Internals) {
  5036. var _AlphaState = (function () {
  5037. function _AlphaState() {
  5038. this._isAlphaBlendDirty = false;
  5039. this._isBlendFunctionParametersDirty = false;
  5040. this._alphaBlend = false;
  5041. this._blendFunctionParameters = new Array(4);
  5042. }
  5043. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5044. get: function () {
  5045. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5046. },
  5047. enumerable: true,
  5048. configurable: true
  5049. });
  5050. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5051. get: function () {
  5052. return this._alphaBlend;
  5053. },
  5054. set: function (value) {
  5055. if (this._alphaBlend === value) {
  5056. return;
  5057. }
  5058. this._alphaBlend = value;
  5059. this._isAlphaBlendDirty = true;
  5060. },
  5061. enumerable: true,
  5062. configurable: true
  5063. });
  5064. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5065. if (this._blendFunctionParameters[0] === value0 &&
  5066. this._blendFunctionParameters[1] === value1 &&
  5067. this._blendFunctionParameters[2] === value2 &&
  5068. this._blendFunctionParameters[3] === value3) {
  5069. return;
  5070. }
  5071. this._blendFunctionParameters[0] = value0;
  5072. this._blendFunctionParameters[1] = value1;
  5073. this._blendFunctionParameters[2] = value2;
  5074. this._blendFunctionParameters[3] = value3;
  5075. this._isBlendFunctionParametersDirty = true;
  5076. };
  5077. _AlphaState.prototype.reset = function () {
  5078. this._alphaBlend = false;
  5079. this._blendFunctionParameters[0] = null;
  5080. this._blendFunctionParameters[1] = null;
  5081. this._blendFunctionParameters[2] = null;
  5082. this._blendFunctionParameters[3] = null;
  5083. this._isAlphaBlendDirty = true;
  5084. this._isBlendFunctionParametersDirty = false;
  5085. };
  5086. _AlphaState.prototype.apply = function (gl) {
  5087. if (!this.isDirty) {
  5088. return;
  5089. }
  5090. // Alpha blend
  5091. if (this._isAlphaBlendDirty) {
  5092. if (this._alphaBlend) {
  5093. gl.enable(gl.BLEND);
  5094. }
  5095. else {
  5096. gl.disable(gl.BLEND);
  5097. }
  5098. this._isAlphaBlendDirty = false;
  5099. }
  5100. // Alpha function
  5101. if (this._isBlendFunctionParametersDirty) {
  5102. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5103. this._isBlendFunctionParametersDirty = false;
  5104. }
  5105. };
  5106. return _AlphaState;
  5107. })();
  5108. Internals._AlphaState = _AlphaState;
  5109. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5110. })(BABYLON || (BABYLON = {}));
  5111. var BABYLON;
  5112. (function (BABYLON) {
  5113. var Internals;
  5114. (function (Internals) {
  5115. var _DepthCullingState = (function () {
  5116. function _DepthCullingState() {
  5117. this._isDepthTestDirty = false;
  5118. this._isDepthMaskDirty = false;
  5119. this._isDepthFuncDirty = false;
  5120. this._isCullFaceDirty = false;
  5121. this._isCullDirty = false;
  5122. this._isZOffsetDirty = false;
  5123. }
  5124. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5125. get: function () {
  5126. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5127. },
  5128. enumerable: true,
  5129. configurable: true
  5130. });
  5131. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5132. get: function () {
  5133. return this._zOffset;
  5134. },
  5135. set: function (value) {
  5136. if (this._zOffset === value) {
  5137. return;
  5138. }
  5139. this._zOffset = value;
  5140. this._isZOffsetDirty = true;
  5141. },
  5142. enumerable: true,
  5143. configurable: true
  5144. });
  5145. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5146. get: function () {
  5147. return this._cullFace;
  5148. },
  5149. set: function (value) {
  5150. if (this._cullFace === value) {
  5151. return;
  5152. }
  5153. this._cullFace = value;
  5154. this._isCullFaceDirty = true;
  5155. },
  5156. enumerable: true,
  5157. configurable: true
  5158. });
  5159. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5160. get: function () {
  5161. return this._cull;
  5162. },
  5163. set: function (value) {
  5164. if (this._cull === value) {
  5165. return;
  5166. }
  5167. this._cull = value;
  5168. this._isCullDirty = true;
  5169. },
  5170. enumerable: true,
  5171. configurable: true
  5172. });
  5173. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5174. get: function () {
  5175. return this._depthFunc;
  5176. },
  5177. set: function (value) {
  5178. if (this._depthFunc === value) {
  5179. return;
  5180. }
  5181. this._depthFunc = value;
  5182. this._isDepthFuncDirty = true;
  5183. },
  5184. enumerable: true,
  5185. configurable: true
  5186. });
  5187. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5188. get: function () {
  5189. return this._depthMask;
  5190. },
  5191. set: function (value) {
  5192. if (this._depthMask === value) {
  5193. return;
  5194. }
  5195. this._depthMask = value;
  5196. this._isDepthMaskDirty = true;
  5197. },
  5198. enumerable: true,
  5199. configurable: true
  5200. });
  5201. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5202. get: function () {
  5203. return this._depthTest;
  5204. },
  5205. set: function (value) {
  5206. if (this._depthTest === value) {
  5207. return;
  5208. }
  5209. this._depthTest = value;
  5210. this._isDepthTestDirty = true;
  5211. },
  5212. enumerable: true,
  5213. configurable: true
  5214. });
  5215. _DepthCullingState.prototype.reset = function () {
  5216. this._depthMask = true;
  5217. this._depthTest = true;
  5218. this._depthFunc = null;
  5219. this._cull = null;
  5220. this._cullFace = null;
  5221. this._zOffset = 0;
  5222. this._isDepthTestDirty = true;
  5223. this._isDepthMaskDirty = true;
  5224. this._isDepthFuncDirty = false;
  5225. this._isCullFaceDirty = false;
  5226. this._isCullDirty = false;
  5227. this._isZOffsetDirty = false;
  5228. };
  5229. _DepthCullingState.prototype.apply = function (gl) {
  5230. if (!this.isDirty) {
  5231. return;
  5232. }
  5233. // Cull
  5234. if (this._isCullDirty) {
  5235. if (this.cull) {
  5236. gl.enable(gl.CULL_FACE);
  5237. }
  5238. else {
  5239. gl.disable(gl.CULL_FACE);
  5240. }
  5241. this._isCullDirty = false;
  5242. }
  5243. // Cull face
  5244. if (this._isCullFaceDirty) {
  5245. gl.cullFace(this.cullFace);
  5246. this._isCullFaceDirty = false;
  5247. }
  5248. // Depth mask
  5249. if (this._isDepthMaskDirty) {
  5250. gl.depthMask(this.depthMask);
  5251. this._isDepthMaskDirty = false;
  5252. }
  5253. // Depth test
  5254. if (this._isDepthTestDirty) {
  5255. if (this.depthTest) {
  5256. gl.enable(gl.DEPTH_TEST);
  5257. }
  5258. else {
  5259. gl.disable(gl.DEPTH_TEST);
  5260. }
  5261. this._isDepthTestDirty = false;
  5262. }
  5263. // Depth func
  5264. if (this._isDepthFuncDirty) {
  5265. gl.depthFunc(this.depthFunc);
  5266. this._isDepthFuncDirty = false;
  5267. }
  5268. // zOffset
  5269. if (this._isZOffsetDirty) {
  5270. if (this.zOffset) {
  5271. gl.enable(gl.POLYGON_OFFSET_FILL);
  5272. gl.polygonOffset(this.zOffset, 0);
  5273. }
  5274. else {
  5275. gl.disable(gl.POLYGON_OFFSET_FILL);
  5276. }
  5277. this._isZOffsetDirty = false;
  5278. }
  5279. };
  5280. return _DepthCullingState;
  5281. })();
  5282. Internals._DepthCullingState = _DepthCullingState;
  5283. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5284. })(BABYLON || (BABYLON = {}));
  5285. var BABYLON;
  5286. (function (BABYLON) {
  5287. var compileShader = function (gl, source, type, defines) {
  5288. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5289. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5290. gl.compileShader(shader);
  5291. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5292. throw new Error(gl.getShaderInfoLog(shader));
  5293. }
  5294. return shader;
  5295. };
  5296. var getWebGLTextureType = function (gl, type) {
  5297. var textureType = gl.UNSIGNED_BYTE;
  5298. if (type === Engine.TEXTURETYPE_FLOAT)
  5299. textureType = gl.FLOAT;
  5300. return textureType;
  5301. };
  5302. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5303. var magFilter = gl.NEAREST;
  5304. var minFilter = gl.NEAREST;
  5305. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5306. magFilter = gl.LINEAR;
  5307. if (generateMipMaps) {
  5308. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5309. }
  5310. else {
  5311. minFilter = gl.LINEAR;
  5312. }
  5313. }
  5314. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5315. magFilter = gl.LINEAR;
  5316. if (generateMipMaps) {
  5317. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5318. }
  5319. else {
  5320. minFilter = gl.LINEAR;
  5321. }
  5322. }
  5323. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5324. magFilter = gl.NEAREST;
  5325. if (generateMipMaps) {
  5326. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5327. }
  5328. else {
  5329. minFilter = gl.NEAREST;
  5330. }
  5331. }
  5332. return {
  5333. min: minFilter,
  5334. mag: magFilter
  5335. };
  5336. };
  5337. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5339. var engine = scene.getEngine();
  5340. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5341. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5342. gl.bindTexture(gl.TEXTURE_2D, texture);
  5343. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5344. texture._baseWidth = width;
  5345. texture._baseHeight = height;
  5346. texture._width = potWidth;
  5347. texture._height = potHeight;
  5348. texture.isReady = true;
  5349. processFunction(potWidth, potHeight);
  5350. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5351. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5352. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5353. if (!noMipmap && !isCompressed) {
  5354. gl.generateMipmap(gl.TEXTURE_2D);
  5355. }
  5356. gl.bindTexture(gl.TEXTURE_2D, null);
  5357. engine.resetTextureCache();
  5358. scene._removePendingData(texture);
  5359. if (onLoad) {
  5360. onLoad();
  5361. }
  5362. };
  5363. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5364. var img;
  5365. var onload = function () {
  5366. loadedImages[index] = img;
  5367. loadedImages._internalCount++;
  5368. scene._removePendingData(img);
  5369. if (loadedImages._internalCount === 6) {
  5370. onfinish(loadedImages);
  5371. }
  5372. };
  5373. var onerror = function () {
  5374. scene._removePendingData(img);
  5375. };
  5376. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5377. scene._addPendingData(img);
  5378. };
  5379. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5380. var loadedImages = [];
  5381. loadedImages._internalCount = 0;
  5382. for (var index = 0; index < 6; index++) {
  5383. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5384. }
  5385. };
  5386. var EngineCapabilities = (function () {
  5387. function EngineCapabilities() {
  5388. }
  5389. return EngineCapabilities;
  5390. })();
  5391. BABYLON.EngineCapabilities = EngineCapabilities;
  5392. /**
  5393. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5394. */
  5395. var Engine = (function () {
  5396. /**
  5397. * @constructor
  5398. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5399. * @param {boolean} [antialias] - enable antialias
  5400. * @param options - further options to be sent to the getContext function
  5401. */
  5402. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5403. var _this = this;
  5404. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5405. // Public members
  5406. this.isFullscreen = false;
  5407. this.isPointerLock = false;
  5408. this.cullBackFaces = true;
  5409. this.renderEvenInBackground = true;
  5410. // To enable/disable IDB support and avoid XHR on .manifest
  5411. this.enableOfflineSupport = true;
  5412. this.scenes = new Array();
  5413. this._windowIsBackground = false;
  5414. this._webGLVersion = "1.0";
  5415. this._drawCalls = 0;
  5416. this._renderingQueueLaunched = false;
  5417. this._activeRenderLoops = [];
  5418. // FPS
  5419. this.fpsRange = 60;
  5420. this.previousFramesDuration = [];
  5421. this.fps = 60;
  5422. this.deltaTime = 0;
  5423. // States
  5424. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5425. this._alphaState = new BABYLON.Internals._AlphaState();
  5426. this._alphaMode = Engine.ALPHA_DISABLE;
  5427. // Cache
  5428. this._loadedTexturesCache = new Array();
  5429. this._maxTextureChannels = 16;
  5430. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5431. this._compiledEffects = {};
  5432. this._uintIndicesCurrentlySet = false;
  5433. this._renderingCanvas = canvas;
  5434. options = options || {};
  5435. options.antialias = antialias;
  5436. if (options.preserveDrawingBuffer === undefined) {
  5437. options.preserveDrawingBuffer = false;
  5438. }
  5439. // GL
  5440. //try {
  5441. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5442. // if (this._gl) {
  5443. // this._webGLVersion = "2.0";
  5444. // }
  5445. //} catch (e) {
  5446. // // Do nothing
  5447. //}
  5448. if (!this._gl) {
  5449. try {
  5450. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5451. }
  5452. catch (e) {
  5453. throw new Error("WebGL not supported");
  5454. }
  5455. }
  5456. if (!this._gl) {
  5457. throw new Error("WebGL not supported");
  5458. }
  5459. this._onBlur = function () {
  5460. _this._windowIsBackground = true;
  5461. };
  5462. this._onFocus = function () {
  5463. _this._windowIsBackground = false;
  5464. };
  5465. window.addEventListener("blur", this._onBlur);
  5466. window.addEventListener("focus", this._onFocus);
  5467. // Viewport
  5468. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5469. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5470. this.resize();
  5471. // Caps
  5472. this._caps = new EngineCapabilities();
  5473. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5474. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5475. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5476. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5477. // Infos
  5478. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5479. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5480. if (rendererInfo != null) {
  5481. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5482. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5483. }
  5484. if (!this._glVendor) {
  5485. this._glVendor = "Unknown vendor";
  5486. }
  5487. if (!this._glRenderer) {
  5488. this._glRenderer = "Unknown renderer";
  5489. }
  5490. // Extensions
  5491. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5492. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5493. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5494. 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');
  5495. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5496. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5497. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5498. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5499. this._caps.highPrecisionShaderSupported = true;
  5500. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5501. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5502. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5503. if (this._gl.getShaderPrecisionFormat) {
  5504. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5505. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5506. }
  5507. // Depth buffer
  5508. this.setDepthBuffer(true);
  5509. this.setDepthFunctionToLessOrEqual();
  5510. this.setDepthWrite(true);
  5511. // Fullscreen
  5512. this._onFullscreenChange = function () {
  5513. if (document.fullscreen !== undefined) {
  5514. _this.isFullscreen = document.fullscreen;
  5515. }
  5516. else if (document.mozFullScreen !== undefined) {
  5517. _this.isFullscreen = document.mozFullScreen;
  5518. }
  5519. else if (document.webkitIsFullScreen !== undefined) {
  5520. _this.isFullscreen = document.webkitIsFullScreen;
  5521. }
  5522. else if (document.msIsFullScreen !== undefined) {
  5523. _this.isFullscreen = document.msIsFullScreen;
  5524. }
  5525. // Pointer lock
  5526. if (_this.isFullscreen && _this._pointerLockRequested) {
  5527. canvas.requestPointerLock = canvas.requestPointerLock ||
  5528. canvas.msRequestPointerLock ||
  5529. canvas.mozRequestPointerLock ||
  5530. canvas.webkitRequestPointerLock;
  5531. if (canvas.requestPointerLock) {
  5532. canvas.requestPointerLock();
  5533. }
  5534. }
  5535. };
  5536. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5537. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5538. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5539. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5540. // Pointer lock
  5541. this._onPointerLockChange = function () {
  5542. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5543. document.webkitPointerLockElement === canvas ||
  5544. document.msPointerLockElement === canvas ||
  5545. document.pointerLockElement === canvas);
  5546. };
  5547. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5548. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5549. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5550. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5551. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5552. Engine.audioEngine = new BABYLON.AudioEngine();
  5553. }
  5554. //default loading screen
  5555. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5556. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5557. }
  5558. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5559. get: function () {
  5560. return Engine._ALPHA_DISABLE;
  5561. },
  5562. enumerable: true,
  5563. configurable: true
  5564. });
  5565. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5566. get: function () {
  5567. return Engine._ALPHA_ONEONE;
  5568. },
  5569. enumerable: true,
  5570. configurable: true
  5571. });
  5572. Object.defineProperty(Engine, "ALPHA_ADD", {
  5573. get: function () {
  5574. return Engine._ALPHA_ADD;
  5575. },
  5576. enumerable: true,
  5577. configurable: true
  5578. });
  5579. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5580. get: function () {
  5581. return Engine._ALPHA_COMBINE;
  5582. },
  5583. enumerable: true,
  5584. configurable: true
  5585. });
  5586. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5587. get: function () {
  5588. return Engine._ALPHA_SUBTRACT;
  5589. },
  5590. enumerable: true,
  5591. configurable: true
  5592. });
  5593. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5594. get: function () {
  5595. return Engine._ALPHA_MULTIPLY;
  5596. },
  5597. enumerable: true,
  5598. configurable: true
  5599. });
  5600. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5601. get: function () {
  5602. return Engine._ALPHA_MAXIMIZED;
  5603. },
  5604. enumerable: true,
  5605. configurable: true
  5606. });
  5607. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5608. get: function () {
  5609. return Engine._DELAYLOADSTATE_NONE;
  5610. },
  5611. enumerable: true,
  5612. configurable: true
  5613. });
  5614. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5615. get: function () {
  5616. return Engine._DELAYLOADSTATE_LOADED;
  5617. },
  5618. enumerable: true,
  5619. configurable: true
  5620. });
  5621. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5622. get: function () {
  5623. return Engine._DELAYLOADSTATE_LOADING;
  5624. },
  5625. enumerable: true,
  5626. configurable: true
  5627. });
  5628. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5629. get: function () {
  5630. return Engine._DELAYLOADSTATE_NOTLOADED;
  5631. },
  5632. enumerable: true,
  5633. configurable: true
  5634. });
  5635. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5636. get: function () {
  5637. return Engine._TEXTUREFORMAT_ALPHA;
  5638. },
  5639. enumerable: true,
  5640. configurable: true
  5641. });
  5642. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5643. get: function () {
  5644. return Engine._TEXTUREFORMAT_LUMINANCE;
  5645. },
  5646. enumerable: true,
  5647. configurable: true
  5648. });
  5649. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5650. get: function () {
  5651. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5652. },
  5653. enumerable: true,
  5654. configurable: true
  5655. });
  5656. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5657. get: function () {
  5658. return Engine._TEXTUREFORMAT_RGB;
  5659. },
  5660. enumerable: true,
  5661. configurable: true
  5662. });
  5663. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5664. get: function () {
  5665. return Engine._TEXTUREFORMAT_RGBA;
  5666. },
  5667. enumerable: true,
  5668. configurable: true
  5669. });
  5670. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5671. get: function () {
  5672. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5673. },
  5674. enumerable: true,
  5675. configurable: true
  5676. });
  5677. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5678. get: function () {
  5679. return Engine._TEXTURETYPE_FLOAT;
  5680. },
  5681. enumerable: true,
  5682. configurable: true
  5683. });
  5684. Object.defineProperty(Engine, "Version", {
  5685. get: function () {
  5686. return "2.4.0-alpha";
  5687. },
  5688. enumerable: true,
  5689. configurable: true
  5690. });
  5691. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5692. get: function () {
  5693. return this._webGLVersion;
  5694. },
  5695. enumerable: true,
  5696. configurable: true
  5697. });
  5698. Engine.prototype._prepareWorkingCanvas = function () {
  5699. if (this._workingCanvas) {
  5700. return;
  5701. }
  5702. this._workingCanvas = document.createElement("canvas");
  5703. this._workingContext = this._workingCanvas.getContext("2d");
  5704. };
  5705. Engine.prototype.resetTextureCache = function () {
  5706. for (var index = 0; index < this._maxTextureChannels; index++) {
  5707. this._activeTexturesCache[index] = null;
  5708. }
  5709. };
  5710. Engine.prototype.getGlInfo = function () {
  5711. return {
  5712. vendor: this._glVendor,
  5713. renderer: this._glRenderer,
  5714. version: this._glVersion
  5715. };
  5716. };
  5717. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5718. if (useScreen === void 0) { useScreen = false; }
  5719. var viewport = camera.viewport;
  5720. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5721. };
  5722. Engine.prototype.getRenderWidth = function (useScreen) {
  5723. if (useScreen === void 0) { useScreen = false; }
  5724. if (!useScreen && this._currentRenderTarget) {
  5725. return this._currentRenderTarget._width;
  5726. }
  5727. return this._renderingCanvas.width;
  5728. };
  5729. Engine.prototype.getRenderHeight = function (useScreen) {
  5730. if (useScreen === void 0) { useScreen = false; }
  5731. if (!useScreen && this._currentRenderTarget) {
  5732. return this._currentRenderTarget._height;
  5733. }
  5734. return this._renderingCanvas.height;
  5735. };
  5736. Engine.prototype.getRenderingCanvas = function () {
  5737. return this._renderingCanvas;
  5738. };
  5739. Engine.prototype.getRenderingCanvasClientRect = function () {
  5740. return this._renderingCanvas.getBoundingClientRect();
  5741. };
  5742. Engine.prototype.setHardwareScalingLevel = function (level) {
  5743. this._hardwareScalingLevel = level;
  5744. this.resize();
  5745. };
  5746. Engine.prototype.getHardwareScalingLevel = function () {
  5747. return this._hardwareScalingLevel;
  5748. };
  5749. Engine.prototype.getLoadedTexturesCache = function () {
  5750. return this._loadedTexturesCache;
  5751. };
  5752. Engine.prototype.getCaps = function () {
  5753. return this._caps;
  5754. };
  5755. Object.defineProperty(Engine.prototype, "drawCalls", {
  5756. get: function () {
  5757. return this._drawCalls;
  5758. },
  5759. enumerable: true,
  5760. configurable: true
  5761. });
  5762. // Methods
  5763. Engine.prototype.resetDrawCalls = function () {
  5764. this._drawCalls = 0;
  5765. };
  5766. Engine.prototype.setDepthFunctionToGreater = function () {
  5767. this._depthCullingState.depthFunc = this._gl.GREATER;
  5768. };
  5769. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5770. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5771. };
  5772. Engine.prototype.setDepthFunctionToLess = function () {
  5773. this._depthCullingState.depthFunc = this._gl.LESS;
  5774. };
  5775. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5776. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5777. };
  5778. /**
  5779. * stop executing a render loop function and remove it from the execution array
  5780. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5781. */
  5782. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5783. if (!renderFunction) {
  5784. this._activeRenderLoops = [];
  5785. return;
  5786. }
  5787. var index = this._activeRenderLoops.indexOf(renderFunction);
  5788. if (index >= 0) {
  5789. this._activeRenderLoops.splice(index, 1);
  5790. }
  5791. };
  5792. Engine.prototype._renderLoop = function () {
  5793. var shouldRender = true;
  5794. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5795. shouldRender = false;
  5796. }
  5797. if (shouldRender) {
  5798. // Start new frame
  5799. this.beginFrame();
  5800. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5801. var renderFunction = this._activeRenderLoops[index];
  5802. renderFunction();
  5803. }
  5804. // Present
  5805. this.endFrame();
  5806. }
  5807. if (this._activeRenderLoops.length > 0) {
  5808. // Register new frame
  5809. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5810. }
  5811. else {
  5812. this._renderingQueueLaunched = false;
  5813. }
  5814. };
  5815. /**
  5816. * Register and execute a render loop. The engine can have more than one render function.
  5817. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5818. * @example
  5819. * engine.runRenderLoop(function () {
  5820. * scene.render()
  5821. * })
  5822. */
  5823. Engine.prototype.runRenderLoop = function (renderFunction) {
  5824. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5825. return;
  5826. }
  5827. this._activeRenderLoops.push(renderFunction);
  5828. if (!this._renderingQueueLaunched) {
  5829. this._renderingQueueLaunched = true;
  5830. this._bindedRenderFunction = this._renderLoop.bind(this);
  5831. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5832. }
  5833. };
  5834. /**
  5835. * Toggle full screen mode.
  5836. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5837. */
  5838. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5839. if (this.isFullscreen) {
  5840. BABYLON.Tools.ExitFullscreen();
  5841. }
  5842. else {
  5843. this._pointerLockRequested = requestPointerLock;
  5844. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5845. }
  5846. };
  5847. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5848. this.applyStates();
  5849. if (backBuffer) {
  5850. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5851. }
  5852. if (depthStencil && this._depthCullingState.depthMask) {
  5853. this._gl.clearDepth(1.0);
  5854. }
  5855. var mode = 0;
  5856. if (backBuffer) {
  5857. mode |= this._gl.COLOR_BUFFER_BIT;
  5858. }
  5859. if (depthStencil && this._depthCullingState.depthMask) {
  5860. mode |= this._gl.DEPTH_BUFFER_BIT;
  5861. }
  5862. this._gl.clear(mode);
  5863. };
  5864. /**
  5865. * Set the WebGL's viewport
  5866. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5867. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5868. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5869. */
  5870. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5871. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5872. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5873. var x = viewport.x || 0;
  5874. var y = viewport.y || 0;
  5875. this._cachedViewport = viewport;
  5876. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5877. };
  5878. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5879. this._cachedViewport = null;
  5880. this._gl.viewport(x, y, width, height);
  5881. };
  5882. Engine.prototype.beginFrame = function () {
  5883. this._measureFps();
  5884. };
  5885. Engine.prototype.endFrame = function () {
  5886. //this.flushFramebuffer();
  5887. };
  5888. /**
  5889. * resize the view according to the canvas' size.
  5890. * @example
  5891. * window.addEventListener("resize", function () {
  5892. * engine.resize();
  5893. * });
  5894. */
  5895. Engine.prototype.resize = function () {
  5896. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5897. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5898. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5899. for (var index = 0; index < this.scenes.length; index++) {
  5900. var scene = this.scenes[index];
  5901. if (scene.debugLayer.isVisible()) {
  5902. scene.debugLayer._syncPositions();
  5903. }
  5904. }
  5905. };
  5906. /**
  5907. * force a specific size of the canvas
  5908. * @param {number} width - the new canvas' width
  5909. * @param {number} height - the new canvas' height
  5910. */
  5911. Engine.prototype.setSize = function (width, height) {
  5912. this._renderingCanvas.width = width;
  5913. this._renderingCanvas.height = height;
  5914. for (var index = 0; index < this.scenes.length; index++) {
  5915. var scene = this.scenes[index];
  5916. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5917. var cam = scene.cameras[camIndex];
  5918. cam._currentRenderId = 0;
  5919. }
  5920. }
  5921. };
  5922. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5923. this._currentRenderTarget = texture;
  5924. var gl = this._gl;
  5925. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5926. if (texture.isCube) {
  5927. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5928. }
  5929. else {
  5930. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5931. }
  5932. this._gl.viewport(0, 0, texture._width, texture._height);
  5933. this.wipeCaches();
  5934. };
  5935. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5936. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5937. this._currentRenderTarget = null;
  5938. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5939. var gl = this._gl;
  5940. gl.bindTexture(gl.TEXTURE_2D, texture);
  5941. gl.generateMipmap(gl.TEXTURE_2D);
  5942. gl.bindTexture(gl.TEXTURE_2D, null);
  5943. }
  5944. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5945. };
  5946. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5947. if (texture.generateMipMaps) {
  5948. var gl = this._gl;
  5949. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5950. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5951. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5952. }
  5953. };
  5954. Engine.prototype.flushFramebuffer = function () {
  5955. this._gl.flush();
  5956. };
  5957. Engine.prototype.restoreDefaultFramebuffer = function () {
  5958. this._currentRenderTarget = null;
  5959. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5960. this.setViewport(this._cachedViewport);
  5961. this.wipeCaches();
  5962. };
  5963. // VBOs
  5964. Engine.prototype._resetVertexBufferBinding = function () {
  5965. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5966. this._cachedVertexBuffers = null;
  5967. };
  5968. Engine.prototype.createVertexBuffer = function (vertices) {
  5969. var vbo = this._gl.createBuffer();
  5970. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5971. if (vertices instanceof Float32Array) {
  5972. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5973. }
  5974. else {
  5975. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5976. }
  5977. this._resetVertexBufferBinding();
  5978. vbo.references = 1;
  5979. return vbo;
  5980. };
  5981. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5982. var vbo = this._gl.createBuffer();
  5983. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5984. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5985. this._resetVertexBufferBinding();
  5986. vbo.references = 1;
  5987. return vbo;
  5988. };
  5989. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5990. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5991. if (offset === undefined) {
  5992. offset = 0;
  5993. }
  5994. if (vertices instanceof Float32Array) {
  5995. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5996. }
  5997. else {
  5998. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5999. }
  6000. this._resetVertexBufferBinding();
  6001. };
  6002. Engine.prototype._resetIndexBufferBinding = function () {
  6003. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6004. this._cachedIndexBuffer = null;
  6005. };
  6006. Engine.prototype.createIndexBuffer = function (indices) {
  6007. var vbo = this._gl.createBuffer();
  6008. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6009. // Check for 32 bits indices
  6010. var arrayBuffer;
  6011. var need32Bits = false;
  6012. if (this._caps.uintIndices) {
  6013. for (var index = 0; index < indices.length; index++) {
  6014. if (indices[index] > 65535) {
  6015. need32Bits = true;
  6016. break;
  6017. }
  6018. }
  6019. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6020. }
  6021. else {
  6022. arrayBuffer = new Uint16Array(indices);
  6023. }
  6024. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6025. this._resetIndexBufferBinding();
  6026. vbo.references = 1;
  6027. vbo.is32Bits = need32Bits;
  6028. return vbo;
  6029. };
  6030. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6031. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6032. this._cachedVertexBuffers = vertexBuffer;
  6033. this._cachedEffectForVertexBuffers = effect;
  6034. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6035. var offset = 0;
  6036. for (var index = 0; index < vertexDeclaration.length; index++) {
  6037. var order = effect.getAttributeLocation(index);
  6038. if (order >= 0) {
  6039. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6040. }
  6041. offset += vertexDeclaration[index] * 4;
  6042. }
  6043. }
  6044. if (this._cachedIndexBuffer !== indexBuffer) {
  6045. this._cachedIndexBuffer = indexBuffer;
  6046. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6047. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6048. }
  6049. };
  6050. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6051. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6052. this._cachedVertexBuffers = vertexBuffers;
  6053. this._cachedEffectForVertexBuffers = effect;
  6054. var attributes = effect.getAttributesNames();
  6055. for (var index = 0; index < attributes.length; index++) {
  6056. var order = effect.getAttributeLocation(index);
  6057. if (order >= 0) {
  6058. var vertexBuffer = vertexBuffers[attributes[index]];
  6059. if (!vertexBuffer) {
  6060. continue;
  6061. }
  6062. var stride = vertexBuffer.getStrideSize();
  6063. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6064. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6065. }
  6066. }
  6067. }
  6068. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6069. this._cachedIndexBuffer = indexBuffer;
  6070. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6071. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6072. }
  6073. };
  6074. Engine.prototype._releaseBuffer = function (buffer) {
  6075. buffer.references--;
  6076. if (buffer.references === 0) {
  6077. this._gl.deleteBuffer(buffer);
  6078. return true;
  6079. }
  6080. return false;
  6081. };
  6082. Engine.prototype.createInstancesBuffer = function (capacity) {
  6083. var buffer = this._gl.createBuffer();
  6084. buffer.capacity = capacity;
  6085. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6086. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6087. return buffer;
  6088. };
  6089. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6090. this._gl.deleteBuffer(buffer);
  6091. };
  6092. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6093. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6094. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6095. for (var index = 0; index < 4; index++) {
  6096. var offsetLocation = offsetLocations[index];
  6097. this._gl.enableVertexAttribArray(offsetLocation);
  6098. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6099. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6100. }
  6101. };
  6102. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6103. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6104. for (var index = 0; index < 4; index++) {
  6105. var offsetLocation = offsetLocations[index];
  6106. this._gl.disableVertexAttribArray(offsetLocation);
  6107. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6108. }
  6109. };
  6110. Engine.prototype.applyStates = function () {
  6111. this._depthCullingState.apply(this._gl);
  6112. this._alphaState.apply(this._gl);
  6113. };
  6114. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6115. // Apply states
  6116. this.applyStates();
  6117. this._drawCalls++;
  6118. // Render
  6119. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6120. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6121. if (instancesCount) {
  6122. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6123. return;
  6124. }
  6125. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6126. };
  6127. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6128. // Apply states
  6129. this.applyStates();
  6130. this._drawCalls++;
  6131. if (instancesCount) {
  6132. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6133. return;
  6134. }
  6135. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6136. };
  6137. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6138. // Apply states
  6139. this.applyStates();
  6140. this._drawCalls++;
  6141. if (instancesCount) {
  6142. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6143. return;
  6144. }
  6145. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6146. };
  6147. // Shaders
  6148. Engine.prototype._releaseEffect = function (effect) {
  6149. if (this._compiledEffects[effect._key]) {
  6150. delete this._compiledEffects[effect._key];
  6151. if (effect.getProgram()) {
  6152. this._gl.deleteProgram(effect.getProgram());
  6153. }
  6154. }
  6155. };
  6156. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6157. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6158. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6159. var name = vertex + "+" + fragment + "@" + defines;
  6160. if (this._compiledEffects[name]) {
  6161. return this._compiledEffects[name];
  6162. }
  6163. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6164. effect._key = name;
  6165. this._compiledEffects[name] = effect;
  6166. return effect;
  6167. };
  6168. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6169. if (uniformsNames === void 0) { uniformsNames = []; }
  6170. if (samplers === void 0) { samplers = []; }
  6171. if (defines === void 0) { defines = ""; }
  6172. return this.createEffect({
  6173. vertex: "particles",
  6174. fragmentElement: fragmentName
  6175. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6176. };
  6177. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6178. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6179. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6180. var shaderProgram = this._gl.createProgram();
  6181. this._gl.attachShader(shaderProgram, vertexShader);
  6182. this._gl.attachShader(shaderProgram, fragmentShader);
  6183. this._gl.linkProgram(shaderProgram);
  6184. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6185. if (!linked) {
  6186. var error = this._gl.getProgramInfoLog(shaderProgram);
  6187. if (error) {
  6188. throw new Error(error);
  6189. }
  6190. }
  6191. this._gl.deleteShader(vertexShader);
  6192. this._gl.deleteShader(fragmentShader);
  6193. return shaderProgram;
  6194. };
  6195. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6196. var results = [];
  6197. for (var index = 0; index < uniformsNames.length; index++) {
  6198. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6199. }
  6200. return results;
  6201. };
  6202. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6203. var results = [];
  6204. for (var index = 0; index < attributesNames.length; index++) {
  6205. try {
  6206. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6207. }
  6208. catch (e) {
  6209. results.push(-1);
  6210. }
  6211. }
  6212. return results;
  6213. };
  6214. Engine.prototype.enableEffect = function (effect) {
  6215. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6216. if (effect && effect.onBind) {
  6217. effect.onBind(effect);
  6218. }
  6219. return;
  6220. }
  6221. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6222. // Use program
  6223. this._gl.useProgram(effect.getProgram());
  6224. for (var i in this._vertexAttribArrays) {
  6225. //make sure this is a number)
  6226. var iAsNumber = +i;
  6227. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6228. continue;
  6229. }
  6230. this._vertexAttribArrays[iAsNumber] = false;
  6231. this._gl.disableVertexAttribArray(iAsNumber);
  6232. }
  6233. var attributesCount = effect.getAttributesCount();
  6234. for (var index = 0; index < attributesCount; index++) {
  6235. // Attributes
  6236. var order = effect.getAttributeLocation(index);
  6237. if (order >= 0) {
  6238. this._vertexAttribArrays[order] = true;
  6239. this._gl.enableVertexAttribArray(order);
  6240. }
  6241. }
  6242. this._currentEffect = effect;
  6243. if (effect.onBind) {
  6244. effect.onBind(effect);
  6245. }
  6246. };
  6247. Engine.prototype.setArray = function (uniform, array) {
  6248. if (!uniform)
  6249. return;
  6250. this._gl.uniform1fv(uniform, array);
  6251. };
  6252. Engine.prototype.setArray2 = function (uniform, array) {
  6253. if (!uniform || array.length % 2 !== 0)
  6254. return;
  6255. this._gl.uniform2fv(uniform, array);
  6256. };
  6257. Engine.prototype.setArray3 = function (uniform, array) {
  6258. if (!uniform || array.length % 3 !== 0)
  6259. return;
  6260. this._gl.uniform3fv(uniform, array);
  6261. };
  6262. Engine.prototype.setArray4 = function (uniform, array) {
  6263. if (!uniform || array.length % 4 !== 0)
  6264. return;
  6265. this._gl.uniform4fv(uniform, array);
  6266. };
  6267. Engine.prototype.setMatrices = function (uniform, matrices) {
  6268. if (!uniform)
  6269. return;
  6270. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6271. };
  6272. Engine.prototype.setMatrix = function (uniform, matrix) {
  6273. if (!uniform)
  6274. return;
  6275. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6276. };
  6277. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6278. if (!uniform)
  6279. return;
  6280. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6281. };
  6282. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6283. if (!uniform)
  6284. return;
  6285. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6286. };
  6287. Engine.prototype.setFloat = function (uniform, value) {
  6288. if (!uniform)
  6289. return;
  6290. this._gl.uniform1f(uniform, value);
  6291. };
  6292. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6293. if (!uniform)
  6294. return;
  6295. this._gl.uniform2f(uniform, x, y);
  6296. };
  6297. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6298. if (!uniform)
  6299. return;
  6300. this._gl.uniform3f(uniform, x, y, z);
  6301. };
  6302. Engine.prototype.setBool = function (uniform, bool) {
  6303. if (!uniform)
  6304. return;
  6305. this._gl.uniform1i(uniform, bool);
  6306. };
  6307. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6308. if (!uniform)
  6309. return;
  6310. this._gl.uniform4f(uniform, x, y, z, w);
  6311. };
  6312. Engine.prototype.setColor3 = function (uniform, color3) {
  6313. if (!uniform)
  6314. return;
  6315. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6316. };
  6317. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6318. if (!uniform)
  6319. return;
  6320. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6321. };
  6322. // States
  6323. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6324. if (zOffset === void 0) { zOffset = 0; }
  6325. if (reverseSide === void 0) { reverseSide = false; }
  6326. // Culling
  6327. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6328. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6329. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6330. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6331. if (culling) {
  6332. this._depthCullingState.cullFace = cullFace;
  6333. this._depthCullingState.cull = true;
  6334. }
  6335. else {
  6336. this._depthCullingState.cull = false;
  6337. }
  6338. }
  6339. // Z offset
  6340. this._depthCullingState.zOffset = zOffset;
  6341. };
  6342. Engine.prototype.setDepthBuffer = function (enable) {
  6343. this._depthCullingState.depthTest = enable;
  6344. };
  6345. Engine.prototype.getDepthWrite = function () {
  6346. return this._depthCullingState.depthMask;
  6347. };
  6348. Engine.prototype.setDepthWrite = function (enable) {
  6349. this._depthCullingState.depthMask = enable;
  6350. };
  6351. Engine.prototype.setColorWrite = function (enable) {
  6352. this._gl.colorMask(enable, enable, enable, enable);
  6353. };
  6354. Engine.prototype.setAlphaMode = function (mode) {
  6355. if (this._alphaMode === mode) {
  6356. return;
  6357. }
  6358. switch (mode) {
  6359. case Engine.ALPHA_DISABLE:
  6360. this.setDepthWrite(true);
  6361. this._alphaState.alphaBlend = false;
  6362. break;
  6363. case Engine.ALPHA_COMBINE:
  6364. this.setDepthWrite(false);
  6365. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6366. this._alphaState.alphaBlend = true;
  6367. break;
  6368. case Engine.ALPHA_ONEONE:
  6369. this.setDepthWrite(false);
  6370. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6371. this._alphaState.alphaBlend = true;
  6372. break;
  6373. case Engine.ALPHA_ADD:
  6374. this.setDepthWrite(false);
  6375. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6376. this._alphaState.alphaBlend = true;
  6377. break;
  6378. case Engine.ALPHA_SUBTRACT:
  6379. this.setDepthWrite(false);
  6380. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6381. this._alphaState.alphaBlend = true;
  6382. break;
  6383. case Engine.ALPHA_MULTIPLY:
  6384. this.setDepthWrite(false);
  6385. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6386. this._alphaState.alphaBlend = true;
  6387. break;
  6388. case Engine.ALPHA_MAXIMIZED:
  6389. this.setDepthWrite(false);
  6390. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6391. this._alphaState.alphaBlend = true;
  6392. break;
  6393. }
  6394. this._alphaMode = mode;
  6395. };
  6396. Engine.prototype.getAlphaMode = function () {
  6397. return this._alphaMode;
  6398. };
  6399. Engine.prototype.setAlphaTesting = function (enable) {
  6400. this._alphaTest = enable;
  6401. };
  6402. Engine.prototype.getAlphaTesting = function () {
  6403. return this._alphaTest;
  6404. };
  6405. // Textures
  6406. Engine.prototype.wipeCaches = function () {
  6407. this.resetTextureCache();
  6408. this._currentEffect = null;
  6409. this._depthCullingState.reset();
  6410. this._alphaState.reset();
  6411. this._cachedVertexBuffers = null;
  6412. this._cachedIndexBuffer = null;
  6413. this._cachedEffectForVertexBuffers = null;
  6414. };
  6415. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6416. var gl = this._gl;
  6417. gl.bindTexture(gl.TEXTURE_2D, texture);
  6418. var magFilter = gl.NEAREST;
  6419. var minFilter = gl.NEAREST;
  6420. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6421. magFilter = gl.LINEAR;
  6422. minFilter = gl.LINEAR;
  6423. }
  6424. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6425. magFilter = gl.LINEAR;
  6426. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6427. }
  6428. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6429. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6430. gl.bindTexture(gl.TEXTURE_2D, null);
  6431. texture.samplingMode = samplingMode;
  6432. };
  6433. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6434. var _this = this;
  6435. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6436. if (onLoad === void 0) { onLoad = null; }
  6437. if (onError === void 0) { onError = null; }
  6438. if (buffer === void 0) { buffer = null; }
  6439. var texture = this._gl.createTexture();
  6440. var extension;
  6441. var fromData = false;
  6442. if (url.substr(0, 5) === "data:") {
  6443. fromData = true;
  6444. }
  6445. if (!fromData)
  6446. extension = url.substr(url.length - 4, 4).toLowerCase();
  6447. else {
  6448. var oldUrl = url;
  6449. fromData = oldUrl.split(':');
  6450. url = oldUrl;
  6451. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6452. }
  6453. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6454. var isTGA = (extension === ".tga");
  6455. scene._addPendingData(texture);
  6456. texture.url = url;
  6457. texture.noMipmap = noMipmap;
  6458. texture.references = 1;
  6459. texture.samplingMode = samplingMode;
  6460. this._loadedTexturesCache.push(texture);
  6461. var onerror = function () {
  6462. scene._removePendingData(texture);
  6463. if (onError) {
  6464. onError();
  6465. }
  6466. };
  6467. var callback;
  6468. if (isTGA) {
  6469. callback = function (arrayBuffer) {
  6470. var data = new Uint8Array(arrayBuffer);
  6471. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6472. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6473. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6474. }, onLoad, samplingMode);
  6475. };
  6476. if (!(fromData instanceof Array))
  6477. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6478. callback(arrayBuffer);
  6479. }, onerror, scene.database, true);
  6480. else
  6481. callback(buffer);
  6482. }
  6483. else if (isDDS) {
  6484. callback = function (data) {
  6485. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6486. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6487. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6488. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6489. }, onLoad, samplingMode);
  6490. };
  6491. if (!(fromData instanceof Array))
  6492. BABYLON.Tools.LoadFile(url, function (data) {
  6493. callback(data);
  6494. }, onerror, scene.database, true);
  6495. else
  6496. callback(buffer);
  6497. }
  6498. else {
  6499. var onload = function (img) {
  6500. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6501. var isPot = (img.width === potWidth && img.height === potHeight);
  6502. if (!isPot) {
  6503. _this._prepareWorkingCanvas();
  6504. _this._workingCanvas.width = potWidth;
  6505. _this._workingCanvas.height = potHeight;
  6506. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6507. _this._workingContext.imageSmoothingEnabled = false;
  6508. _this._workingContext.mozImageSmoothingEnabled = false;
  6509. _this._workingContext.oImageSmoothingEnabled = false;
  6510. _this._workingContext.webkitImageSmoothingEnabled = false;
  6511. _this._workingContext.msImageSmoothingEnabled = false;
  6512. }
  6513. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6514. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6515. _this._workingContext.imageSmoothingEnabled = true;
  6516. _this._workingContext.mozImageSmoothingEnabled = true;
  6517. _this._workingContext.oImageSmoothingEnabled = true;
  6518. _this._workingContext.webkitImageSmoothingEnabled = true;
  6519. _this._workingContext.msImageSmoothingEnabled = true;
  6520. }
  6521. }
  6522. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6523. }, onLoad, samplingMode);
  6524. };
  6525. if (!(fromData instanceof Array))
  6526. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6527. else
  6528. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6529. }
  6530. return texture;
  6531. };
  6532. Engine.prototype._getInternalFormat = function (format) {
  6533. var internalFormat = this._gl.RGBA;
  6534. switch (format) {
  6535. case Engine.TEXTUREFORMAT_ALPHA:
  6536. internalFormat = this._gl.ALPHA;
  6537. break;
  6538. case Engine.TEXTUREFORMAT_LUMINANCE:
  6539. internalFormat = this._gl.LUMINANCE;
  6540. break;
  6541. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6542. internalFormat = this._gl.LUMINANCE_ALPHA;
  6543. break;
  6544. case Engine.TEXTUREFORMAT_RGB:
  6545. internalFormat = this._gl.RGB;
  6546. break;
  6547. case Engine.TEXTUREFORMAT_RGBA:
  6548. internalFormat = this._gl.RGBA;
  6549. break;
  6550. }
  6551. return internalFormat;
  6552. };
  6553. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6554. if (compression === void 0) { compression = null; }
  6555. var internalFormat = this._getInternalFormat(format);
  6556. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6557. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6558. if (compression) {
  6559. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6560. }
  6561. else {
  6562. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6563. }
  6564. if (texture.generateMipMaps) {
  6565. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6566. }
  6567. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6568. this.resetTextureCache();
  6569. texture.isReady = true;
  6570. };
  6571. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6572. if (compression === void 0) { compression = null; }
  6573. var texture = this._gl.createTexture();
  6574. texture._baseWidth = width;
  6575. texture._baseHeight = height;
  6576. texture._width = width;
  6577. texture._height = height;
  6578. texture.references = 1;
  6579. this.updateRawTexture(texture, data, format, invertY, compression);
  6580. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6581. // Filters
  6582. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6583. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6584. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6585. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6586. texture.samplingMode = samplingMode;
  6587. this._loadedTexturesCache.push(texture);
  6588. return texture;
  6589. };
  6590. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6591. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6592. var texture = this._gl.createTexture();
  6593. texture._baseWidth = width;
  6594. texture._baseHeight = height;
  6595. if (forceExponantOfTwo) {
  6596. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6597. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6598. }
  6599. this.resetTextureCache();
  6600. texture._width = width;
  6601. texture._height = height;
  6602. texture.isReady = false;
  6603. texture.generateMipMaps = generateMipMaps;
  6604. texture.references = 1;
  6605. texture.samplingMode = samplingMode;
  6606. this.updateTextureSamplingMode(samplingMode, texture);
  6607. this._loadedTexturesCache.push(texture);
  6608. return texture;
  6609. };
  6610. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6611. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6612. if (texture.isCube) {
  6613. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6614. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6615. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6616. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6617. }
  6618. else {
  6619. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6620. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6621. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6622. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6623. }
  6624. };
  6625. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6626. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6627. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6628. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6629. if (texture.generateMipMaps) {
  6630. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6631. }
  6632. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6633. this.resetTextureCache();
  6634. texture.isReady = true;
  6635. };
  6636. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6637. if (texture._isDisabled) {
  6638. return;
  6639. }
  6640. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6641. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6642. try {
  6643. // Testing video texture support
  6644. if (this._videoTextureSupported === undefined) {
  6645. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6646. if (this._gl.getError() !== 0) {
  6647. this._videoTextureSupported = false;
  6648. }
  6649. else {
  6650. this._videoTextureSupported = true;
  6651. }
  6652. }
  6653. // Copy video through the current working canvas if video texture is not supported
  6654. if (!this._videoTextureSupported) {
  6655. if (!texture._workingCanvas) {
  6656. texture._workingCanvas = document.createElement("canvas");
  6657. texture._workingContext = texture._workingCanvas.getContext("2d");
  6658. texture._workingCanvas.width = texture._width;
  6659. texture._workingCanvas.height = texture._height;
  6660. }
  6661. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6662. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6663. }
  6664. else {
  6665. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6666. }
  6667. if (texture.generateMipMaps) {
  6668. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6669. }
  6670. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6671. this.resetTextureCache();
  6672. texture.isReady = true;
  6673. }
  6674. catch (ex) {
  6675. // Something unexpected
  6676. // Let's disable the texture
  6677. texture._isDisabled = true;
  6678. }
  6679. };
  6680. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6681. // old version had a "generateMipMaps" arg instead of options.
  6682. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6683. // in the same way, generateDepthBuffer is defaulted to true
  6684. var generateMipMaps = false;
  6685. var generateDepthBuffer = true;
  6686. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6687. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6688. if (options !== undefined) {
  6689. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6690. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6691. type = options.type === undefined ? type : options.type;
  6692. if (options.samplingMode !== undefined) {
  6693. samplingMode = options.samplingMode;
  6694. }
  6695. if (type === Engine.TEXTURETYPE_FLOAT) {
  6696. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6697. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6698. }
  6699. }
  6700. var gl = this._gl;
  6701. var texture = gl.createTexture();
  6702. gl.bindTexture(gl.TEXTURE_2D, texture);
  6703. var width = size.width || size;
  6704. var height = size.height || size;
  6705. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6706. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6707. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6708. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6709. }
  6710. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6711. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6712. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6714. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6715. var depthBuffer;
  6716. // Create the depth buffer
  6717. if (generateDepthBuffer) {
  6718. depthBuffer = gl.createRenderbuffer();
  6719. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6720. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6721. }
  6722. // Create the framebuffer
  6723. var framebuffer = gl.createFramebuffer();
  6724. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6725. if (generateDepthBuffer) {
  6726. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6727. }
  6728. if (generateMipMaps) {
  6729. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6730. }
  6731. // Unbind
  6732. gl.bindTexture(gl.TEXTURE_2D, null);
  6733. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6734. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6735. texture._framebuffer = framebuffer;
  6736. if (generateDepthBuffer) {
  6737. texture._depthBuffer = depthBuffer;
  6738. }
  6739. texture._width = width;
  6740. texture._height = height;
  6741. texture.isReady = true;
  6742. texture.generateMipMaps = generateMipMaps;
  6743. texture.references = 1;
  6744. texture.samplingMode = samplingMode;
  6745. this.resetTextureCache();
  6746. this._loadedTexturesCache.push(texture);
  6747. return texture;
  6748. };
  6749. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6750. var gl = this._gl;
  6751. var texture = gl.createTexture();
  6752. var generateMipMaps = true;
  6753. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6754. if (options !== undefined) {
  6755. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6756. if (options.samplingMode !== undefined) {
  6757. samplingMode = options.samplingMode;
  6758. }
  6759. }
  6760. texture.isCube = true;
  6761. texture.references = 1;
  6762. texture.generateMipMaps = generateMipMaps;
  6763. texture.references = 1;
  6764. texture.samplingMode = samplingMode;
  6765. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6766. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6767. for (var face = 0; face < 6; face++) {
  6768. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6769. }
  6770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6771. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6772. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6774. // Create the depth buffer
  6775. var depthBuffer = gl.createRenderbuffer();
  6776. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6777. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6778. // Create the framebuffer
  6779. var framebuffer = gl.createFramebuffer();
  6780. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6781. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6782. // Mipmaps
  6783. if (texture.generateMipMaps) {
  6784. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6785. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6786. }
  6787. // Unbind
  6788. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6789. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6790. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6791. texture._framebuffer = framebuffer;
  6792. texture._depthBuffer = depthBuffer;
  6793. this.resetTextureCache();
  6794. texture._width = size;
  6795. texture._height = size;
  6796. texture.isReady = true;
  6797. return texture;
  6798. };
  6799. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6800. var _this = this;
  6801. var gl = this._gl;
  6802. var texture = gl.createTexture();
  6803. texture.isCube = true;
  6804. texture.url = rootUrl;
  6805. texture.references = 1;
  6806. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6807. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6808. if (isDDS) {
  6809. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6810. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6811. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6812. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6813. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6814. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6815. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6816. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6817. }
  6818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6822. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6823. _this.resetTextureCache();
  6824. texture._width = info.width;
  6825. texture._height = info.height;
  6826. texture.isReady = true;
  6827. }, null, null, true);
  6828. }
  6829. else {
  6830. cascadeLoad(rootUrl, scene, function (imgs) {
  6831. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6832. var height = width;
  6833. _this._prepareWorkingCanvas();
  6834. _this._workingCanvas.width = width;
  6835. _this._workingCanvas.height = height;
  6836. var faces = [
  6837. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6838. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6839. ];
  6840. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6841. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6842. for (var index = 0; index < faces.length; index++) {
  6843. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6844. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6845. }
  6846. if (!noMipmap) {
  6847. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6848. }
  6849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6853. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6854. _this.resetTextureCache();
  6855. texture._width = width;
  6856. texture._height = height;
  6857. texture.isReady = true;
  6858. }, files);
  6859. }
  6860. return texture;
  6861. };
  6862. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6863. var _this = this;
  6864. var gl = this._gl;
  6865. var texture = gl.createTexture();
  6866. scene._addPendingData(texture);
  6867. texture.isCube = true;
  6868. texture.references = 1;
  6869. texture.url = url;
  6870. var internalFormat = this._getInternalFormat(format);
  6871. var textureType = gl.UNSIGNED_BYTE;
  6872. if (type === Engine.TEXTURETYPE_FLOAT) {
  6873. textureType = gl.FLOAT;
  6874. }
  6875. var width = size;
  6876. var height = width;
  6877. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6878. texture._width = width;
  6879. texture._height = height;
  6880. var onerror = function () {
  6881. scene._removePendingData(texture);
  6882. };
  6883. var internalCallback = function (data) {
  6884. var rgbeDataArrays = callback(data);
  6885. var facesIndex = [
  6886. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6887. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6888. ];
  6889. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6890. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6891. if (!noMipmap && isPot) {
  6892. if (mipmmapGenerator) {
  6893. var arrayTemp = [];
  6894. // Data are known to be in +X +Y +Z -X -Y -Z
  6895. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6896. arrayTemp.push(rgbeDataArrays[0]); // +X
  6897. arrayTemp.push(rgbeDataArrays[3]); // -X
  6898. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6899. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6900. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6901. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6902. var mipData = mipmmapGenerator(arrayTemp);
  6903. for (var level = 0; level < mipData.length; level++) {
  6904. var mipSize = width >> level;
  6905. // mipData is order in +X -X +Y -Y +Z -Z
  6906. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6907. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6908. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6909. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6910. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6911. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6912. }
  6913. }
  6914. else {
  6915. // Data are known to be in +X +Y +Z -X -Y -Z
  6916. for (var index = 0; index < facesIndex.length; index++) {
  6917. var faceData = rgbeDataArrays[index];
  6918. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6919. }
  6920. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6921. }
  6922. }
  6923. else {
  6924. noMipmap = true;
  6925. }
  6926. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6929. }
  6930. else {
  6931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6933. }
  6934. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6935. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6936. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6937. texture.isReady = true;
  6938. _this.resetTextureCache();
  6939. scene._removePendingData(texture);
  6940. };
  6941. BABYLON.Tools.LoadFile(url, function (data) {
  6942. internalCallback(data);
  6943. }, onerror, scene.database, true);
  6944. return texture;
  6945. };
  6946. ;
  6947. Engine.prototype._releaseTexture = function (texture) {
  6948. var gl = this._gl;
  6949. if (texture._framebuffer) {
  6950. gl.deleteFramebuffer(texture._framebuffer);
  6951. }
  6952. if (texture._depthBuffer) {
  6953. gl.deleteRenderbuffer(texture._depthBuffer);
  6954. }
  6955. gl.deleteTexture(texture);
  6956. // Unbind channels
  6957. this.unbindAllTextures();
  6958. var index = this._loadedTexturesCache.indexOf(texture);
  6959. if (index !== -1) {
  6960. this._loadedTexturesCache.splice(index, 1);
  6961. }
  6962. };
  6963. Engine.prototype.bindSamplers = function (effect) {
  6964. this._gl.useProgram(effect.getProgram());
  6965. var samplers = effect.getSamplers();
  6966. for (var index = 0; index < samplers.length; index++) {
  6967. var uniform = effect.getUniform(samplers[index]);
  6968. this._gl.uniform1i(uniform, index);
  6969. }
  6970. this._currentEffect = null;
  6971. };
  6972. Engine.prototype._bindTexture = function (channel, texture) {
  6973. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6974. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6975. this._activeTexturesCache[channel] = null;
  6976. };
  6977. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6978. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6979. };
  6980. Engine.prototype.unbindAllTextures = function () {
  6981. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6982. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6983. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6984. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6985. this._activeTexturesCache[channel] = null;
  6986. }
  6987. };
  6988. Engine.prototype.setTexture = function (channel, texture) {
  6989. if (channel < 0) {
  6990. return;
  6991. }
  6992. // Not ready?
  6993. if (!texture || !texture.isReady()) {
  6994. if (this._activeTexturesCache[channel] != null) {
  6995. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6996. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6997. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6998. this._activeTexturesCache[channel] = null;
  6999. }
  7000. return;
  7001. }
  7002. // Video
  7003. var alreadyActivated = false;
  7004. if (texture instanceof BABYLON.VideoTexture) {
  7005. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7006. alreadyActivated = true;
  7007. texture.update();
  7008. }
  7009. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7010. texture.delayLoad();
  7011. return;
  7012. }
  7013. if (this._activeTexturesCache[channel] === texture) {
  7014. return;
  7015. }
  7016. this._activeTexturesCache[channel] = texture;
  7017. var internalTexture = texture.getInternalTexture();
  7018. if (!alreadyActivated) {
  7019. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7020. }
  7021. if (internalTexture.isCube) {
  7022. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7023. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7024. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7025. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7026. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7027. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7028. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7029. }
  7030. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7031. }
  7032. else {
  7033. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7034. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7035. internalTexture._cachedWrapU = texture.wrapU;
  7036. switch (texture.wrapU) {
  7037. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7038. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7039. break;
  7040. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7041. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7042. break;
  7043. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7044. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7045. break;
  7046. }
  7047. }
  7048. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7049. internalTexture._cachedWrapV = texture.wrapV;
  7050. switch (texture.wrapV) {
  7051. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7052. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7053. break;
  7054. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7055. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7056. break;
  7057. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7058. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7059. break;
  7060. }
  7061. }
  7062. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7063. }
  7064. };
  7065. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7066. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7067. var value = texture.anisotropicFilteringLevel;
  7068. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7069. value = 1;
  7070. }
  7071. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7072. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7073. texture._cachedAnisotropicFilteringLevel = value;
  7074. }
  7075. };
  7076. Engine.prototype.readPixels = function (x, y, width, height) {
  7077. var data = new Uint8Array(height * width * 4);
  7078. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7079. return data;
  7080. };
  7081. Engine.prototype.releaseInternalTexture = function (texture) {
  7082. if (!texture) {
  7083. return;
  7084. }
  7085. texture.references--;
  7086. // Final reference ?
  7087. if (texture.references === 0) {
  7088. var texturesCache = this.getLoadedTexturesCache();
  7089. var index = texturesCache.indexOf(texture);
  7090. if (index > -1) {
  7091. texturesCache.splice(index, 1);
  7092. }
  7093. this._releaseTexture(texture);
  7094. }
  7095. };
  7096. // Dispose
  7097. Engine.prototype.dispose = function () {
  7098. this.hideLoadingUI();
  7099. this.stopRenderLoop();
  7100. // Release scenes
  7101. while (this.scenes.length) {
  7102. this.scenes[0].dispose();
  7103. }
  7104. // Release audio engine
  7105. Engine.audioEngine.dispose();
  7106. // Release effects
  7107. for (var name in this._compiledEffects) {
  7108. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7109. }
  7110. // Unbind
  7111. for (var i in this._vertexAttribArrays) {
  7112. //making sure this is a string
  7113. var iAsNumber = +i;
  7114. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7115. continue;
  7116. }
  7117. this._gl.disableVertexAttribArray(iAsNumber);
  7118. }
  7119. this._gl = null;
  7120. // Events
  7121. window.removeEventListener("blur", this._onBlur);
  7122. window.removeEventListener("focus", this._onFocus);
  7123. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7124. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7125. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7126. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7127. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7128. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7129. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7130. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7131. };
  7132. // Loading screen
  7133. Engine.prototype.displayLoadingUI = function () {
  7134. this._loadingScreen.displayLoadingUI();
  7135. };
  7136. Engine.prototype.hideLoadingUI = function () {
  7137. this._loadingScreen.hideLoadingUI();
  7138. };
  7139. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7140. get: function () {
  7141. return this._loadingScreen;
  7142. },
  7143. set: function (loadingScreen) {
  7144. this._loadingScreen = loadingScreen;
  7145. },
  7146. enumerable: true,
  7147. configurable: true
  7148. });
  7149. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7150. set: function (text) {
  7151. this._loadingScreen.loadingUIText = text;
  7152. },
  7153. enumerable: true,
  7154. configurable: true
  7155. });
  7156. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7157. set: function (color) {
  7158. this._loadingScreen.loadingUIBackgroundColor = color;
  7159. },
  7160. enumerable: true,
  7161. configurable: true
  7162. });
  7163. // FPS
  7164. Engine.prototype.getFps = function () {
  7165. return this.fps;
  7166. };
  7167. Engine.prototype.getDeltaTime = function () {
  7168. return this.deltaTime;
  7169. };
  7170. Engine.prototype._measureFps = function () {
  7171. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7172. var length = this.previousFramesDuration.length;
  7173. if (length >= 2) {
  7174. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7175. }
  7176. if (length >= this.fpsRange) {
  7177. if (length > this.fpsRange) {
  7178. this.previousFramesDuration.splice(0, 1);
  7179. length = this.previousFramesDuration.length;
  7180. }
  7181. var sum = 0;
  7182. for (var id = 0; id < length - 1; id++) {
  7183. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7184. }
  7185. this.fps = 1000.0 / (sum / (length - 1));
  7186. }
  7187. };
  7188. // Statics
  7189. Engine.isSupported = function () {
  7190. try {
  7191. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7192. if (navigator.isCocoonJS) {
  7193. return true;
  7194. }
  7195. var tempcanvas = document.createElement("canvas");
  7196. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7197. return gl != null && !!window.WebGLRenderingContext;
  7198. }
  7199. catch (e) {
  7200. return false;
  7201. }
  7202. };
  7203. // Const statics
  7204. Engine._ALPHA_DISABLE = 0;
  7205. Engine._ALPHA_ADD = 1;
  7206. Engine._ALPHA_COMBINE = 2;
  7207. Engine._ALPHA_SUBTRACT = 3;
  7208. Engine._ALPHA_MULTIPLY = 4;
  7209. Engine._ALPHA_MAXIMIZED = 5;
  7210. Engine._ALPHA_ONEONE = 6;
  7211. Engine._DELAYLOADSTATE_NONE = 0;
  7212. Engine._DELAYLOADSTATE_LOADED = 1;
  7213. Engine._DELAYLOADSTATE_LOADING = 2;
  7214. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7215. Engine._TEXTUREFORMAT_ALPHA = 0;
  7216. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7217. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7218. Engine._TEXTUREFORMAT_RGB = 4;
  7219. Engine._TEXTUREFORMAT_RGBA = 5;
  7220. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7221. Engine._TEXTURETYPE_FLOAT = 1;
  7222. // Updatable statics so stick with vars here
  7223. Engine.CollisionsEpsilon = 0.001;
  7224. Engine.CodeRepository = "src/";
  7225. Engine.ShadersRepository = "src/Shaders/";
  7226. return Engine;
  7227. })();
  7228. BABYLON.Engine = Engine;
  7229. })(BABYLON || (BABYLON = {}));
  7230. var BABYLON;
  7231. (function (BABYLON) {
  7232. /**
  7233. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7234. */
  7235. var Node = (function () {
  7236. /**
  7237. * @constructor
  7238. * @param {string} name - the name and id to be given to this node
  7239. * @param {BABYLON.Scene} the scene this node will be added to
  7240. */
  7241. function Node(name, scene) {
  7242. this.state = "";
  7243. this.animations = new Array();
  7244. this._ranges = {};
  7245. this._childrenFlag = -1;
  7246. this._isEnabled = true;
  7247. this._isReady = true;
  7248. this._currentRenderId = -1;
  7249. this._parentRenderId = -1;
  7250. this.name = name;
  7251. this.id = name;
  7252. this._scene = scene;
  7253. this._initCache();
  7254. }
  7255. Object.defineProperty(Node.prototype, "parent", {
  7256. get: function () {
  7257. return this._parentNode;
  7258. },
  7259. set: function (parent) {
  7260. if (this._parentNode === parent) {
  7261. return;
  7262. }
  7263. if (this._parentNode) {
  7264. var index = this._parentNode._children.indexOf(this);
  7265. if (index !== -1) {
  7266. this._parentNode._children.splice(index, 1);
  7267. }
  7268. }
  7269. this._parentNode = parent;
  7270. if (this._parentNode) {
  7271. if (!this._parentNode._children) {
  7272. this._parentNode._children = new Array();
  7273. }
  7274. this._parentNode._children.push(this);
  7275. }
  7276. },
  7277. enumerable: true,
  7278. configurable: true
  7279. });
  7280. Node.prototype.getScene = function () {
  7281. return this._scene;
  7282. };
  7283. Node.prototype.getEngine = function () {
  7284. return this._scene.getEngine();
  7285. };
  7286. // override it in derived class
  7287. Node.prototype.getWorldMatrix = function () {
  7288. return BABYLON.Matrix.Identity();
  7289. };
  7290. // override it in derived class if you add new variables to the cache
  7291. // and call the parent class method
  7292. Node.prototype._initCache = function () {
  7293. this._cache = {};
  7294. this._cache.parent = undefined;
  7295. };
  7296. Node.prototype.updateCache = function (force) {
  7297. if (!force && this.isSynchronized())
  7298. return;
  7299. this._cache.parent = this.parent;
  7300. this._updateCache();
  7301. };
  7302. // override it in derived class if you add new variables to the cache
  7303. // and call the parent class method if !ignoreParentClass
  7304. Node.prototype._updateCache = function (ignoreParentClass) {
  7305. };
  7306. // override it in derived class if you add new variables to the cache
  7307. Node.prototype._isSynchronized = function () {
  7308. return true;
  7309. };
  7310. Node.prototype._markSyncedWithParent = function () {
  7311. this._parentRenderId = this.parent._currentRenderId;
  7312. };
  7313. Node.prototype.isSynchronizedWithParent = function () {
  7314. if (!this.parent) {
  7315. return true;
  7316. }
  7317. if (this._parentRenderId !== this.parent._currentRenderId) {
  7318. return false;
  7319. }
  7320. return this.parent.isSynchronized();
  7321. };
  7322. Node.prototype.isSynchronized = function (updateCache) {
  7323. var check = this.hasNewParent();
  7324. check = check || !this.isSynchronizedWithParent();
  7325. check = check || !this._isSynchronized();
  7326. if (updateCache)
  7327. this.updateCache(true);
  7328. return !check;
  7329. };
  7330. Node.prototype.hasNewParent = function (update) {
  7331. if (this._cache.parent === this.parent)
  7332. return false;
  7333. if (update)
  7334. this._cache.parent = this.parent;
  7335. return true;
  7336. };
  7337. /**
  7338. * Is this node ready to be used/rendered
  7339. * @return {boolean} is it ready
  7340. */
  7341. Node.prototype.isReady = function () {
  7342. return this._isReady;
  7343. };
  7344. /**
  7345. * Is this node enabled.
  7346. * If the node has a parent and is enabled, the parent will be inspected as well.
  7347. * @return {boolean} whether this node (and its parent) is enabled.
  7348. * @see setEnabled
  7349. */
  7350. Node.prototype.isEnabled = function () {
  7351. if (!this._isEnabled) {
  7352. return false;
  7353. }
  7354. if (this.parent) {
  7355. return this.parent.isEnabled();
  7356. }
  7357. return true;
  7358. };
  7359. /**
  7360. * Set the enabled state of this node.
  7361. * @param {boolean} value - the new enabled state
  7362. * @see isEnabled
  7363. */
  7364. Node.prototype.setEnabled = function (value) {
  7365. this._isEnabled = value;
  7366. };
  7367. /**
  7368. * Is this node a descendant of the given node.
  7369. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7370. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7371. * @see parent
  7372. */
  7373. Node.prototype.isDescendantOf = function (ancestor) {
  7374. if (this.parent) {
  7375. if (this.parent === ancestor) {
  7376. return true;
  7377. }
  7378. return this.parent.isDescendantOf(ancestor);
  7379. }
  7380. return false;
  7381. };
  7382. /**
  7383. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7384. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7385. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7386. * @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.
  7387. */
  7388. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7389. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7390. if (!this._children) {
  7391. return;
  7392. }
  7393. for (var index = 0; index < this._children.length; index++) {
  7394. var item = this._children[index];
  7395. if (!predicate || predicate(item)) {
  7396. results.push(item);
  7397. }
  7398. if (!directDescendantsOnly) {
  7399. item._getDescendants(results, false, predicate);
  7400. }
  7401. }
  7402. };
  7403. /**
  7404. * Will return all nodes that have this node as ascendant.
  7405. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7406. * @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.
  7407. * @return {BABYLON.Node[]} all children nodes of all types.
  7408. */
  7409. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7410. var results = [];
  7411. this._getDescendants(results, directDescendantsOnly, predicate);
  7412. return results;
  7413. };
  7414. /**
  7415. * @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.
  7416. * @Deprecated, legacy support.
  7417. * use getDecendants instead.
  7418. */
  7419. Node.prototype.getChildren = function (predicate) {
  7420. return this.getDescendants(true, predicate);
  7421. };
  7422. /**
  7423. * Get all child-meshes of this node.
  7424. */
  7425. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7426. var results = [];
  7427. this._getDescendants(results, directDecendantsOnly, function (node) {
  7428. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7429. });
  7430. return results;
  7431. };
  7432. Node.prototype._setReady = function (state) {
  7433. if (state === this._isReady) {
  7434. return;
  7435. }
  7436. if (!state) {
  7437. this._isReady = false;
  7438. return;
  7439. }
  7440. this._isReady = true;
  7441. if (this.onReady) {
  7442. this.onReady(this);
  7443. }
  7444. };
  7445. Node.prototype.getAnimationByName = function (name) {
  7446. for (var i = 0; i < this.animations.length; i++) {
  7447. var animation = this.animations[i];
  7448. if (animation.name === name) {
  7449. return animation;
  7450. }
  7451. }
  7452. return null;
  7453. };
  7454. Node.prototype.createAnimationRange = function (name, from, to) {
  7455. // check name not already in use
  7456. if (!this._ranges[name]) {
  7457. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7458. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7459. if (this.animations[i]) {
  7460. this.animations[i].createRange(name, from, to);
  7461. }
  7462. }
  7463. }
  7464. };
  7465. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7466. if (deleteFrames === void 0) { deleteFrames = true; }
  7467. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7468. if (this.animations[i]) {
  7469. this.animations[i].deleteRange(name, deleteFrames);
  7470. }
  7471. }
  7472. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7473. };
  7474. Node.prototype.getAnimationRange = function (name) {
  7475. return this._ranges[name];
  7476. };
  7477. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7478. var range = this.getAnimationRange(name);
  7479. if (!range) {
  7480. return null;
  7481. }
  7482. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7483. };
  7484. Node.prototype.serializeAnimationRanges = function () {
  7485. var serializationRanges = [];
  7486. for (var name in this._ranges) {
  7487. var range = {};
  7488. range.name = name;
  7489. range.from = this._ranges[name].from;
  7490. range.to = this._ranges[name].to;
  7491. serializationRanges.push(range);
  7492. }
  7493. return serializationRanges;
  7494. };
  7495. Node.prototype.dispose = function () {
  7496. this.parent = null;
  7497. };
  7498. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7499. if (parsedNode.ranges) {
  7500. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7501. var data = parsedNode.ranges[index];
  7502. node.createAnimationRange(data.name, data.from, data.to);
  7503. }
  7504. }
  7505. };
  7506. __decorate([
  7507. BABYLON.serialize()
  7508. ], Node.prototype, "name", void 0);
  7509. __decorate([
  7510. BABYLON.serialize()
  7511. ], Node.prototype, "id", void 0);
  7512. __decorate([
  7513. BABYLON.serialize()
  7514. ], Node.prototype, "uniqueId", void 0);
  7515. __decorate([
  7516. BABYLON.serialize()
  7517. ], Node.prototype, "state", void 0);
  7518. return Node;
  7519. })();
  7520. BABYLON.Node = Node;
  7521. })(BABYLON || (BABYLON = {}));
  7522. var BABYLON;
  7523. (function (BABYLON) {
  7524. var FilesInput = (function () {
  7525. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7526. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7527. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7528. this._engine = p_engine;
  7529. this._canvas = p_canvas;
  7530. this._currentScene = p_scene;
  7531. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7532. this._progressCallback = p_progressCallback;
  7533. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7534. this._textureLoadingCallback = p_textureLoadingCallback;
  7535. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7536. }
  7537. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7538. var _this = this;
  7539. if (p_elementToMonitor) {
  7540. this._elementToMonitor = p_elementToMonitor;
  7541. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7542. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7543. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7544. }
  7545. };
  7546. FilesInput.prototype.renderFunction = function () {
  7547. if (this._additionnalRenderLoopLogicCallback) {
  7548. this._additionnalRenderLoopLogicCallback();
  7549. }
  7550. if (this._currentScene) {
  7551. if (this._textureLoadingCallback) {
  7552. var remaining = this._currentScene.getWaitingItemsCount();
  7553. if (remaining > 0) {
  7554. this._textureLoadingCallback(remaining);
  7555. }
  7556. }
  7557. this._currentScene.render();
  7558. }
  7559. };
  7560. FilesInput.prototype.drag = function (e) {
  7561. e.stopPropagation();
  7562. e.preventDefault();
  7563. };
  7564. FilesInput.prototype.drop = function (eventDrop) {
  7565. eventDrop.stopPropagation();
  7566. eventDrop.preventDefault();
  7567. this.loadFiles(eventDrop);
  7568. };
  7569. FilesInput.prototype.loadFiles = function (event) {
  7570. if (this._startingProcessingFilesCallback)
  7571. this._startingProcessingFilesCallback();
  7572. // Handling data transfer via drag'n'drop
  7573. if (event && event.dataTransfer && event.dataTransfer.files) {
  7574. this._filesToLoad = event.dataTransfer.files;
  7575. }
  7576. // Handling files from input files
  7577. if (event && event.target && event.target.files) {
  7578. this._filesToLoad = event.target.files;
  7579. }
  7580. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7581. for (var i = 0; i < this._filesToLoad.length; i++) {
  7582. switch (this._filesToLoad[i].type) {
  7583. case "image/jpeg":
  7584. case "image/png":
  7585. case "image/bmp":
  7586. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7587. break;
  7588. case "image/targa":
  7589. case "image/vnd.ms-dds":
  7590. case "audio/wav":
  7591. case "audio/x-wav":
  7592. case "audio/mp3":
  7593. case "audio/mpeg":
  7594. case "audio/mpeg3":
  7595. case "audio/x-mpeg-3":
  7596. case "audio/ogg":
  7597. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7598. break;
  7599. default:
  7600. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  7601. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7602. }
  7603. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  7604. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7605. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  7606. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7607. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7608. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7609. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7610. this._sceneFileToLoad = this._filesToLoad[i];
  7611. }
  7612. break;
  7613. }
  7614. }
  7615. this.reload();
  7616. }
  7617. };
  7618. FilesInput.prototype.reload = function () {
  7619. var _this = this;
  7620. var that = this;
  7621. // If a ".babylon" file has been provided
  7622. if (this._sceneFileToLoad) {
  7623. if (this._currentScene) {
  7624. if (BABYLON.Tools.errorsCount > 0) {
  7625. BABYLON.Tools.ClearLogCache();
  7626. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7627. }
  7628. this._engine.stopRenderLoop();
  7629. this._currentScene.dispose();
  7630. }
  7631. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7632. that._currentScene = newScene;
  7633. // Wait for textures and shaders to be ready
  7634. that._currentScene.executeWhenReady(function () {
  7635. // Attach camera to canvas inputs
  7636. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7637. that._currentScene.createDefaultCameraOrLight();
  7638. }
  7639. that._currentScene.activeCamera.attachControl(that._canvas);
  7640. if (that._sceneLoadedCallback) {
  7641. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7642. }
  7643. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7644. });
  7645. }, function (progress) {
  7646. if (_this._progressCallback) {
  7647. _this._progressCallback(progress);
  7648. }
  7649. });
  7650. }
  7651. else {
  7652. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7653. }
  7654. };
  7655. FilesInput.FilesTextures = new Array();
  7656. FilesInput.FilesToLoad = new Array();
  7657. return FilesInput;
  7658. })();
  7659. BABYLON.FilesInput = FilesInput;
  7660. })(BABYLON || (BABYLON = {}));
  7661. var BABYLON;
  7662. (function (BABYLON) {
  7663. var IntersectionInfo = (function () {
  7664. function IntersectionInfo(bu, bv, distance) {
  7665. this.bu = bu;
  7666. this.bv = bv;
  7667. this.distance = distance;
  7668. this.faceId = 0;
  7669. this.subMeshId = 0;
  7670. }
  7671. return IntersectionInfo;
  7672. })();
  7673. BABYLON.IntersectionInfo = IntersectionInfo;
  7674. var PickingInfo = (function () {
  7675. function PickingInfo() {
  7676. this.hit = false;
  7677. this.distance = 0;
  7678. this.pickedPoint = null;
  7679. this.pickedMesh = null;
  7680. this.bu = 0;
  7681. this.bv = 0;
  7682. this.faceId = -1;
  7683. this.subMeshId = 0;
  7684. this.pickedSprite = null;
  7685. }
  7686. // Methods
  7687. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7688. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7689. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7690. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7691. return null;
  7692. }
  7693. var indices = this.pickedMesh.getIndices();
  7694. var result;
  7695. if (useVerticesNormals) {
  7696. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7697. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7698. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7699. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7700. normal0 = normal0.scale(this.bu);
  7701. normal1 = normal1.scale(this.bv);
  7702. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7703. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7704. }
  7705. else {
  7706. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7707. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7708. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7709. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7710. var p1p2 = vertex1.subtract(vertex2);
  7711. var p3p2 = vertex3.subtract(vertex2);
  7712. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7713. }
  7714. if (useWorldCoordinates) {
  7715. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7716. }
  7717. return BABYLON.Vector3.Normalize(result);
  7718. };
  7719. PickingInfo.prototype.getTextureCoordinates = function () {
  7720. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7721. return null;
  7722. }
  7723. var indices = this.pickedMesh.getIndices();
  7724. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7725. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7726. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7727. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7728. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7729. uv1 = uv1.scale(this.bu);
  7730. uv2 = uv2.scale(this.bv);
  7731. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7732. };
  7733. return PickingInfo;
  7734. })();
  7735. BABYLON.PickingInfo = PickingInfo;
  7736. })(BABYLON || (BABYLON = {}));
  7737. var BABYLON;
  7738. (function (BABYLON) {
  7739. var BoundingSphere = (function () {
  7740. function BoundingSphere(minimum, maximum) {
  7741. this.minimum = minimum;
  7742. this.maximum = maximum;
  7743. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7744. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7745. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7746. this.radius = distance * 0.5;
  7747. this.centerWorld = BABYLON.Vector3.Zero();
  7748. this._update(BABYLON.Matrix.Identity());
  7749. }
  7750. // Methods
  7751. BoundingSphere.prototype._update = function (world) {
  7752. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7753. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7754. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7755. };
  7756. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7757. for (var i = 0; i < 6; i++) {
  7758. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7759. return false;
  7760. }
  7761. return true;
  7762. };
  7763. BoundingSphere.prototype.intersectsPoint = function (point) {
  7764. var x = this.centerWorld.x - point.x;
  7765. var y = this.centerWorld.y - point.y;
  7766. var z = this.centerWorld.z - point.z;
  7767. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7768. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7769. return false;
  7770. return true;
  7771. };
  7772. // Statics
  7773. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7774. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7775. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7776. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7777. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7778. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7779. return false;
  7780. return true;
  7781. };
  7782. return BoundingSphere;
  7783. })();
  7784. BABYLON.BoundingSphere = BoundingSphere;
  7785. })(BABYLON || (BABYLON = {}));
  7786. var BABYLON;
  7787. (function (BABYLON) {
  7788. var BoundingBox = (function () {
  7789. function BoundingBox(minimum, maximum) {
  7790. this.minimum = minimum;
  7791. this.maximum = maximum;
  7792. this.vectors = new Array();
  7793. this.vectorsWorld = new Array();
  7794. // Bounding vectors
  7795. this.vectors.push(this.minimum.clone());
  7796. this.vectors.push(this.maximum.clone());
  7797. this.vectors.push(this.minimum.clone());
  7798. this.vectors[2].x = this.maximum.x;
  7799. this.vectors.push(this.minimum.clone());
  7800. this.vectors[3].y = this.maximum.y;
  7801. this.vectors.push(this.minimum.clone());
  7802. this.vectors[4].z = this.maximum.z;
  7803. this.vectors.push(this.maximum.clone());
  7804. this.vectors[5].z = this.minimum.z;
  7805. this.vectors.push(this.maximum.clone());
  7806. this.vectors[6].x = this.minimum.x;
  7807. this.vectors.push(this.maximum.clone());
  7808. this.vectors[7].y = this.minimum.y;
  7809. // OBB
  7810. this.center = this.maximum.add(this.minimum).scale(0.5);
  7811. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7812. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7813. // World
  7814. for (var index = 0; index < this.vectors.length; index++) {
  7815. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7816. }
  7817. this.minimumWorld = BABYLON.Vector3.Zero();
  7818. this.maximumWorld = BABYLON.Vector3.Zero();
  7819. this._update(BABYLON.Matrix.Identity());
  7820. }
  7821. // Methods
  7822. BoundingBox.prototype.getWorldMatrix = function () {
  7823. return this._worldMatrix;
  7824. };
  7825. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7826. this._worldMatrix.copyFrom(matrix);
  7827. return this;
  7828. };
  7829. BoundingBox.prototype._update = function (world) {
  7830. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7831. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7832. for (var index = 0; index < this.vectors.length; index++) {
  7833. var v = this.vectorsWorld[index];
  7834. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7835. if (v.x < this.minimumWorld.x)
  7836. this.minimumWorld.x = v.x;
  7837. if (v.y < this.minimumWorld.y)
  7838. this.minimumWorld.y = v.y;
  7839. if (v.z < this.minimumWorld.z)
  7840. this.minimumWorld.z = v.z;
  7841. if (v.x > this.maximumWorld.x)
  7842. this.maximumWorld.x = v.x;
  7843. if (v.y > this.maximumWorld.y)
  7844. this.maximumWorld.y = v.y;
  7845. if (v.z > this.maximumWorld.z)
  7846. this.maximumWorld.z = v.z;
  7847. }
  7848. // OBB
  7849. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7850. this.center.scaleInPlace(0.5);
  7851. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7852. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7853. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7854. this._worldMatrix = world;
  7855. };
  7856. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7857. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7858. };
  7859. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7860. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7861. };
  7862. BoundingBox.prototype.intersectsPoint = function (point) {
  7863. var delta = -BABYLON.Epsilon;
  7864. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7865. return false;
  7866. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7867. return false;
  7868. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7869. return false;
  7870. return true;
  7871. };
  7872. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7873. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7874. };
  7875. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7876. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7877. return false;
  7878. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7879. return false;
  7880. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7881. return false;
  7882. return true;
  7883. };
  7884. // Statics
  7885. BoundingBox.Intersects = function (box0, box1) {
  7886. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7887. return false;
  7888. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7889. return false;
  7890. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7891. return false;
  7892. return true;
  7893. };
  7894. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7895. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7896. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7897. return (num <= (sphereRadius * sphereRadius));
  7898. };
  7899. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7900. for (var p = 0; p < 6; p++) {
  7901. for (var i = 0; i < 8; i++) {
  7902. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7903. return false;
  7904. }
  7905. }
  7906. }
  7907. return true;
  7908. };
  7909. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7910. for (var p = 0; p < 6; p++) {
  7911. var inCount = 8;
  7912. for (var i = 0; i < 8; i++) {
  7913. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7914. --inCount;
  7915. }
  7916. else {
  7917. break;
  7918. }
  7919. }
  7920. if (inCount === 0)
  7921. return false;
  7922. }
  7923. return true;
  7924. };
  7925. return BoundingBox;
  7926. })();
  7927. BABYLON.BoundingBox = BoundingBox;
  7928. })(BABYLON || (BABYLON = {}));
  7929. var BABYLON;
  7930. (function (BABYLON) {
  7931. var computeBoxExtents = function (axis, box) {
  7932. var p = BABYLON.Vector3.Dot(box.center, axis);
  7933. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7934. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7935. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7936. var r = r0 + r1 + r2;
  7937. return {
  7938. min: p - r,
  7939. max: p + r
  7940. };
  7941. };
  7942. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7943. var axisOverlap = function (axis, box0, box1) {
  7944. var result0 = computeBoxExtents(axis, box0);
  7945. var result1 = computeBoxExtents(axis, box1);
  7946. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7947. };
  7948. var BoundingInfo = (function () {
  7949. function BoundingInfo(minimum, maximum) {
  7950. this.minimum = minimum;
  7951. this.maximum = maximum;
  7952. this._isLocked = false;
  7953. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7954. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7955. }
  7956. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7957. get: function () {
  7958. return this._isLocked;
  7959. },
  7960. set: function (value) {
  7961. this._isLocked = value;
  7962. },
  7963. enumerable: true,
  7964. configurable: true
  7965. });
  7966. // Methods
  7967. BoundingInfo.prototype.update = function (world) {
  7968. if (this._isLocked) {
  7969. return;
  7970. }
  7971. this.boundingBox._update(world);
  7972. this.boundingSphere._update(world);
  7973. };
  7974. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7975. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7976. return false;
  7977. return this.boundingBox.isInFrustum(frustumPlanes);
  7978. };
  7979. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7980. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7981. };
  7982. BoundingInfo.prototype._checkCollision = function (collider) {
  7983. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7984. };
  7985. BoundingInfo.prototype.intersectsPoint = function (point) {
  7986. if (!this.boundingSphere.centerWorld) {
  7987. return false;
  7988. }
  7989. if (!this.boundingSphere.intersectsPoint(point)) {
  7990. return false;
  7991. }
  7992. if (!this.boundingBox.intersectsPoint(point)) {
  7993. return false;
  7994. }
  7995. return true;
  7996. };
  7997. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7998. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7999. return false;
  8000. }
  8001. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8002. return false;
  8003. }
  8004. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8005. return false;
  8006. }
  8007. if (!precise) {
  8008. return true;
  8009. }
  8010. var box0 = this.boundingBox;
  8011. var box1 = boundingInfo.boundingBox;
  8012. if (!axisOverlap(box0.directions[0], box0, box1))
  8013. return false;
  8014. if (!axisOverlap(box0.directions[1], box0, box1))
  8015. return false;
  8016. if (!axisOverlap(box0.directions[2], box0, box1))
  8017. return false;
  8018. if (!axisOverlap(box1.directions[0], box0, box1))
  8019. return false;
  8020. if (!axisOverlap(box1.directions[1], box0, box1))
  8021. return false;
  8022. if (!axisOverlap(box1.directions[2], box0, box1))
  8023. return false;
  8024. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8025. return false;
  8026. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8027. return false;
  8028. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8029. return false;
  8030. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8031. return false;
  8032. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8033. return false;
  8034. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8035. return false;
  8036. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8037. return false;
  8038. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8039. return false;
  8040. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8041. return false;
  8042. return true;
  8043. };
  8044. return BoundingInfo;
  8045. })();
  8046. BABYLON.BoundingInfo = BoundingInfo;
  8047. })(BABYLON || (BABYLON = {}));
  8048. var BABYLON;
  8049. (function (BABYLON) {
  8050. var Ray = (function () {
  8051. function Ray(origin, direction, length) {
  8052. if (length === void 0) { length = Number.MAX_VALUE; }
  8053. this.origin = origin;
  8054. this.direction = direction;
  8055. this.length = length;
  8056. }
  8057. // Methods
  8058. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8059. var d = 0.0;
  8060. var maxValue = Number.MAX_VALUE;
  8061. var inv;
  8062. var min;
  8063. var max;
  8064. var temp;
  8065. if (Math.abs(this.direction.x) < 0.0000001) {
  8066. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8067. return false;
  8068. }
  8069. }
  8070. else {
  8071. inv = 1.0 / this.direction.x;
  8072. min = (minimum.x - this.origin.x) * inv;
  8073. max = (maximum.x - this.origin.x) * inv;
  8074. if (max === -Infinity) {
  8075. max = Infinity;
  8076. }
  8077. if (min > max) {
  8078. temp = min;
  8079. min = max;
  8080. max = temp;
  8081. }
  8082. d = Math.max(min, d);
  8083. maxValue = Math.min(max, maxValue);
  8084. if (d > maxValue) {
  8085. return false;
  8086. }
  8087. }
  8088. if (Math.abs(this.direction.y) < 0.0000001) {
  8089. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8090. return false;
  8091. }
  8092. }
  8093. else {
  8094. inv = 1.0 / this.direction.y;
  8095. min = (minimum.y - this.origin.y) * inv;
  8096. max = (maximum.y - this.origin.y) * inv;
  8097. if (max === -Infinity) {
  8098. max = Infinity;
  8099. }
  8100. if (min > max) {
  8101. temp = min;
  8102. min = max;
  8103. max = temp;
  8104. }
  8105. d = Math.max(min, d);
  8106. maxValue = Math.min(max, maxValue);
  8107. if (d > maxValue) {
  8108. return false;
  8109. }
  8110. }
  8111. if (Math.abs(this.direction.z) < 0.0000001) {
  8112. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8113. return false;
  8114. }
  8115. }
  8116. else {
  8117. inv = 1.0 / this.direction.z;
  8118. min = (minimum.z - this.origin.z) * inv;
  8119. max = (maximum.z - this.origin.z) * inv;
  8120. if (max === -Infinity) {
  8121. max = Infinity;
  8122. }
  8123. if (min > max) {
  8124. temp = min;
  8125. min = max;
  8126. max = temp;
  8127. }
  8128. d = Math.max(min, d);
  8129. maxValue = Math.min(max, maxValue);
  8130. if (d > maxValue) {
  8131. return false;
  8132. }
  8133. }
  8134. return true;
  8135. };
  8136. Ray.prototype.intersectsBox = function (box) {
  8137. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8138. };
  8139. Ray.prototype.intersectsSphere = function (sphere) {
  8140. var x = sphere.center.x - this.origin.x;
  8141. var y = sphere.center.y - this.origin.y;
  8142. var z = sphere.center.z - this.origin.z;
  8143. var pyth = (x * x) + (y * y) + (z * z);
  8144. var rr = sphere.radius * sphere.radius;
  8145. if (pyth <= rr) {
  8146. return true;
  8147. }
  8148. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8149. if (dot < 0.0) {
  8150. return false;
  8151. }
  8152. var temp = pyth - (dot * dot);
  8153. return temp <= rr;
  8154. };
  8155. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8156. if (!this._edge1) {
  8157. this._edge1 = BABYLON.Vector3.Zero();
  8158. this._edge2 = BABYLON.Vector3.Zero();
  8159. this._pvec = BABYLON.Vector3.Zero();
  8160. this._tvec = BABYLON.Vector3.Zero();
  8161. this._qvec = BABYLON.Vector3.Zero();
  8162. }
  8163. vertex1.subtractToRef(vertex0, this._edge1);
  8164. vertex2.subtractToRef(vertex0, this._edge2);
  8165. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8166. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8167. if (det === 0) {
  8168. return null;
  8169. }
  8170. var invdet = 1 / det;
  8171. this.origin.subtractToRef(vertex0, this._tvec);
  8172. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8173. if (bu < 0 || bu > 1.0) {
  8174. return null;
  8175. }
  8176. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8177. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8178. if (bv < 0 || bu + bv > 1.0) {
  8179. return null;
  8180. }
  8181. //check if the distance is longer than the predefined length.
  8182. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8183. if (distance > this.length) {
  8184. return null;
  8185. }
  8186. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8187. };
  8188. Ray.prototype.intersectsPlane = function (plane) {
  8189. var distance;
  8190. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8191. if (Math.abs(result1) < 9.99999997475243E-07) {
  8192. return null;
  8193. }
  8194. else {
  8195. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8196. distance = (-plane.d - result2) / result1;
  8197. if (distance < 0.0) {
  8198. if (distance < -9.99999997475243E-07) {
  8199. return null;
  8200. }
  8201. else {
  8202. return 0;
  8203. }
  8204. }
  8205. return distance;
  8206. }
  8207. };
  8208. /**
  8209. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8210. * @param sega the first point of the segment to test the intersection against
  8211. * @param segb the second point of the segment to test the intersection against
  8212. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8213. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8214. */
  8215. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8216. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8217. var u = segb.subtract(sega);
  8218. var v = rsegb.subtract(this.origin);
  8219. var w = sega.subtract(this.origin);
  8220. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8221. var b = BABYLON.Vector3.Dot(u, v);
  8222. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8223. var d = BABYLON.Vector3.Dot(u, w);
  8224. var e = BABYLON.Vector3.Dot(v, w);
  8225. var D = a * c - b * b; // always >= 0
  8226. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8227. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8228. // compute the line parameters of the two closest points
  8229. if (D < Ray.smallnum) {
  8230. sN = 0.0; // force using point P0 on segment S1
  8231. sD = 1.0; // to prevent possible division by 0.0 later
  8232. tN = e;
  8233. tD = c;
  8234. }
  8235. else {
  8236. sN = (b * e - c * d);
  8237. tN = (a * e - b * d);
  8238. if (sN < 0.0) {
  8239. sN = 0.0;
  8240. tN = e;
  8241. tD = c;
  8242. }
  8243. else if (sN > sD) {
  8244. sN = sD;
  8245. tN = e + b;
  8246. tD = c;
  8247. }
  8248. }
  8249. if (tN < 0.0) {
  8250. tN = 0.0;
  8251. // recompute sc for this edge
  8252. if (-d < 0.0) {
  8253. sN = 0.0;
  8254. }
  8255. else if (-d > a)
  8256. sN = sD;
  8257. else {
  8258. sN = -d;
  8259. sD = a;
  8260. }
  8261. }
  8262. else if (tN > tD) {
  8263. tN = tD;
  8264. // recompute sc for this edge
  8265. if ((-d + b) < 0.0) {
  8266. sN = 0;
  8267. }
  8268. else if ((-d + b) > a) {
  8269. sN = sD;
  8270. }
  8271. else {
  8272. sN = (-d + b);
  8273. sD = a;
  8274. }
  8275. }
  8276. // finally do the division to get sc and tc
  8277. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8278. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8279. // get the difference of the two closest points
  8280. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(v.multiplyByFloats(tc, tc, tc)); // = S1(sc) - S2(tc)
  8281. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8282. if (isIntersected) {
  8283. return tc;
  8284. }
  8285. return -1;
  8286. };
  8287. // Statics
  8288. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8289. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8290. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8291. var direction = end.subtract(start);
  8292. direction.normalize();
  8293. return new Ray(start, direction);
  8294. };
  8295. /**
  8296. * 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
  8297. * transformed to the given world matrix.
  8298. * @param origin The origin point
  8299. * @param end The end point
  8300. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8301. */
  8302. Ray.CreateNewFromTo = function (origin, end, world) {
  8303. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8304. var direction = end.subtract(origin);
  8305. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8306. direction.normalize();
  8307. return Ray.Transform(new Ray(origin, direction, length), world);
  8308. };
  8309. Ray.Transform = function (ray, matrix) {
  8310. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8311. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8312. newDirection.normalize();
  8313. return new Ray(newOrigin, newDirection, ray.length);
  8314. };
  8315. Ray.smallnum = 0.00000001;
  8316. Ray.rayl = 10e8;
  8317. return Ray;
  8318. })();
  8319. BABYLON.Ray = Ray;
  8320. })(BABYLON || (BABYLON = {}));
  8321. var BABYLON;
  8322. (function (BABYLON) {
  8323. var AbstractMesh = (function (_super) {
  8324. __extends(AbstractMesh, _super);
  8325. // Constructor
  8326. function AbstractMesh(name, scene) {
  8327. var _this = this;
  8328. _super.call(this, name, scene);
  8329. // Events
  8330. /**
  8331. * An event triggered when this mesh collides with another one
  8332. * @type {BABYLON.Observable}
  8333. */
  8334. this.onCollideObservable = new BABYLON.Observable();
  8335. /**
  8336. * An event triggered when the collision's position changes
  8337. * @type {BABYLON.Observable}
  8338. */
  8339. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8340. /**
  8341. * An event triggered after the world matrix is updated
  8342. * @type {BABYLON.Observable}
  8343. */
  8344. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8345. // Properties
  8346. this.definedFacingForward = true; // orientation for POV movement & rotation
  8347. this.position = new BABYLON.Vector3(0, 0, 0);
  8348. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8349. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8350. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8351. this.visibility = 1.0;
  8352. this.alphaIndex = Number.MAX_VALUE;
  8353. this.infiniteDistance = false;
  8354. this.isVisible = true;
  8355. this.isPickable = true;
  8356. this.showBoundingBox = false;
  8357. this.showSubMeshesBoundingBox = false;
  8358. this.onDispose = null;
  8359. this.isBlocker = false;
  8360. this.renderingGroupId = 0;
  8361. this.receiveShadows = false;
  8362. this.renderOutline = false;
  8363. this.outlineColor = BABYLON.Color3.Red();
  8364. this.outlineWidth = 0.02;
  8365. this.renderOverlay = false;
  8366. this.overlayColor = BABYLON.Color3.Red();
  8367. this.overlayAlpha = 0.5;
  8368. this.hasVertexAlpha = false;
  8369. this.useVertexColors = true;
  8370. this.applyFog = true;
  8371. this.computeBonesUsingShaders = true;
  8372. this.scalingDeterminant = 1;
  8373. this.numBoneInfluencers = 4;
  8374. this.useOctreeForRenderingSelection = true;
  8375. this.useOctreeForPicking = true;
  8376. this.useOctreeForCollisions = true;
  8377. this.layerMask = 0x0FFFFFFF;
  8378. this.alwaysSelectAsActiveMesh = false;
  8379. // Collisions
  8380. this._checkCollisions = false;
  8381. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8382. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8383. this._collider = new BABYLON.Collider();
  8384. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8385. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8386. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8387. // Edges
  8388. this.edgesWidth = 1;
  8389. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8390. // Cache
  8391. this._localWorld = BABYLON.Matrix.Zero();
  8392. this._worldMatrix = BABYLON.Matrix.Zero();
  8393. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8394. this._absolutePosition = BABYLON.Vector3.Zero();
  8395. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8396. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8397. this._isDirty = false;
  8398. this._pivotMatrix = BABYLON.Matrix.Identity();
  8399. this._isDisposed = false;
  8400. this._renderId = 0;
  8401. this._intersectionsInProgress = new Array();
  8402. this._isWorldMatrixFrozen = false;
  8403. this._unIndexed = false;
  8404. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8405. if (collidedMesh === void 0) { collidedMesh = null; }
  8406. //TODO move this to the collision coordinator!
  8407. if (_this.getScene().workerCollisions)
  8408. newPosition.multiplyInPlace(_this._collider.radius);
  8409. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8410. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8411. _this.position.addInPlace(_this._diffPositionForCollisions);
  8412. }
  8413. if (collidedMesh) {
  8414. _this.onCollideObservable.notifyObservers(collidedMesh);
  8415. }
  8416. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8417. };
  8418. scene.addMesh(this);
  8419. }
  8420. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8421. get: function () {
  8422. return AbstractMesh._BILLBOARDMODE_NONE;
  8423. },
  8424. enumerable: true,
  8425. configurable: true
  8426. });
  8427. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8428. get: function () {
  8429. return AbstractMesh._BILLBOARDMODE_X;
  8430. },
  8431. enumerable: true,
  8432. configurable: true
  8433. });
  8434. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8435. get: function () {
  8436. return AbstractMesh._BILLBOARDMODE_Y;
  8437. },
  8438. enumerable: true,
  8439. configurable: true
  8440. });
  8441. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8442. get: function () {
  8443. return AbstractMesh._BILLBOARDMODE_Z;
  8444. },
  8445. enumerable: true,
  8446. configurable: true
  8447. });
  8448. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8449. get: function () {
  8450. return AbstractMesh._BILLBOARDMODE_ALL;
  8451. },
  8452. enumerable: true,
  8453. configurable: true
  8454. });
  8455. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8456. set: function (callback) {
  8457. if (this._onCollideObserver) {
  8458. this.onCollideObservable.remove(this._onCollideObserver);
  8459. }
  8460. this._onCollideObserver = this.onCollideObservable.add(callback);
  8461. },
  8462. enumerable: true,
  8463. configurable: true
  8464. });
  8465. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8466. set: function (callback) {
  8467. if (this._onCollisionPositionChangeObserver) {
  8468. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8469. }
  8470. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8471. },
  8472. enumerable: true,
  8473. configurable: true
  8474. });
  8475. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8476. get: function () {
  8477. return this._skeleton;
  8478. },
  8479. set: function (value) {
  8480. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8481. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8482. }
  8483. if (value && value.needInitialSkinMatrix) {
  8484. value._registerMeshWithPoseMatrix(this);
  8485. }
  8486. this._skeleton = value;
  8487. if (!this._skeleton) {
  8488. this._bonesTransformMatrices = null;
  8489. }
  8490. },
  8491. enumerable: true,
  8492. configurable: true
  8493. });
  8494. /**
  8495. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8496. */
  8497. AbstractMesh.prototype.toString = function (fullDetails) {
  8498. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8499. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8500. if (this._skeleton) {
  8501. ret += ", skeleton: " + this._skeleton.name;
  8502. }
  8503. if (fullDetails) {
  8504. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8505. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8506. }
  8507. return ret;
  8508. };
  8509. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8510. /**
  8511. * Getting the rotation object.
  8512. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8513. */
  8514. get: function () {
  8515. return this._rotation;
  8516. },
  8517. set: function (newRotation) {
  8518. this._rotation = newRotation;
  8519. },
  8520. enumerable: true,
  8521. configurable: true
  8522. });
  8523. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8524. get: function () {
  8525. return this._scaling;
  8526. },
  8527. set: function (newScaling) {
  8528. this._scaling = newScaling;
  8529. if (this.physicsImpostor) {
  8530. this.physicsImpostor.forceUpdate();
  8531. }
  8532. },
  8533. enumerable: true,
  8534. configurable: true
  8535. });
  8536. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8537. get: function () {
  8538. return this._rotationQuaternion;
  8539. },
  8540. set: function (quaternion) {
  8541. this._rotationQuaternion = quaternion;
  8542. //reset the rotation vector.
  8543. if (quaternion && this.rotation.length()) {
  8544. this.rotation.copyFromFloats(0, 0, 0);
  8545. }
  8546. },
  8547. enumerable: true,
  8548. configurable: true
  8549. });
  8550. // Methods
  8551. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8552. this._poseMatrix.copyFrom(matrix);
  8553. };
  8554. AbstractMesh.prototype.getPoseMatrix = function () {
  8555. return this._poseMatrix;
  8556. };
  8557. AbstractMesh.prototype.disableEdgesRendering = function () {
  8558. if (this._edgesRenderer !== undefined) {
  8559. this._edgesRenderer.dispose();
  8560. this._edgesRenderer = undefined;
  8561. }
  8562. };
  8563. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8564. if (epsilon === void 0) { epsilon = 0.95; }
  8565. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8566. this.disableEdgesRendering();
  8567. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8568. };
  8569. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8570. get: function () {
  8571. return false;
  8572. },
  8573. enumerable: true,
  8574. configurable: true
  8575. });
  8576. AbstractMesh.prototype.getLOD = function (camera) {
  8577. return this;
  8578. };
  8579. AbstractMesh.prototype.getTotalVertices = function () {
  8580. return 0;
  8581. };
  8582. AbstractMesh.prototype.getIndices = function () {
  8583. return null;
  8584. };
  8585. AbstractMesh.prototype.getVerticesData = function (kind) {
  8586. return null;
  8587. };
  8588. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8589. return false;
  8590. };
  8591. AbstractMesh.prototype.getBoundingInfo = function () {
  8592. if (this._masterMesh) {
  8593. return this._masterMesh.getBoundingInfo();
  8594. }
  8595. if (!this._boundingInfo) {
  8596. this._updateBoundingInfo();
  8597. }
  8598. return this._boundingInfo;
  8599. };
  8600. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8601. get: function () {
  8602. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8603. },
  8604. enumerable: true,
  8605. configurable: true
  8606. });
  8607. AbstractMesh.prototype._preActivate = function () {
  8608. };
  8609. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  8610. };
  8611. AbstractMesh.prototype._activate = function (renderId) {
  8612. this._renderId = renderId;
  8613. };
  8614. AbstractMesh.prototype.getWorldMatrix = function () {
  8615. if (this._masterMesh) {
  8616. return this._masterMesh.getWorldMatrix();
  8617. }
  8618. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8619. this.computeWorldMatrix();
  8620. }
  8621. return this._worldMatrix;
  8622. };
  8623. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8624. get: function () {
  8625. return this._worldMatrix;
  8626. },
  8627. enumerable: true,
  8628. configurable: true
  8629. });
  8630. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8631. get: function () {
  8632. return this._absolutePosition;
  8633. },
  8634. enumerable: true,
  8635. configurable: true
  8636. });
  8637. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8638. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8639. this.computeWorldMatrix(true);
  8640. this._isWorldMatrixFrozen = true;
  8641. };
  8642. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8643. this._isWorldMatrixFrozen = false;
  8644. this.computeWorldMatrix(true);
  8645. };
  8646. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8647. get: function () {
  8648. return this._isWorldMatrixFrozen;
  8649. },
  8650. enumerable: true,
  8651. configurable: true
  8652. });
  8653. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8654. axis.normalize();
  8655. if (!this.rotationQuaternion) {
  8656. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8657. this.rotation = BABYLON.Vector3.Zero();
  8658. }
  8659. var rotationQuaternion;
  8660. if (!space || space === BABYLON.Space.LOCAL) {
  8661. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8662. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8663. }
  8664. else {
  8665. if (this.parent) {
  8666. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8667. invertParentWorldMatrix.invert();
  8668. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8669. }
  8670. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8671. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8672. }
  8673. };
  8674. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8675. var displacementVector = axis.scale(distance);
  8676. if (!space || space === BABYLON.Space.LOCAL) {
  8677. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8678. this.setPositionWithLocalVector(tempV3);
  8679. }
  8680. else {
  8681. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8682. }
  8683. };
  8684. AbstractMesh.prototype.getAbsolutePosition = function () {
  8685. this.computeWorldMatrix();
  8686. return this._absolutePosition;
  8687. };
  8688. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8689. if (!absolutePosition) {
  8690. return;
  8691. }
  8692. var absolutePositionX;
  8693. var absolutePositionY;
  8694. var absolutePositionZ;
  8695. if (absolutePosition.x === undefined) {
  8696. if (arguments.length < 3) {
  8697. return;
  8698. }
  8699. absolutePositionX = arguments[0];
  8700. absolutePositionY = arguments[1];
  8701. absolutePositionZ = arguments[2];
  8702. }
  8703. else {
  8704. absolutePositionX = absolutePosition.x;
  8705. absolutePositionY = absolutePosition.y;
  8706. absolutePositionZ = absolutePosition.z;
  8707. }
  8708. if (this.parent) {
  8709. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8710. invertParentWorldMatrix.invert();
  8711. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8712. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8713. }
  8714. else {
  8715. this.position.x = absolutePositionX;
  8716. this.position.y = absolutePositionY;
  8717. this.position.z = absolutePositionZ;
  8718. }
  8719. };
  8720. // ================================== Point of View Movement =================================
  8721. /**
  8722. * Perform relative position change from the point of view of behind the front of the mesh.
  8723. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8724. * Supports definition of mesh facing forward or backward.
  8725. * @param {number} amountRight
  8726. * @param {number} amountUp
  8727. * @param {number} amountForward
  8728. */
  8729. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8730. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8731. };
  8732. /**
  8733. * Calculate relative position change from the point of view of behind the front of the mesh.
  8734. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8735. * Supports definition of mesh facing forward or backward.
  8736. * @param {number} amountRight
  8737. * @param {number} amountUp
  8738. * @param {number} amountForward
  8739. */
  8740. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8741. var rotMatrix = new BABYLON.Matrix();
  8742. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8743. rotQuaternion.toRotationMatrix(rotMatrix);
  8744. var translationDelta = BABYLON.Vector3.Zero();
  8745. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8746. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8747. return translationDelta;
  8748. };
  8749. // ================================== Point of View Rotation =================================
  8750. /**
  8751. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8752. * Supports definition of mesh facing forward or backward.
  8753. * @param {number} flipBack
  8754. * @param {number} twirlClockwise
  8755. * @param {number} tiltRight
  8756. */
  8757. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8758. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8759. };
  8760. /**
  8761. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8762. * Supports definition of mesh facing forward or backward.
  8763. * @param {number} flipBack
  8764. * @param {number} twirlClockwise
  8765. * @param {number} tiltRight
  8766. */
  8767. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8768. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8769. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8770. };
  8771. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8772. this._pivotMatrix = matrix;
  8773. this._cache.pivotMatrixUpdated = true;
  8774. };
  8775. AbstractMesh.prototype.getPivotMatrix = function () {
  8776. return this._pivotMatrix;
  8777. };
  8778. AbstractMesh.prototype._isSynchronized = function () {
  8779. if (this._isDirty) {
  8780. return false;
  8781. }
  8782. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8783. return false;
  8784. if (this._cache.pivotMatrixUpdated) {
  8785. return false;
  8786. }
  8787. if (this.infiniteDistance) {
  8788. return false;
  8789. }
  8790. if (!this._cache.position.equals(this.position))
  8791. return false;
  8792. if (this.rotationQuaternion) {
  8793. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8794. return false;
  8795. }
  8796. else {
  8797. if (!this._cache.rotation.equals(this.rotation))
  8798. return false;
  8799. }
  8800. if (!this._cache.scaling.equals(this.scaling))
  8801. return false;
  8802. return true;
  8803. };
  8804. AbstractMesh.prototype._initCache = function () {
  8805. _super.prototype._initCache.call(this);
  8806. this._cache.localMatrixUpdated = false;
  8807. this._cache.position = BABYLON.Vector3.Zero();
  8808. this._cache.scaling = BABYLON.Vector3.Zero();
  8809. this._cache.rotation = BABYLON.Vector3.Zero();
  8810. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8811. this._cache.billboardMode = -1;
  8812. };
  8813. AbstractMesh.prototype.markAsDirty = function (property) {
  8814. if (property === "rotation") {
  8815. this.rotationQuaternion = null;
  8816. }
  8817. this._currentRenderId = Number.MAX_VALUE;
  8818. this._isDirty = true;
  8819. };
  8820. AbstractMesh.prototype._updateBoundingInfo = function () {
  8821. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8822. this._boundingInfo.update(this.worldMatrixFromCache);
  8823. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8824. };
  8825. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8826. if (!this.subMeshes) {
  8827. return;
  8828. }
  8829. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8830. var subMesh = this.subMeshes[subIndex];
  8831. if (!subMesh.IsGlobal) {
  8832. subMesh.updateBoundingInfo(matrix);
  8833. }
  8834. }
  8835. };
  8836. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8837. if (this._isWorldMatrixFrozen) {
  8838. return this._worldMatrix;
  8839. }
  8840. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8841. this._currentRenderId = this.getScene().getRenderId();
  8842. return this._worldMatrix;
  8843. }
  8844. this._cache.position.copyFrom(this.position);
  8845. this._cache.scaling.copyFrom(this.scaling);
  8846. this._cache.pivotMatrixUpdated = false;
  8847. this._cache.billboardMode = this.billboardMode;
  8848. this._currentRenderId = this.getScene().getRenderId();
  8849. this._isDirty = false;
  8850. // Scaling
  8851. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8852. // Rotation
  8853. //rotate, if quaternion is set and rotation was used
  8854. if (this.rotationQuaternion) {
  8855. var len = this.rotation.length();
  8856. if (len) {
  8857. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8858. this.rotation.copyFromFloats(0, 0, 0);
  8859. }
  8860. }
  8861. if (this.rotationQuaternion) {
  8862. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8863. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8864. }
  8865. else {
  8866. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8867. this._cache.rotation.copyFrom(this.rotation);
  8868. }
  8869. // Translation
  8870. if (this.infiniteDistance && !this.parent) {
  8871. var camera = this.getScene().activeCamera;
  8872. if (camera) {
  8873. var cameraWorldMatrix = camera.getWorldMatrix();
  8874. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8875. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8876. }
  8877. }
  8878. else {
  8879. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8880. }
  8881. // Composing transformations
  8882. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8883. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8884. // Billboarding
  8885. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8886. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  8887. var localPosition = BABYLON.Tmp.Vector3[0];
  8888. if (this.parent && this.parent.getWorldMatrix) {
  8889. this._markSyncedWithParent();
  8890. var parentMatrix;
  8891. if (this._meshToBoneReferal) {
  8892. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8893. parentMatrix = BABYLON.Tmp.Matrix[6];
  8894. }
  8895. else {
  8896. parentMatrix = this.parent.getWorldMatrix();
  8897. }
  8898. BABYLON.Vector3.TransformCoordinatesToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  8899. localPosition = BABYLON.Tmp.Vector3[1];
  8900. }
  8901. var zero = this.getScene().activeCamera.globalPosition.clone();
  8902. if (this.parent && this.parent.position) {
  8903. localPosition.addInPlace(this.parent.position);
  8904. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8905. }
  8906. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8907. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8908. zero.x = localPosition.x + BABYLON.Epsilon;
  8909. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8910. zero.y = localPosition.y + BABYLON.Epsilon;
  8911. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8912. zero.z = localPosition.z + BABYLON.Epsilon;
  8913. }
  8914. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8915. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8916. BABYLON.Tmp.Matrix[3].invert();
  8917. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8918. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8919. }
  8920. // Local world
  8921. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8922. // Parent
  8923. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8924. this._markSyncedWithParent();
  8925. if (this._meshToBoneReferal) {
  8926. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8927. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8928. }
  8929. else {
  8930. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8931. }
  8932. }
  8933. else {
  8934. this._worldMatrix.copyFrom(this._localWorld);
  8935. }
  8936. // Bounding info
  8937. this._updateBoundingInfo();
  8938. // Absolute position
  8939. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8940. // Callbacks
  8941. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  8942. if (!this._poseMatrix) {
  8943. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8944. }
  8945. return this._worldMatrix;
  8946. };
  8947. /**
  8948. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8949. * @param func: callback function to add
  8950. */
  8951. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8952. this.onAfterWorldMatrixUpdateObservable.add(func);
  8953. };
  8954. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8955. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  8956. };
  8957. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8958. this.computeWorldMatrix();
  8959. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8960. };
  8961. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8962. this.computeWorldMatrix();
  8963. var invLocalWorldMatrix = this._localWorld.clone();
  8964. invLocalWorldMatrix.invert();
  8965. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8966. };
  8967. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8968. this.computeWorldMatrix(true);
  8969. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8970. };
  8971. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8972. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8973. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8974. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8975. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8976. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8977. /// <returns>Mesh oriented towards targetMesh</returns>
  8978. yawCor = yawCor || 0; // default to zero if undefined
  8979. pitchCor = pitchCor || 0;
  8980. rollCor = rollCor || 0;
  8981. var dv = targetPoint.subtract(this.position);
  8982. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8983. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8984. var pitch = Math.atan2(dv.y, len);
  8985. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8986. };
  8987. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8988. this._meshToBoneReferal = affectedMesh;
  8989. this.parent = bone;
  8990. if (bone.getWorldMatrix().determinant() < 0) {
  8991. this.scalingDeterminant *= -1;
  8992. }
  8993. };
  8994. AbstractMesh.prototype.detachFromBone = function () {
  8995. if (this.parent.getWorldMatrix().determinant() < 0) {
  8996. this.scalingDeterminant *= -1;
  8997. }
  8998. this._meshToBoneReferal = null;
  8999. this.parent = null;
  9000. };
  9001. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9002. return this._boundingInfo.isInFrustum(frustumPlanes);
  9003. };
  9004. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9005. if (!camera) {
  9006. camera = this.getScene().activeCamera;
  9007. }
  9008. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9009. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9010. return false;
  9011. }
  9012. return true;
  9013. };
  9014. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9015. if (!this._boundingInfo || !mesh._boundingInfo) {
  9016. return false;
  9017. }
  9018. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9019. };
  9020. AbstractMesh.prototype.intersectsPoint = function (point) {
  9021. if (!this._boundingInfo) {
  9022. return false;
  9023. }
  9024. return this._boundingInfo.intersectsPoint(point);
  9025. };
  9026. // Physics
  9027. /**
  9028. * @Deprecated. Use new PhysicsImpostor instead.
  9029. * */
  9030. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9031. //legacy support
  9032. if (impostor.impostor) {
  9033. options = impostor;
  9034. impostor = impostor.impostor;
  9035. }
  9036. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9037. return this.physicsImpostor.physicsBody;
  9038. };
  9039. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9040. return this.physicsImpostor;
  9041. };
  9042. /**
  9043. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9044. */
  9045. AbstractMesh.prototype.getPhysicsMass = function () {
  9046. return this.physicsImpostor.getParam("mass");
  9047. };
  9048. /**
  9049. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9050. */
  9051. AbstractMesh.prototype.getPhysicsFriction = function () {
  9052. return this.physicsImpostor.getParam("friction");
  9053. };
  9054. /**
  9055. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9056. */
  9057. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9058. return this.physicsImpostor.getParam("resitution");
  9059. };
  9060. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9061. if (!camera) {
  9062. camera = this.getScene().activeCamera;
  9063. }
  9064. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9065. };
  9066. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9067. if (!camera) {
  9068. camera = this.getScene().activeCamera;
  9069. }
  9070. return this.absolutePosition.subtract(camera.position).length();
  9071. };
  9072. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9073. if (!this.physicsImpostor) {
  9074. return;
  9075. }
  9076. this.physicsImpostor.applyImpulse(force, contactPoint);
  9077. };
  9078. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9079. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9080. return;
  9081. }
  9082. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9083. mainPivot: pivot1,
  9084. connectedPivot: pivot2,
  9085. nativeParams: options
  9086. });
  9087. };
  9088. /**
  9089. * @Deprecated
  9090. */
  9091. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9092. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9093. this.updatePhysicsBody();
  9094. };
  9095. /**
  9096. * @Deprecated
  9097. * Calling this function is not needed anymore.
  9098. * The physics engine takes care of transofmration automatically.
  9099. */
  9100. AbstractMesh.prototype.updatePhysicsBody = function () {
  9101. //Unneeded
  9102. };
  9103. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9104. // Collisions
  9105. get: function () {
  9106. return this._checkCollisions;
  9107. },
  9108. set: function (collisionEnabled) {
  9109. this._checkCollisions = collisionEnabled;
  9110. if (this.getScene().workerCollisions) {
  9111. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9112. }
  9113. },
  9114. enumerable: true,
  9115. configurable: true
  9116. });
  9117. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9118. var globalPosition = this.getAbsolutePosition();
  9119. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9120. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9121. this._collider.radius = this.ellipsoid;
  9122. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9123. };
  9124. // Submeshes octree
  9125. /**
  9126. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9127. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9128. */
  9129. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9130. if (maxCapacity === void 0) { maxCapacity = 64; }
  9131. if (maxDepth === void 0) { maxDepth = 2; }
  9132. if (!this._submeshesOctree) {
  9133. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9134. }
  9135. this.computeWorldMatrix(true);
  9136. // Update octree
  9137. var bbox = this.getBoundingInfo().boundingBox;
  9138. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9139. return this._submeshesOctree;
  9140. };
  9141. // Collisions
  9142. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9143. this._generatePointsArray();
  9144. // Transformation
  9145. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9146. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9147. subMesh._lastColliderWorldVertices = [];
  9148. subMesh._trianglePlanes = [];
  9149. var start = subMesh.verticesStart;
  9150. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9151. for (var i = start; i < end; i++) {
  9152. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9153. }
  9154. }
  9155. // Collide
  9156. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9157. if (collider.collisionFound) {
  9158. collider.collidedMesh = this;
  9159. }
  9160. };
  9161. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9162. var subMeshes;
  9163. var len;
  9164. // Octrees
  9165. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9166. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9167. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9168. len = intersections.length;
  9169. subMeshes = intersections.data;
  9170. }
  9171. else {
  9172. subMeshes = this.subMeshes;
  9173. len = subMeshes.length;
  9174. }
  9175. for (var index = 0; index < len; index++) {
  9176. var subMesh = subMeshes[index];
  9177. // Bounding test
  9178. if (len > 1 && !subMesh._checkCollision(collider))
  9179. continue;
  9180. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9181. }
  9182. };
  9183. AbstractMesh.prototype._checkCollision = function (collider) {
  9184. // Bounding box test
  9185. if (!this._boundingInfo._checkCollision(collider))
  9186. return;
  9187. // Transformation matrix
  9188. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9189. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9190. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9191. };
  9192. // Picking
  9193. AbstractMesh.prototype._generatePointsArray = function () {
  9194. return false;
  9195. };
  9196. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9197. var pickingInfo = new BABYLON.PickingInfo();
  9198. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9199. return pickingInfo;
  9200. }
  9201. if (!this._generatePointsArray()) {
  9202. return pickingInfo;
  9203. }
  9204. var intersectInfo = null;
  9205. // Octrees
  9206. var subMeshes;
  9207. var len;
  9208. if (this._submeshesOctree && this.useOctreeForPicking) {
  9209. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9210. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9211. len = intersections.length;
  9212. subMeshes = intersections.data;
  9213. }
  9214. else {
  9215. subMeshes = this.subMeshes;
  9216. len = subMeshes.length;
  9217. }
  9218. for (var index = 0; index < len; index++) {
  9219. var subMesh = subMeshes[index];
  9220. // Bounding test
  9221. if (len > 1 && !subMesh.canIntersects(ray))
  9222. continue;
  9223. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9224. if (currentIntersectInfo) {
  9225. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9226. intersectInfo = currentIntersectInfo;
  9227. intersectInfo.subMeshId = index;
  9228. if (fastCheck) {
  9229. break;
  9230. }
  9231. }
  9232. }
  9233. }
  9234. if (intersectInfo) {
  9235. // Get picked point
  9236. var world = this.getWorldMatrix();
  9237. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9238. var direction = ray.direction.clone();
  9239. direction = direction.scale(intersectInfo.distance);
  9240. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9241. var pickedPoint = worldOrigin.add(worldDirection);
  9242. // Return result
  9243. pickingInfo.hit = true;
  9244. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9245. pickingInfo.pickedPoint = pickedPoint;
  9246. pickingInfo.pickedMesh = this;
  9247. pickingInfo.bu = intersectInfo.bu;
  9248. pickingInfo.bv = intersectInfo.bv;
  9249. pickingInfo.faceId = intersectInfo.faceId;
  9250. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9251. return pickingInfo;
  9252. }
  9253. return pickingInfo;
  9254. };
  9255. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9256. return null;
  9257. };
  9258. AbstractMesh.prototype.releaseSubMeshes = function () {
  9259. if (this.subMeshes) {
  9260. while (this.subMeshes.length) {
  9261. this.subMeshes[0].dispose();
  9262. }
  9263. }
  9264. else {
  9265. this.subMeshes = new Array();
  9266. }
  9267. };
  9268. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9269. var _this = this;
  9270. var index;
  9271. // Action manager
  9272. if (this.actionManager) {
  9273. this.actionManager.dispose();
  9274. this.actionManager = null;
  9275. }
  9276. // Skeleton
  9277. this.skeleton = null;
  9278. // Animations
  9279. this.getScene().stopAnimation(this);
  9280. // Physics
  9281. if (this.physicsImpostor) {
  9282. this.physicsImpostor.dispose();
  9283. }
  9284. // Intersections in progress
  9285. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9286. var other = this._intersectionsInProgress[index];
  9287. var pos = other._intersectionsInProgress.indexOf(this);
  9288. other._intersectionsInProgress.splice(pos, 1);
  9289. }
  9290. this._intersectionsInProgress = [];
  9291. // Lights
  9292. var lights = this.getScene().lights;
  9293. lights.forEach(function (light) {
  9294. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9295. if (meshIndex !== -1) {
  9296. light.includedOnlyMeshes.splice(meshIndex, 1);
  9297. }
  9298. meshIndex = light.excludedMeshes.indexOf(_this);
  9299. if (meshIndex !== -1) {
  9300. light.excludedMeshes.splice(meshIndex, 1);
  9301. }
  9302. });
  9303. // Edges
  9304. if (this._edgesRenderer) {
  9305. this._edgesRenderer.dispose();
  9306. this._edgesRenderer = null;
  9307. }
  9308. // SubMeshes
  9309. this.releaseSubMeshes();
  9310. // Remove from scene
  9311. this.getScene().removeMesh(this);
  9312. if (!doNotRecurse) {
  9313. // Particles
  9314. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9315. if (this.getScene().particleSystems[index].emitter === this) {
  9316. this.getScene().particleSystems[index].dispose();
  9317. index--;
  9318. }
  9319. }
  9320. // Children
  9321. var objects = this.getDescendants(true);
  9322. for (index = 0; index < objects.length; index++) {
  9323. objects[index].dispose();
  9324. }
  9325. }
  9326. else {
  9327. var childMeshes = this.getChildMeshes(true);
  9328. for (index = 0; index < childMeshes.length; index++) {
  9329. var child = childMeshes[index];
  9330. child.parent = null;
  9331. child.computeWorldMatrix(true);
  9332. }
  9333. }
  9334. _super.prototype.dispose.call(this);
  9335. this.onAfterWorldMatrixUpdateObservable.clear();
  9336. this._isDisposed = true;
  9337. // Callback
  9338. if (this.onDispose) {
  9339. this.onDispose();
  9340. }
  9341. };
  9342. // Statics
  9343. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9344. AbstractMesh._BILLBOARDMODE_X = 1;
  9345. AbstractMesh._BILLBOARDMODE_Y = 2;
  9346. AbstractMesh._BILLBOARDMODE_Z = 4;
  9347. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9348. return AbstractMesh;
  9349. })(BABYLON.Node);
  9350. BABYLON.AbstractMesh = AbstractMesh;
  9351. })(BABYLON || (BABYLON = {}));
  9352. var BABYLON;
  9353. (function (BABYLON) {
  9354. var Light = (function (_super) {
  9355. __extends(Light, _super);
  9356. function Light(name, scene) {
  9357. _super.call(this, name, scene);
  9358. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9359. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9360. this.intensity = 1.0;
  9361. this.range = Number.MAX_VALUE;
  9362. this.includeOnlyWithLayerMask = 0;
  9363. this.includedOnlyMeshes = new Array();
  9364. this.excludedMeshes = new Array();
  9365. this.excludeWithLayerMask = 0;
  9366. // PBR Properties.
  9367. this.radius = 0.00001;
  9368. this._excludedMeshesIds = new Array();
  9369. this._includedOnlyMeshesIds = new Array();
  9370. scene.addLight(this);
  9371. }
  9372. /**
  9373. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9374. */
  9375. Light.prototype.toString = function (fullDetails) {
  9376. var ret = "Name: " + this.name;
  9377. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9378. if (this.animations) {
  9379. for (var i = 0; i < this.animations.length; i++) {
  9380. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9381. }
  9382. }
  9383. if (fullDetails) {
  9384. }
  9385. return ret;
  9386. };
  9387. Light.prototype.getShadowGenerator = function () {
  9388. return this._shadowGenerator;
  9389. };
  9390. Light.prototype.getAbsolutePosition = function () {
  9391. return BABYLON.Vector3.Zero();
  9392. };
  9393. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9394. };
  9395. Light.prototype._getWorldMatrix = function () {
  9396. return BABYLON.Matrix.Identity();
  9397. };
  9398. Light.prototype.canAffectMesh = function (mesh) {
  9399. if (!mesh) {
  9400. return true;
  9401. }
  9402. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9403. return false;
  9404. }
  9405. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9406. return false;
  9407. }
  9408. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9409. return false;
  9410. }
  9411. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9412. return false;
  9413. }
  9414. return true;
  9415. };
  9416. Light.prototype.getWorldMatrix = function () {
  9417. this._currentRenderId = this.getScene().getRenderId();
  9418. var worldMatrix = this._getWorldMatrix();
  9419. if (this.parent && this.parent.getWorldMatrix) {
  9420. if (!this._parentedWorldMatrix) {
  9421. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9422. }
  9423. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9424. this._markSyncedWithParent();
  9425. return this._parentedWorldMatrix;
  9426. }
  9427. return worldMatrix;
  9428. };
  9429. Light.prototype.dispose = function () {
  9430. if (this._shadowGenerator) {
  9431. this._shadowGenerator.dispose();
  9432. this._shadowGenerator = null;
  9433. }
  9434. // Animations
  9435. this.getScene().stopAnimation(this);
  9436. // Remove from scene
  9437. this.getScene().removeLight(this);
  9438. _super.prototype.dispose.call(this);
  9439. };
  9440. Light.prototype.getTypeID = function () {
  9441. return 0;
  9442. };
  9443. Light.prototype.clone = function (name) {
  9444. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9445. };
  9446. Light.prototype.serialize = function () {
  9447. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9448. // Type
  9449. serializationObject.type = this.getTypeID();
  9450. // Parent
  9451. if (this.parent) {
  9452. serializationObject.parentId = this.parent.id;
  9453. }
  9454. // Inclusion / exclusions
  9455. if (this.excludedMeshes.length > 0) {
  9456. serializationObject.excludedMeshesIds = [];
  9457. this.excludedMeshes.forEach(function (mesh) {
  9458. serializationObject.excludedMeshesIds.push(mesh.id);
  9459. });
  9460. }
  9461. if (this.includedOnlyMeshes.length > 0) {
  9462. serializationObject.includedOnlyMeshesIds = [];
  9463. this.includedOnlyMeshes.forEach(function (mesh) {
  9464. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9465. });
  9466. }
  9467. // Animations
  9468. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9469. serializationObject.ranges = this.serializeAnimationRanges();
  9470. return serializationObject;
  9471. };
  9472. Light.GetConstructorFromName = function (type, name, scene) {
  9473. switch (type) {
  9474. case 0:
  9475. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9476. case 1:
  9477. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9478. case 2:
  9479. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9480. case 3:
  9481. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9482. }
  9483. };
  9484. Light.Parse = function (parsedLight, scene) {
  9485. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9486. // Inclusion / exclusions
  9487. if (parsedLight.excludedMeshesIds) {
  9488. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9489. }
  9490. if (parsedLight.includedOnlyMeshesIds) {
  9491. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9492. }
  9493. // Parent
  9494. if (parsedLight.parentId) {
  9495. light._waitingParentId = parsedLight.parentId;
  9496. }
  9497. // Animations
  9498. if (parsedLight.animations) {
  9499. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9500. var parsedAnimation = parsedLight.animations[animationIndex];
  9501. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9502. }
  9503. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9504. }
  9505. if (parsedLight.autoAnimate) {
  9506. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9507. }
  9508. return light;
  9509. };
  9510. __decorate([
  9511. BABYLON.serializeAsColor3()
  9512. ], Light.prototype, "diffuse", void 0);
  9513. __decorate([
  9514. BABYLON.serializeAsColor3()
  9515. ], Light.prototype, "specular", void 0);
  9516. __decorate([
  9517. BABYLON.serialize()
  9518. ], Light.prototype, "intensity", void 0);
  9519. __decorate([
  9520. BABYLON.serialize()
  9521. ], Light.prototype, "range", void 0);
  9522. __decorate([
  9523. BABYLON.serialize()
  9524. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9525. __decorate([
  9526. BABYLON.serialize()
  9527. ], Light.prototype, "excludeWithLayerMask", void 0);
  9528. __decorate([
  9529. BABYLON.serialize()
  9530. ], Light.prototype, "radius", void 0);
  9531. return Light;
  9532. })(BABYLON.Node);
  9533. BABYLON.Light = Light;
  9534. })(BABYLON || (BABYLON = {}));
  9535. var BABYLON;
  9536. (function (BABYLON) {
  9537. var PointLight = (function (_super) {
  9538. __extends(PointLight, _super);
  9539. function PointLight(name, position, scene) {
  9540. _super.call(this, name, scene);
  9541. this.position = position;
  9542. }
  9543. PointLight.prototype.getAbsolutePosition = function () {
  9544. return this.transformedPosition ? this.transformedPosition : this.position;
  9545. };
  9546. PointLight.prototype.computeTransformedPosition = function () {
  9547. if (this.parent && this.parent.getWorldMatrix) {
  9548. if (!this.transformedPosition) {
  9549. this.transformedPosition = BABYLON.Vector3.Zero();
  9550. }
  9551. BABYLON.Vector3.TransformCoordinatesToRef(this.getAbsolutePosition(), this.parent.getWorldMatrix(), this.transformedPosition);
  9552. return true;
  9553. }
  9554. return false;
  9555. };
  9556. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9557. if (this.parent && this.parent.getWorldMatrix) {
  9558. this.computeTransformedPosition();
  9559. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9560. return;
  9561. }
  9562. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9563. };
  9564. PointLight.prototype.needCube = function () {
  9565. return true;
  9566. };
  9567. PointLight.prototype.supportsVSM = function () {
  9568. return false;
  9569. };
  9570. PointLight.prototype.needRefreshPerFrame = function () {
  9571. return false;
  9572. };
  9573. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9574. switch (faceIndex) {
  9575. case 0:
  9576. return new BABYLON.Vector3(1, 0, 0);
  9577. case 1:
  9578. return new BABYLON.Vector3(-1, 0, 0);
  9579. case 2:
  9580. return new BABYLON.Vector3(0, -1, 0);
  9581. case 3:
  9582. return new BABYLON.Vector3(0, 1, 0);
  9583. case 4:
  9584. return new BABYLON.Vector3(0, 0, 1);
  9585. case 5:
  9586. return new BABYLON.Vector3(0, 0, -1);
  9587. }
  9588. return BABYLON.Vector3.Zero();
  9589. };
  9590. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9591. var activeCamera = this.getScene().activeCamera;
  9592. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9593. };
  9594. PointLight.prototype._getWorldMatrix = function () {
  9595. if (!this._worldMatrix) {
  9596. this._worldMatrix = BABYLON.Matrix.Identity();
  9597. }
  9598. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9599. return this._worldMatrix;
  9600. };
  9601. PointLight.prototype.getTypeID = function () {
  9602. return 0;
  9603. };
  9604. __decorate([
  9605. BABYLON.serializeAsVector3()
  9606. ], PointLight.prototype, "position", void 0);
  9607. return PointLight;
  9608. })(BABYLON.Light);
  9609. BABYLON.PointLight = PointLight;
  9610. })(BABYLON || (BABYLON = {}));
  9611. var BABYLON;
  9612. (function (BABYLON) {
  9613. var SpotLight = (function (_super) {
  9614. __extends(SpotLight, _super);
  9615. function SpotLight(name, position, direction, angle, exponent, scene) {
  9616. _super.call(this, name, scene);
  9617. this.position = position;
  9618. this.direction = direction;
  9619. this.angle = angle;
  9620. this.exponent = exponent;
  9621. }
  9622. SpotLight.prototype.getAbsolutePosition = function () {
  9623. return this.transformedPosition ? this.transformedPosition : this.position;
  9624. };
  9625. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9626. var activeCamera = this.getScene().activeCamera;
  9627. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9628. };
  9629. SpotLight.prototype.needCube = function () {
  9630. return false;
  9631. };
  9632. SpotLight.prototype.supportsVSM = function () {
  9633. return true;
  9634. };
  9635. SpotLight.prototype.needRefreshPerFrame = function () {
  9636. return false;
  9637. };
  9638. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9639. return this.direction;
  9640. };
  9641. SpotLight.prototype.setDirectionToTarget = function (target) {
  9642. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9643. return this.direction;
  9644. };
  9645. SpotLight.prototype.computeTransformedPosition = function () {
  9646. if (this.parent && this.parent.getWorldMatrix) {
  9647. if (!this.transformedPosition) {
  9648. this.transformedPosition = BABYLON.Vector3.Zero();
  9649. }
  9650. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9651. return true;
  9652. }
  9653. return false;
  9654. };
  9655. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9656. var normalizeDirection;
  9657. if (this.parent && this.parent.getWorldMatrix) {
  9658. if (!this._transformedDirection) {
  9659. this._transformedDirection = BABYLON.Vector3.Zero();
  9660. }
  9661. this.computeTransformedPosition();
  9662. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9663. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9664. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9665. }
  9666. else {
  9667. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9668. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9669. }
  9670. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9671. };
  9672. SpotLight.prototype._getWorldMatrix = function () {
  9673. if (!this._worldMatrix) {
  9674. this._worldMatrix = BABYLON.Matrix.Identity();
  9675. }
  9676. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9677. return this._worldMatrix;
  9678. };
  9679. SpotLight.prototype.getTypeID = function () {
  9680. return 2;
  9681. };
  9682. __decorate([
  9683. BABYLON.serializeAsVector3()
  9684. ], SpotLight.prototype, "position", void 0);
  9685. __decorate([
  9686. BABYLON.serializeAsVector3()
  9687. ], SpotLight.prototype, "direction", void 0);
  9688. __decorate([
  9689. BABYLON.serialize()
  9690. ], SpotLight.prototype, "angle", void 0);
  9691. __decorate([
  9692. BABYLON.serialize()
  9693. ], SpotLight.prototype, "exponent", void 0);
  9694. return SpotLight;
  9695. })(BABYLON.Light);
  9696. BABYLON.SpotLight = SpotLight;
  9697. })(BABYLON || (BABYLON = {}));
  9698. var BABYLON;
  9699. (function (BABYLON) {
  9700. var HemisphericLight = (function (_super) {
  9701. __extends(HemisphericLight, _super);
  9702. function HemisphericLight(name, direction, scene) {
  9703. _super.call(this, name, scene);
  9704. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9705. this.direction = direction;
  9706. }
  9707. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9708. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9709. return this.direction;
  9710. };
  9711. HemisphericLight.prototype.getShadowGenerator = function () {
  9712. return null;
  9713. };
  9714. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9715. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9716. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9717. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9718. };
  9719. HemisphericLight.prototype._getWorldMatrix = function () {
  9720. if (!this._worldMatrix) {
  9721. this._worldMatrix = BABYLON.Matrix.Identity();
  9722. }
  9723. return this._worldMatrix;
  9724. };
  9725. HemisphericLight.prototype.getTypeID = function () {
  9726. return 3;
  9727. };
  9728. __decorate([
  9729. BABYLON.serializeAsColor3()
  9730. ], HemisphericLight.prototype, "groundColor", void 0);
  9731. __decorate([
  9732. BABYLON.serializeAsVector3()
  9733. ], HemisphericLight.prototype, "direction", void 0);
  9734. return HemisphericLight;
  9735. })(BABYLON.Light);
  9736. BABYLON.HemisphericLight = HemisphericLight;
  9737. })(BABYLON || (BABYLON = {}));
  9738. var BABYLON;
  9739. (function (BABYLON) {
  9740. var DirectionalLight = (function (_super) {
  9741. __extends(DirectionalLight, _super);
  9742. function DirectionalLight(name, direction, scene) {
  9743. _super.call(this, name, scene);
  9744. this.shadowOrthoScale = 0.5;
  9745. this.autoUpdateExtends = true;
  9746. // Cache
  9747. this._orthoLeft = Number.MAX_VALUE;
  9748. this._orthoRight = Number.MIN_VALUE;
  9749. this._orthoTop = Number.MIN_VALUE;
  9750. this._orthoBottom = Number.MAX_VALUE;
  9751. this.position = direction.scale(-1);
  9752. this.direction = direction;
  9753. }
  9754. DirectionalLight.prototype.getAbsolutePosition = function () {
  9755. return this.transformedPosition ? this.transformedPosition : this.position;
  9756. };
  9757. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9758. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9759. return this.direction;
  9760. };
  9761. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9762. var activeCamera = this.getScene().activeCamera;
  9763. // Check extends
  9764. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9765. var tempVector3 = BABYLON.Vector3.Zero();
  9766. this._orthoLeft = Number.MAX_VALUE;
  9767. this._orthoRight = Number.MIN_VALUE;
  9768. this._orthoTop = Number.MIN_VALUE;
  9769. this._orthoBottom = Number.MAX_VALUE;
  9770. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9771. var mesh = renderList[meshIndex];
  9772. if (!mesh) {
  9773. continue;
  9774. }
  9775. var boundingInfo = mesh.getBoundingInfo();
  9776. if (!boundingInfo) {
  9777. continue;
  9778. }
  9779. var boundingBox = boundingInfo.boundingBox;
  9780. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9781. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9782. if (tempVector3.x < this._orthoLeft)
  9783. this._orthoLeft = tempVector3.x;
  9784. if (tempVector3.y < this._orthoBottom)
  9785. this._orthoBottom = tempVector3.y;
  9786. if (tempVector3.x > this._orthoRight)
  9787. this._orthoRight = tempVector3.x;
  9788. if (tempVector3.y > this._orthoTop)
  9789. this._orthoTop = tempVector3.y;
  9790. }
  9791. }
  9792. }
  9793. var xOffset = this._orthoRight - this._orthoLeft;
  9794. var yOffset = this._orthoTop - this._orthoBottom;
  9795. 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);
  9796. };
  9797. DirectionalLight.prototype.supportsVSM = function () {
  9798. return true;
  9799. };
  9800. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9801. return true;
  9802. };
  9803. DirectionalLight.prototype.needCube = function () {
  9804. return false;
  9805. };
  9806. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9807. return this.direction;
  9808. };
  9809. DirectionalLight.prototype.computeTransformedPosition = function () {
  9810. if (this.parent && this.parent.getWorldMatrix) {
  9811. if (!this.transformedPosition) {
  9812. this.transformedPosition = BABYLON.Vector3.Zero();
  9813. }
  9814. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9815. return true;
  9816. }
  9817. return false;
  9818. };
  9819. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9820. if (this.parent && this.parent.getWorldMatrix) {
  9821. if (!this._transformedDirection) {
  9822. this._transformedDirection = BABYLON.Vector3.Zero();
  9823. }
  9824. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9825. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9826. return;
  9827. }
  9828. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9829. };
  9830. DirectionalLight.prototype._getWorldMatrix = function () {
  9831. if (!this._worldMatrix) {
  9832. this._worldMatrix = BABYLON.Matrix.Identity();
  9833. }
  9834. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9835. return this._worldMatrix;
  9836. };
  9837. DirectionalLight.prototype.getTypeID = function () {
  9838. return 1;
  9839. };
  9840. __decorate([
  9841. BABYLON.serializeAsVector3()
  9842. ], DirectionalLight.prototype, "position", void 0);
  9843. __decorate([
  9844. BABYLON.serializeAsVector3()
  9845. ], DirectionalLight.prototype, "direction", void 0);
  9846. __decorate([
  9847. BABYLON.serialize()
  9848. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9849. __decorate([
  9850. BABYLON.serialize()
  9851. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9852. return DirectionalLight;
  9853. })(BABYLON.Light);
  9854. BABYLON.DirectionalLight = DirectionalLight;
  9855. })(BABYLON || (BABYLON = {}));
  9856. var BABYLON;
  9857. (function (BABYLON) {
  9858. var ShadowGenerator = (function () {
  9859. function ShadowGenerator(mapSize, light) {
  9860. var _this = this;
  9861. // Members
  9862. this._filter = ShadowGenerator.FILTER_NONE;
  9863. this.blurScale = 2;
  9864. this._blurBoxOffset = 0;
  9865. this._bias = 0.00005;
  9866. this._lightDirection = BABYLON.Vector3.Zero();
  9867. this.forceBackFacesOnly = false;
  9868. this._darkness = 0;
  9869. this._transparencyShadow = false;
  9870. this._viewMatrix = BABYLON.Matrix.Zero();
  9871. this._projectionMatrix = BABYLON.Matrix.Zero();
  9872. this._transformMatrix = BABYLON.Matrix.Zero();
  9873. this._worldViewProjection = BABYLON.Matrix.Zero();
  9874. this._currentFaceIndex = 0;
  9875. this._currentFaceIndexCache = 0;
  9876. this._light = light;
  9877. this._scene = light.getScene();
  9878. this._mapSize = mapSize;
  9879. light._shadowGenerator = this;
  9880. // Render target
  9881. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9882. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9883. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9884. this._shadowMap.anisotropicFilteringLevel = 1;
  9885. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9886. this._shadowMap.renderParticles = false;
  9887. this._shadowMap.onBeforeRender = function (faceIndex) {
  9888. _this._currentFaceIndex = faceIndex;
  9889. };
  9890. this._shadowMap.onAfterUnbind = function () {
  9891. if (!_this.useBlurVarianceShadowMap) {
  9892. return;
  9893. }
  9894. if (!_this._shadowMap2) {
  9895. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9896. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9897. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9898. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9899. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9900. _this._downSamplePostprocess.onApply = function (effect) {
  9901. effect.setTexture("textureSampler", _this._shadowMap);
  9902. };
  9903. _this.blurBoxOffset = 1;
  9904. }
  9905. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9906. };
  9907. // Custom render function
  9908. var renderSubMesh = function (subMesh) {
  9909. var mesh = subMesh.getRenderingMesh();
  9910. var scene = _this._scene;
  9911. var engine = scene.getEngine();
  9912. // Culling
  9913. engine.setState(subMesh.getMaterial().backFaceCulling);
  9914. // Managing instances
  9915. var batch = mesh._getInstancesRenderList(subMesh._id);
  9916. if (batch.mustReturn) {
  9917. return;
  9918. }
  9919. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9920. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9921. engine.enableEffect(_this._effect);
  9922. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9923. var material = subMesh.getMaterial();
  9924. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9925. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9926. if (_this.getLight().needCube()) {
  9927. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9928. }
  9929. // Alpha test
  9930. if (material && material.needAlphaTesting()) {
  9931. var alphaTexture = material.getAlphaTestTexture();
  9932. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9933. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9934. }
  9935. // Bones
  9936. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9937. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9938. }
  9939. if (_this.forceBackFacesOnly) {
  9940. engine.setState(true, 0, false, true);
  9941. }
  9942. // Draw
  9943. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9944. if (_this.forceBackFacesOnly) {
  9945. engine.setState(true, 0, false, false);
  9946. }
  9947. }
  9948. else {
  9949. // Need to reset refresh rate of the shadowMap
  9950. _this._shadowMap.resetRefreshCounter();
  9951. }
  9952. };
  9953. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9954. var index;
  9955. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9956. renderSubMesh(opaqueSubMeshes.data[index]);
  9957. }
  9958. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9959. renderSubMesh(alphaTestSubMeshes.data[index]);
  9960. }
  9961. if (_this._transparencyShadow) {
  9962. for (index = 0; index < transparentSubMeshes.length; index++) {
  9963. renderSubMesh(transparentSubMeshes.data[index]);
  9964. }
  9965. }
  9966. };
  9967. this._shadowMap.onClear = function (engine) {
  9968. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9969. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9970. }
  9971. else {
  9972. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9973. }
  9974. };
  9975. }
  9976. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9977. // Static
  9978. get: function () {
  9979. return ShadowGenerator._FILTER_NONE;
  9980. },
  9981. enumerable: true,
  9982. configurable: true
  9983. });
  9984. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9985. get: function () {
  9986. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9987. },
  9988. enumerable: true,
  9989. configurable: true
  9990. });
  9991. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9992. get: function () {
  9993. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9994. },
  9995. enumerable: true,
  9996. configurable: true
  9997. });
  9998. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9999. get: function () {
  10000. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10001. },
  10002. enumerable: true,
  10003. configurable: true
  10004. });
  10005. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10006. get: function () {
  10007. return this._bias;
  10008. },
  10009. set: function (bias) {
  10010. this._bias = bias;
  10011. },
  10012. enumerable: true,
  10013. configurable: true
  10014. });
  10015. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10016. get: function () {
  10017. return this._blurBoxOffset;
  10018. },
  10019. set: function (value) {
  10020. var _this = this;
  10021. if (this._blurBoxOffset === value) {
  10022. return;
  10023. }
  10024. this._blurBoxOffset = value;
  10025. if (this._boxBlurPostprocess) {
  10026. this._boxBlurPostprocess.dispose();
  10027. }
  10028. 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);
  10029. this._boxBlurPostprocess.onApply = function (effect) {
  10030. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10031. };
  10032. },
  10033. enumerable: true,
  10034. configurable: true
  10035. });
  10036. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10037. get: function () {
  10038. return this._filter;
  10039. },
  10040. set: function (value) {
  10041. if (this._filter === value) {
  10042. return;
  10043. }
  10044. this._filter = value;
  10045. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10046. this._shadowMap.anisotropicFilteringLevel = 16;
  10047. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10048. }
  10049. else {
  10050. this._shadowMap.anisotropicFilteringLevel = 1;
  10051. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10052. }
  10053. },
  10054. enumerable: true,
  10055. configurable: true
  10056. });
  10057. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10058. get: function () {
  10059. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10060. },
  10061. set: function (value) {
  10062. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10063. },
  10064. enumerable: true,
  10065. configurable: true
  10066. });
  10067. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10068. get: function () {
  10069. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10070. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10071. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10072. },
  10073. set: function (value) {
  10074. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10080. get: function () {
  10081. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10082. },
  10083. set: function (value) {
  10084. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10085. },
  10086. enumerable: true,
  10087. configurable: true
  10088. });
  10089. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10090. var defines = [];
  10091. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10092. defines.push("#define VSM");
  10093. }
  10094. if (this.getLight().needCube()) {
  10095. defines.push("#define CUBEMAP");
  10096. }
  10097. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10098. var mesh = subMesh.getMesh();
  10099. var material = subMesh.getMaterial();
  10100. // Alpha test
  10101. if (material && material.needAlphaTesting()) {
  10102. defines.push("#define ALPHATEST");
  10103. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10104. attribs.push(BABYLON.VertexBuffer.UVKind);
  10105. defines.push("#define UV1");
  10106. }
  10107. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10108. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10109. defines.push("#define UV2");
  10110. }
  10111. }
  10112. // Bones
  10113. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10114. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10115. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10116. if (mesh.numBoneInfluencers > 4) {
  10117. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10118. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10119. }
  10120. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10121. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10122. }
  10123. else {
  10124. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10125. }
  10126. // Instances
  10127. if (useInstances) {
  10128. defines.push("#define INSTANCES");
  10129. attribs.push("world0");
  10130. attribs.push("world1");
  10131. attribs.push("world2");
  10132. attribs.push("world3");
  10133. }
  10134. // Get correct effect
  10135. var join = defines.join("\n");
  10136. if (this._cachedDefines !== join) {
  10137. this._cachedDefines = join;
  10138. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10139. }
  10140. return this._effect.isReady();
  10141. };
  10142. ShadowGenerator.prototype.getShadowMap = function () {
  10143. return this._shadowMap;
  10144. };
  10145. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10146. if (this._shadowMap2) {
  10147. return this._shadowMap2;
  10148. }
  10149. return this._shadowMap;
  10150. };
  10151. ShadowGenerator.prototype.getLight = function () {
  10152. return this._light;
  10153. };
  10154. // Methods
  10155. ShadowGenerator.prototype.getTransformMatrix = function () {
  10156. var scene = this._scene;
  10157. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10158. return this._transformMatrix;
  10159. }
  10160. this._currentRenderID = scene.getRenderId();
  10161. this._currentFaceIndexCache = this._currentFaceIndex;
  10162. var lightPosition = this._light.position;
  10163. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10164. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10165. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10166. }
  10167. if (this._light.computeTransformedPosition()) {
  10168. lightPosition = this._light.transformedPosition;
  10169. }
  10170. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10171. this._cachedPosition = lightPosition.clone();
  10172. this._cachedDirection = this._lightDirection.clone();
  10173. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10174. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10175. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10176. }
  10177. return this._transformMatrix;
  10178. };
  10179. ShadowGenerator.prototype.getDarkness = function () {
  10180. return this._darkness;
  10181. };
  10182. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10183. if (darkness >= 1.0)
  10184. this._darkness = 1.0;
  10185. else if (darkness <= 0.0)
  10186. this._darkness = 0.0;
  10187. else
  10188. this._darkness = darkness;
  10189. };
  10190. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10191. this._transparencyShadow = hasShadow;
  10192. };
  10193. ShadowGenerator.prototype._packHalf = function (depth) {
  10194. var scale = depth * 255.0;
  10195. var fract = scale - Math.floor(scale);
  10196. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10197. };
  10198. ShadowGenerator.prototype.dispose = function () {
  10199. this._shadowMap.dispose();
  10200. if (this._shadowMap2) {
  10201. this._shadowMap2.dispose();
  10202. }
  10203. if (this._downSamplePostprocess) {
  10204. this._downSamplePostprocess.dispose();
  10205. }
  10206. if (this._boxBlurPostprocess) {
  10207. this._boxBlurPostprocess.dispose();
  10208. }
  10209. };
  10210. ShadowGenerator.prototype.serialize = function () {
  10211. var serializationObject = {};
  10212. serializationObject.lightId = this._light.id;
  10213. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10214. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10215. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10216. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10217. serializationObject.renderList = [];
  10218. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10219. var mesh = this.getShadowMap().renderList[meshIndex];
  10220. serializationObject.renderList.push(mesh.id);
  10221. }
  10222. return serializationObject;
  10223. };
  10224. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10225. //casting to point light, as light is missing the position attr and typescript complains.
  10226. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10227. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10228. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10229. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  10230. shadowGenerator.getShadowMap().renderList.push(mesh);
  10231. }
  10232. if (parsedShadowGenerator.usePoissonSampling) {
  10233. shadowGenerator.usePoissonSampling = true;
  10234. }
  10235. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10236. shadowGenerator.useVarianceShadowMap = true;
  10237. }
  10238. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10239. shadowGenerator.useBlurVarianceShadowMap = true;
  10240. if (parsedShadowGenerator.blurScale) {
  10241. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10242. }
  10243. if (parsedShadowGenerator.blurBoxOffset) {
  10244. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10245. }
  10246. }
  10247. if (parsedShadowGenerator.bias !== undefined) {
  10248. shadowGenerator.bias = parsedShadowGenerator.bias;
  10249. }
  10250. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10251. return shadowGenerator;
  10252. };
  10253. ShadowGenerator._FILTER_NONE = 0;
  10254. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10255. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10256. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10257. return ShadowGenerator;
  10258. })();
  10259. BABYLON.ShadowGenerator = ShadowGenerator;
  10260. })(BABYLON || (BABYLON = {}));
  10261. var BABYLON;
  10262. (function (BABYLON) {
  10263. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10264. if (boxMin.x > sphereCenter.x + sphereRadius)
  10265. return false;
  10266. if (sphereCenter.x - sphereRadius > boxMax.x)
  10267. return false;
  10268. if (boxMin.y > sphereCenter.y + sphereRadius)
  10269. return false;
  10270. if (sphereCenter.y - sphereRadius > boxMax.y)
  10271. return false;
  10272. if (boxMin.z > sphereCenter.z + sphereRadius)
  10273. return false;
  10274. if (sphereCenter.z - sphereRadius > boxMax.z)
  10275. return false;
  10276. return true;
  10277. };
  10278. var getLowestRoot = function (a, b, c, maxR) {
  10279. var determinant = b * b - 4.0 * a * c;
  10280. var result = { root: 0, found: false };
  10281. if (determinant < 0)
  10282. return result;
  10283. var sqrtD = Math.sqrt(determinant);
  10284. var r1 = (-b - sqrtD) / (2.0 * a);
  10285. var r2 = (-b + sqrtD) / (2.0 * a);
  10286. if (r1 > r2) {
  10287. var temp = r2;
  10288. r2 = r1;
  10289. r1 = temp;
  10290. }
  10291. if (r1 > 0 && r1 < maxR) {
  10292. result.root = r1;
  10293. result.found = true;
  10294. return result;
  10295. }
  10296. if (r2 > 0 && r2 < maxR) {
  10297. result.root = r2;
  10298. result.found = true;
  10299. return result;
  10300. }
  10301. return result;
  10302. };
  10303. var Collider = (function () {
  10304. function Collider() {
  10305. this.radius = new BABYLON.Vector3(1, 1, 1);
  10306. this.retry = 0;
  10307. this.basePointWorld = BABYLON.Vector3.Zero();
  10308. this.velocityWorld = BABYLON.Vector3.Zero();
  10309. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10310. this._collisionPoint = BABYLON.Vector3.Zero();
  10311. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10312. this._tempVector = BABYLON.Vector3.Zero();
  10313. this._tempVector2 = BABYLON.Vector3.Zero();
  10314. this._tempVector3 = BABYLON.Vector3.Zero();
  10315. this._tempVector4 = BABYLON.Vector3.Zero();
  10316. this._edge = BABYLON.Vector3.Zero();
  10317. this._baseToVertex = BABYLON.Vector3.Zero();
  10318. this._destinationPoint = BABYLON.Vector3.Zero();
  10319. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10320. this._displacementVector = BABYLON.Vector3.Zero();
  10321. }
  10322. // Methods
  10323. Collider.prototype._initialize = function (source, dir, e) {
  10324. this.velocity = dir;
  10325. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10326. this.basePoint = source;
  10327. source.multiplyToRef(this.radius, this.basePointWorld);
  10328. dir.multiplyToRef(this.radius, this.velocityWorld);
  10329. this.velocityWorldLength = this.velocityWorld.length();
  10330. this.epsilon = e;
  10331. this.collisionFound = false;
  10332. };
  10333. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10334. pa.subtractToRef(point, this._tempVector);
  10335. pb.subtractToRef(point, this._tempVector2);
  10336. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10337. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10338. if (d < 0)
  10339. return false;
  10340. pc.subtractToRef(point, this._tempVector3);
  10341. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10342. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10343. if (d < 0)
  10344. return false;
  10345. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10346. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10347. return d >= 0;
  10348. };
  10349. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10350. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10351. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10352. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10353. return false;
  10354. }
  10355. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10356. return false;
  10357. return true;
  10358. };
  10359. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10360. var t0;
  10361. var embeddedInPlane = false;
  10362. //defensive programming, actually not needed.
  10363. if (!trianglePlaneArray) {
  10364. trianglePlaneArray = [];
  10365. }
  10366. if (!trianglePlaneArray[faceIndex]) {
  10367. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10368. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10369. }
  10370. var trianglePlane = trianglePlaneArray[faceIndex];
  10371. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10372. return;
  10373. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10374. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10375. if (normalDotVelocity == 0) {
  10376. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10377. return;
  10378. embeddedInPlane = true;
  10379. t0 = 0;
  10380. }
  10381. else {
  10382. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10383. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10384. if (t0 > t1) {
  10385. var temp = t1;
  10386. t1 = t0;
  10387. t0 = temp;
  10388. }
  10389. if (t0 > 1.0 || t1 < 0.0)
  10390. return;
  10391. if (t0 < 0)
  10392. t0 = 0;
  10393. if (t0 > 1.0)
  10394. t0 = 1.0;
  10395. }
  10396. this._collisionPoint.copyFromFloats(0, 0, 0);
  10397. var found = false;
  10398. var t = 1.0;
  10399. if (!embeddedInPlane) {
  10400. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10401. this.velocity.scaleToRef(t0, this._tempVector);
  10402. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10403. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10404. found = true;
  10405. t = t0;
  10406. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10407. }
  10408. }
  10409. if (!found) {
  10410. var velocitySquaredLength = this.velocity.lengthSquared();
  10411. var a = velocitySquaredLength;
  10412. this.basePoint.subtractToRef(p1, this._tempVector);
  10413. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10414. var c = this._tempVector.lengthSquared() - 1.0;
  10415. var lowestRoot = getLowestRoot(a, b, c, t);
  10416. if (lowestRoot.found) {
  10417. t = lowestRoot.root;
  10418. found = true;
  10419. this._collisionPoint.copyFrom(p1);
  10420. }
  10421. this.basePoint.subtractToRef(p2, this._tempVector);
  10422. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10423. c = this._tempVector.lengthSquared() - 1.0;
  10424. lowestRoot = getLowestRoot(a, b, c, t);
  10425. if (lowestRoot.found) {
  10426. t = lowestRoot.root;
  10427. found = true;
  10428. this._collisionPoint.copyFrom(p2);
  10429. }
  10430. this.basePoint.subtractToRef(p3, this._tempVector);
  10431. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10432. c = this._tempVector.lengthSquared() - 1.0;
  10433. lowestRoot = getLowestRoot(a, b, c, t);
  10434. if (lowestRoot.found) {
  10435. t = lowestRoot.root;
  10436. found = true;
  10437. this._collisionPoint.copyFrom(p3);
  10438. }
  10439. p2.subtractToRef(p1, this._edge);
  10440. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10441. var edgeSquaredLength = this._edge.lengthSquared();
  10442. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10443. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10444. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10445. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10446. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10447. lowestRoot = getLowestRoot(a, b, c, t);
  10448. if (lowestRoot.found) {
  10449. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10450. if (f >= 0.0 && f <= 1.0) {
  10451. t = lowestRoot.root;
  10452. found = true;
  10453. this._edge.scaleInPlace(f);
  10454. p1.addToRef(this._edge, this._collisionPoint);
  10455. }
  10456. }
  10457. p3.subtractToRef(p2, this._edge);
  10458. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10459. edgeSquaredLength = this._edge.lengthSquared();
  10460. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10461. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10462. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10463. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10464. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10465. lowestRoot = getLowestRoot(a, b, c, t);
  10466. if (lowestRoot.found) {
  10467. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10468. if (f >= 0.0 && f <= 1.0) {
  10469. t = lowestRoot.root;
  10470. found = true;
  10471. this._edge.scaleInPlace(f);
  10472. p2.addToRef(this._edge, this._collisionPoint);
  10473. }
  10474. }
  10475. p1.subtractToRef(p3, this._edge);
  10476. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10477. edgeSquaredLength = this._edge.lengthSquared();
  10478. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10479. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10480. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10481. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10482. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10483. lowestRoot = getLowestRoot(a, b, c, t);
  10484. if (lowestRoot.found) {
  10485. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10486. if (f >= 0.0 && f <= 1.0) {
  10487. t = lowestRoot.root;
  10488. found = true;
  10489. this._edge.scaleInPlace(f);
  10490. p3.addToRef(this._edge, this._collisionPoint);
  10491. }
  10492. }
  10493. }
  10494. if (found) {
  10495. var distToCollision = t * this.velocity.length();
  10496. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10497. if (!this.intersectionPoint) {
  10498. this.intersectionPoint = this._collisionPoint.clone();
  10499. }
  10500. else {
  10501. this.intersectionPoint.copyFrom(this._collisionPoint);
  10502. }
  10503. this.nearestDistance = distToCollision;
  10504. this.collisionFound = true;
  10505. }
  10506. }
  10507. };
  10508. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10509. for (var i = indexStart; i < indexEnd; i += 3) {
  10510. var p1 = pts[indices[i] - decal];
  10511. var p2 = pts[indices[i + 1] - decal];
  10512. var p3 = pts[indices[i + 2] - decal];
  10513. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10514. }
  10515. };
  10516. Collider.prototype._getResponse = function (pos, vel) {
  10517. pos.addToRef(vel, this._destinationPoint);
  10518. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10519. this.basePoint.addToRef(vel, pos);
  10520. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10521. this._slidePlaneNormal.normalize();
  10522. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10523. pos.addInPlace(this._displacementVector);
  10524. this.intersectionPoint.addInPlace(this._displacementVector);
  10525. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10526. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10527. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10528. };
  10529. return Collider;
  10530. })();
  10531. BABYLON.Collider = Collider;
  10532. })(BABYLON || (BABYLON = {}));
  10533. var BABYLON;
  10534. (function (BABYLON) {
  10535. //WebWorker code will be inserted to this variable.
  10536. BABYLON.CollisionWorker = "";
  10537. (function (WorkerTaskType) {
  10538. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10539. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10540. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10541. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10542. var WorkerTaskType = BABYLON.WorkerTaskType;
  10543. (function (WorkerReplyType) {
  10544. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10545. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10546. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10547. var WorkerReplyType = BABYLON.WorkerReplyType;
  10548. var CollisionCoordinatorWorker = (function () {
  10549. function CollisionCoordinatorWorker() {
  10550. var _this = this;
  10551. this._scaledPosition = BABYLON.Vector3.Zero();
  10552. this._scaledVelocity = BABYLON.Vector3.Zero();
  10553. this.onMeshUpdated = function (mesh) {
  10554. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10555. };
  10556. this.onGeometryUpdated = function (geometry) {
  10557. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10558. };
  10559. this._afterRender = function () {
  10560. if (!_this._init)
  10561. return;
  10562. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10563. return;
  10564. }
  10565. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10566. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10567. if (_this._runningUpdated > 4) {
  10568. return;
  10569. }
  10570. ++_this._runningUpdated;
  10571. var payload = {
  10572. updatedMeshes: _this._addUpdateMeshesList,
  10573. updatedGeometries: _this._addUpdateGeometriesList,
  10574. removedGeometries: _this._toRemoveGeometryArray,
  10575. removedMeshes: _this._toRemoveMeshesArray
  10576. };
  10577. var message = {
  10578. payload: payload,
  10579. taskType: WorkerTaskType.UPDATE
  10580. };
  10581. var serializable = [];
  10582. for (var id in payload.updatedGeometries) {
  10583. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10584. //prepare transferables
  10585. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10586. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10587. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10588. }
  10589. }
  10590. _this._worker.postMessage(message, serializable);
  10591. _this._addUpdateMeshesList = {};
  10592. _this._addUpdateGeometriesList = {};
  10593. _this._toRemoveGeometryArray = [];
  10594. _this._toRemoveMeshesArray = [];
  10595. };
  10596. this._onMessageFromWorker = function (e) {
  10597. var returnData = e.data;
  10598. if (returnData.error != WorkerReplyType.SUCCESS) {
  10599. //TODO what errors can be returned from the worker?
  10600. BABYLON.Tools.Warn("error returned from worker!");
  10601. return;
  10602. }
  10603. switch (returnData.taskType) {
  10604. case WorkerTaskType.INIT:
  10605. _this._init = true;
  10606. //Update the worked with ALL of the scene's current state
  10607. _this._scene.meshes.forEach(function (mesh) {
  10608. _this.onMeshAdded(mesh);
  10609. });
  10610. _this._scene.getGeometries().forEach(function (geometry) {
  10611. _this.onGeometryAdded(geometry);
  10612. });
  10613. break;
  10614. case WorkerTaskType.UPDATE:
  10615. _this._runningUpdated--;
  10616. break;
  10617. case WorkerTaskType.COLLIDE:
  10618. _this._runningCollisionTask = false;
  10619. var returnPayload = returnData.payload;
  10620. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10621. return;
  10622. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10623. //cleanup
  10624. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10625. break;
  10626. }
  10627. };
  10628. this._collisionsCallbackArray = [];
  10629. this._init = false;
  10630. this._runningUpdated = 0;
  10631. this._runningCollisionTask = false;
  10632. this._addUpdateMeshesList = {};
  10633. this._addUpdateGeometriesList = {};
  10634. this._toRemoveGeometryArray = [];
  10635. this._toRemoveMeshesArray = [];
  10636. }
  10637. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10638. if (!this._init)
  10639. return;
  10640. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10641. return;
  10642. position.divideToRef(collider.radius, this._scaledPosition);
  10643. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10644. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10645. var payload = {
  10646. collider: {
  10647. position: this._scaledPosition.asArray(),
  10648. velocity: this._scaledVelocity.asArray(),
  10649. radius: collider.radius.asArray()
  10650. },
  10651. collisionId: collisionIndex,
  10652. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10653. maximumRetry: maximumRetry
  10654. };
  10655. var message = {
  10656. payload: payload,
  10657. taskType: WorkerTaskType.COLLIDE
  10658. };
  10659. this._worker.postMessage(message);
  10660. };
  10661. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10662. this._scene = scene;
  10663. this._scene.registerAfterRender(this._afterRender);
  10664. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10665. this._worker = new Worker(workerUrl);
  10666. this._worker.onmessage = this._onMessageFromWorker;
  10667. var message = {
  10668. payload: {},
  10669. taskType: WorkerTaskType.INIT
  10670. };
  10671. this._worker.postMessage(message);
  10672. };
  10673. CollisionCoordinatorWorker.prototype.destroy = function () {
  10674. this._scene.unregisterAfterRender(this._afterRender);
  10675. this._worker.terminate();
  10676. };
  10677. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10678. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10679. this.onMeshUpdated(mesh);
  10680. };
  10681. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10682. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10683. };
  10684. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10685. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10686. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10687. this.onGeometryUpdated(geometry);
  10688. };
  10689. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10690. this._toRemoveGeometryArray.push(geometry.id);
  10691. };
  10692. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10693. var submeshes = [];
  10694. if (mesh.subMeshes) {
  10695. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10696. return {
  10697. position: idx,
  10698. verticesStart: sm.verticesStart,
  10699. verticesCount: sm.verticesCount,
  10700. indexStart: sm.indexStart,
  10701. indexCount: sm.indexCount,
  10702. hasMaterial: !!sm.getMaterial(),
  10703. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10704. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10705. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10706. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10707. };
  10708. });
  10709. }
  10710. var geometryId = null;
  10711. if (mesh instanceof BABYLON.Mesh) {
  10712. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10713. }
  10714. else if (mesh instanceof BABYLON.InstancedMesh) {
  10715. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10716. }
  10717. return {
  10718. uniqueId: mesh.uniqueId,
  10719. id: mesh.id,
  10720. name: mesh.name,
  10721. geometryId: geometryId,
  10722. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10723. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10724. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10725. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10726. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10727. subMeshes: submeshes,
  10728. checkCollisions: mesh.checkCollisions
  10729. };
  10730. };
  10731. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10732. return {
  10733. id: geometry.id,
  10734. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10735. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10736. indices: new Int32Array(geometry.getIndices() || []),
  10737. };
  10738. };
  10739. return CollisionCoordinatorWorker;
  10740. })();
  10741. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10742. var CollisionCoordinatorLegacy = (function () {
  10743. function CollisionCoordinatorLegacy() {
  10744. this._scaledPosition = BABYLON.Vector3.Zero();
  10745. this._scaledVelocity = BABYLON.Vector3.Zero();
  10746. this._finalPosition = BABYLON.Vector3.Zero();
  10747. }
  10748. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10749. position.divideToRef(collider.radius, this._scaledPosition);
  10750. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10751. collider.collidedMesh = null;
  10752. collider.retry = 0;
  10753. collider.initialVelocity = this._scaledVelocity;
  10754. collider.initialPosition = this._scaledPosition;
  10755. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10756. this._finalPosition.multiplyInPlace(collider.radius);
  10757. //run the callback
  10758. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10759. };
  10760. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10761. this._scene = scene;
  10762. };
  10763. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10764. //Legacy need no destruction method.
  10765. };
  10766. //No update in legacy mode
  10767. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10768. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10769. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10770. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10771. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10772. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10773. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10774. if (excludedMesh === void 0) { excludedMesh = null; }
  10775. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10776. if (collider.retry >= maximumRetry) {
  10777. finalPosition.copyFrom(position);
  10778. return;
  10779. }
  10780. collider._initialize(position, velocity, closeDistance);
  10781. // Check all meshes
  10782. for (var index = 0; index < this._scene.meshes.length; index++) {
  10783. var mesh = this._scene.meshes[index];
  10784. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10785. mesh._checkCollision(collider);
  10786. }
  10787. }
  10788. if (!collider.collisionFound) {
  10789. position.addToRef(velocity, finalPosition);
  10790. return;
  10791. }
  10792. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10793. collider._getResponse(position, velocity);
  10794. }
  10795. if (velocity.length() <= closeDistance) {
  10796. finalPosition.copyFrom(position);
  10797. return;
  10798. }
  10799. collider.retry++;
  10800. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10801. };
  10802. return CollisionCoordinatorLegacy;
  10803. })();
  10804. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10805. })(BABYLON || (BABYLON = {}));
  10806. var BABYLON;
  10807. (function (BABYLON) {
  10808. var Camera = (function (_super) {
  10809. __extends(Camera, _super);
  10810. function Camera(name, position, scene) {
  10811. _super.call(this, name, scene);
  10812. this.upVector = BABYLON.Vector3.Up();
  10813. this.orthoLeft = null;
  10814. this.orthoRight = null;
  10815. this.orthoBottom = null;
  10816. this.orthoTop = null;
  10817. this.fov = 0.8;
  10818. this.minZ = 1.0;
  10819. this.maxZ = 10000.0;
  10820. this.inertia = 0.9;
  10821. this.mode = Camera.PERSPECTIVE_CAMERA;
  10822. this.isIntermediate = false;
  10823. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10824. this.layerMask = 0x0FFFFFFF;
  10825. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10826. // Camera rig members
  10827. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10828. this._rigCameras = new Array();
  10829. // Cache
  10830. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10831. this._projectionMatrix = new BABYLON.Matrix();
  10832. this._postProcesses = new Array();
  10833. this._postProcessesTakenIndices = [];
  10834. this._activeMeshes = new BABYLON.SmartArray(256);
  10835. this._globalPosition = BABYLON.Vector3.Zero();
  10836. scene.addCamera(this);
  10837. if (!scene.activeCamera) {
  10838. scene.activeCamera = this;
  10839. }
  10840. this.position = position;
  10841. }
  10842. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10843. get: function () {
  10844. return Camera._PERSPECTIVE_CAMERA;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10850. get: function () {
  10851. return Camera._ORTHOGRAPHIC_CAMERA;
  10852. },
  10853. enumerable: true,
  10854. configurable: true
  10855. });
  10856. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10857. get: function () {
  10858. return Camera._FOVMODE_VERTICAL_FIXED;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10864. get: function () {
  10865. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10866. },
  10867. enumerable: true,
  10868. configurable: true
  10869. });
  10870. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10871. get: function () {
  10872. return Camera._RIG_MODE_NONE;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10878. get: function () {
  10879. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10885. get: function () {
  10886. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10892. get: function () {
  10893. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10899. get: function () {
  10900. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10906. get: function () {
  10907. return Camera._RIG_MODE_VR;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. /**
  10913. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10914. */
  10915. Camera.prototype.toString = function (fullDetails) {
  10916. var ret = "Name: " + this.name;
  10917. ret += ", type: " + this.getTypeName();
  10918. if (this.animations) {
  10919. for (var i = 0; i < this.animations.length; i++) {
  10920. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10921. }
  10922. }
  10923. if (fullDetails) {
  10924. }
  10925. return ret;
  10926. };
  10927. Object.defineProperty(Camera.prototype, "globalPosition", {
  10928. get: function () {
  10929. return this._globalPosition;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Camera.prototype.getActiveMeshes = function () {
  10935. return this._activeMeshes;
  10936. };
  10937. Camera.prototype.isActiveMesh = function (mesh) {
  10938. return (this._activeMeshes.indexOf(mesh) !== -1);
  10939. };
  10940. //Cache
  10941. Camera.prototype._initCache = function () {
  10942. _super.prototype._initCache.call(this);
  10943. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10944. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10945. this._cache.mode = undefined;
  10946. this._cache.minZ = undefined;
  10947. this._cache.maxZ = undefined;
  10948. this._cache.fov = undefined;
  10949. this._cache.aspectRatio = undefined;
  10950. this._cache.orthoLeft = undefined;
  10951. this._cache.orthoRight = undefined;
  10952. this._cache.orthoBottom = undefined;
  10953. this._cache.orthoTop = undefined;
  10954. this._cache.renderWidth = undefined;
  10955. this._cache.renderHeight = undefined;
  10956. };
  10957. Camera.prototype._updateCache = function (ignoreParentClass) {
  10958. if (!ignoreParentClass) {
  10959. _super.prototype._updateCache.call(this);
  10960. }
  10961. var engine = this.getEngine();
  10962. this._cache.position.copyFrom(this.position);
  10963. this._cache.upVector.copyFrom(this.upVector);
  10964. this._cache.mode = this.mode;
  10965. this._cache.minZ = this.minZ;
  10966. this._cache.maxZ = this.maxZ;
  10967. this._cache.fov = this.fov;
  10968. this._cache.aspectRatio = engine.getAspectRatio(this);
  10969. this._cache.orthoLeft = this.orthoLeft;
  10970. this._cache.orthoRight = this.orthoRight;
  10971. this._cache.orthoBottom = this.orthoBottom;
  10972. this._cache.orthoTop = this.orthoTop;
  10973. this._cache.renderWidth = engine.getRenderWidth();
  10974. this._cache.renderHeight = engine.getRenderHeight();
  10975. };
  10976. Camera.prototype._updateFromScene = function () {
  10977. this.updateCache();
  10978. this._update();
  10979. };
  10980. // Synchronized
  10981. Camera.prototype._isSynchronized = function () {
  10982. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10983. };
  10984. Camera.prototype._isSynchronizedViewMatrix = function () {
  10985. if (!_super.prototype._isSynchronized.call(this))
  10986. return false;
  10987. return this._cache.position.equals(this.position)
  10988. && this._cache.upVector.equals(this.upVector)
  10989. && this.isSynchronizedWithParent();
  10990. };
  10991. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10992. var check = this._cache.mode === this.mode
  10993. && this._cache.minZ === this.minZ
  10994. && this._cache.maxZ === this.maxZ;
  10995. if (!check) {
  10996. return false;
  10997. }
  10998. var engine = this.getEngine();
  10999. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11000. check = this._cache.fov === this.fov
  11001. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11002. }
  11003. else {
  11004. check = this._cache.orthoLeft === this.orthoLeft
  11005. && this._cache.orthoRight === this.orthoRight
  11006. && this._cache.orthoBottom === this.orthoBottom
  11007. && this._cache.orthoTop === this.orthoTop
  11008. && this._cache.renderWidth === engine.getRenderWidth()
  11009. && this._cache.renderHeight === engine.getRenderHeight();
  11010. }
  11011. return check;
  11012. };
  11013. // Controls
  11014. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11015. };
  11016. Camera.prototype.detachControl = function (element) {
  11017. };
  11018. Camera.prototype._update = function () {
  11019. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11020. this._updateRigCameras();
  11021. }
  11022. this._checkInputs();
  11023. };
  11024. Camera.prototype._checkInputs = function () {
  11025. };
  11026. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11027. if (insertAt === void 0) { insertAt = null; }
  11028. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11029. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11030. return 0;
  11031. }
  11032. if (insertAt == null || insertAt < 0) {
  11033. this._postProcesses.push(postProcess);
  11034. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  11035. return this._postProcesses.length - 1;
  11036. }
  11037. var add = 0;
  11038. var i;
  11039. var start;
  11040. if (this._postProcesses[insertAt]) {
  11041. start = this._postProcesses.length - 1;
  11042. for (i = start; i >= insertAt + 1; --i) {
  11043. this._postProcesses[i + 1] = this._postProcesses[i];
  11044. }
  11045. add = 1;
  11046. }
  11047. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11048. if (this._postProcessesTakenIndices[i] < insertAt) {
  11049. continue;
  11050. }
  11051. start = this._postProcessesTakenIndices.length - 1;
  11052. for (var j = start; j >= i; --j) {
  11053. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  11054. }
  11055. this._postProcessesTakenIndices[i] = insertAt;
  11056. break;
  11057. }
  11058. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  11059. this._postProcessesTakenIndices.push(insertAt);
  11060. }
  11061. var result = insertAt + add;
  11062. this._postProcesses[result] = postProcess;
  11063. return result;
  11064. };
  11065. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11066. if (atIndices === void 0) { atIndices = null; }
  11067. var result = [];
  11068. var i;
  11069. var index;
  11070. if (!atIndices) {
  11071. var length = this._postProcesses.length;
  11072. for (i = 0; i < length; i++) {
  11073. if (this._postProcesses[i] !== postProcess) {
  11074. continue;
  11075. }
  11076. delete this._postProcesses[i];
  11077. index = this._postProcessesTakenIndices.indexOf(i);
  11078. this._postProcessesTakenIndices.splice(index, 1);
  11079. }
  11080. }
  11081. else {
  11082. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11083. for (i = 0; i < atIndices.length; i++) {
  11084. var foundPostProcess = this._postProcesses[atIndices[i]];
  11085. if (foundPostProcess !== postProcess) {
  11086. result.push(i);
  11087. continue;
  11088. }
  11089. delete this._postProcesses[atIndices[i]];
  11090. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  11091. this._postProcessesTakenIndices.splice(index, 1);
  11092. }
  11093. }
  11094. return result;
  11095. };
  11096. Camera.prototype.getWorldMatrix = function () {
  11097. if (!this._worldMatrix) {
  11098. this._worldMatrix = BABYLON.Matrix.Identity();
  11099. }
  11100. var viewMatrix = this.getViewMatrix();
  11101. viewMatrix.invertToRef(this._worldMatrix);
  11102. return this._worldMatrix;
  11103. };
  11104. Camera.prototype._getViewMatrix = function () {
  11105. return BABYLON.Matrix.Identity();
  11106. };
  11107. Camera.prototype.getViewMatrix = function (force) {
  11108. this._computedViewMatrix = this._computeViewMatrix(force);
  11109. if (!force && this._isSynchronizedViewMatrix()) {
  11110. return this._computedViewMatrix;
  11111. }
  11112. if (!this.parent || !this.parent.getWorldMatrix) {
  11113. this._globalPosition.copyFrom(this.position);
  11114. }
  11115. else {
  11116. if (!this._worldMatrix) {
  11117. this._worldMatrix = BABYLON.Matrix.Identity();
  11118. }
  11119. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11120. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11121. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11122. this._computedViewMatrix.invert();
  11123. this._markSyncedWithParent();
  11124. }
  11125. this._currentRenderId = this.getScene().getRenderId();
  11126. return this._computedViewMatrix;
  11127. };
  11128. Camera.prototype._computeViewMatrix = function (force) {
  11129. if (!force && this._isSynchronizedViewMatrix()) {
  11130. return this._computedViewMatrix;
  11131. }
  11132. this._computedViewMatrix = this._getViewMatrix();
  11133. this._currentRenderId = this.getScene().getRenderId();
  11134. return this._computedViewMatrix;
  11135. };
  11136. Camera.prototype.getProjectionMatrix = function (force) {
  11137. if (!force && this._isSynchronizedProjectionMatrix()) {
  11138. return this._projectionMatrix;
  11139. }
  11140. var engine = this.getEngine();
  11141. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11142. if (this.minZ <= 0) {
  11143. this.minZ = 0.1;
  11144. }
  11145. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11146. return this._projectionMatrix;
  11147. }
  11148. var halfWidth = engine.getRenderWidth() / 2.0;
  11149. var halfHeight = engine.getRenderHeight() / 2.0;
  11150. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11151. return this._projectionMatrix;
  11152. };
  11153. Camera.prototype.dispose = function () {
  11154. // Animations
  11155. this.getScene().stopAnimation(this);
  11156. // Remove from scene
  11157. this.getScene().removeCamera(this);
  11158. while (this._rigCameras.length > 0) {
  11159. this._rigCameras.pop().dispose();
  11160. }
  11161. // Postprocesses
  11162. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11163. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  11164. }
  11165. _super.prototype.dispose.call(this);
  11166. };
  11167. // ---- Camera rigs section ----
  11168. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11169. while (this._rigCameras.length > 0) {
  11170. this._rigCameras.pop().dispose();
  11171. }
  11172. this.cameraRigMode = mode;
  11173. this._cameraRigParams = {};
  11174. switch (this.cameraRigMode) {
  11175. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11176. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11177. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11178. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11179. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11180. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11181. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11182. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11183. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11184. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11185. break;
  11186. }
  11187. var postProcesses = new Array();
  11188. switch (this.cameraRigMode) {
  11189. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11190. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  11191. this._rigCameras[0].isIntermediate = true;
  11192. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  11193. postProcesses[1].onApply = function (effect) {
  11194. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  11195. };
  11196. break;
  11197. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11198. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11199. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11200. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  11201. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  11202. var secondCamIndex = 1 - firstCamIndex;
  11203. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  11204. this._rigCameras[firstCamIndex].isIntermediate = true;
  11205. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  11206. break;
  11207. case Camera.RIG_MODE_VR:
  11208. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11209. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11210. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11211. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11212. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11213. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11214. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11215. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11216. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11217. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11218. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11219. if (metrics.compensateDistortion) {
  11220. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  11221. }
  11222. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  11223. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11224. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11225. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11226. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11227. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11228. if (metrics.compensateDistortion) {
  11229. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  11230. }
  11231. break;
  11232. }
  11233. this._update();
  11234. };
  11235. Camera.prototype._getVRProjectionMatrix = function () {
  11236. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11237. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11238. return this._projectionMatrix;
  11239. };
  11240. Camera.prototype.setCameraRigParameter = function (name, value) {
  11241. this._cameraRigParams[name] = value;
  11242. //provisionnally:
  11243. if (name === "interaxialDistance") {
  11244. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11245. }
  11246. };
  11247. /**
  11248. * May needs to be overridden by children so sub has required properties to be copied
  11249. */
  11250. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11251. return null;
  11252. };
  11253. /**
  11254. * May needs to be overridden by children
  11255. */
  11256. Camera.prototype._updateRigCameras = function () {
  11257. for (var i = 0; i < this._rigCameras.length; i++) {
  11258. this._rigCameras[i].minZ = this.minZ;
  11259. this._rigCameras[i].maxZ = this.maxZ;
  11260. this._rigCameras[i].fov = this.fov;
  11261. }
  11262. // only update viewport when ANAGLYPH
  11263. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11264. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11265. }
  11266. };
  11267. Camera.prototype.serialize = function () {
  11268. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11269. // Type
  11270. serializationObject.type = this.getTypeName();
  11271. // Parent
  11272. if (this.parent) {
  11273. serializationObject.parentId = this.parent.id;
  11274. }
  11275. if (this.inputs) {
  11276. this.inputs.serialize(serializationObject);
  11277. }
  11278. // Animations
  11279. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11280. serializationObject.ranges = this.serializeAnimationRanges();
  11281. return serializationObject;
  11282. };
  11283. Camera.prototype.getTypeName = function () {
  11284. return "Camera";
  11285. };
  11286. Camera.prototype.clone = function (name) {
  11287. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11288. };
  11289. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11290. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11291. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11292. switch (type) {
  11293. case "ArcRotateCamera":
  11294. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11295. case "DeviceOrientationCamera":
  11296. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11297. case "FollowCamera":
  11298. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11299. case "ArcFollowCamera":
  11300. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11301. case "GamepadCamera":
  11302. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11303. case "TouchCamera":
  11304. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11305. case "VirtualJoysticksCamera":
  11306. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11307. case "WebVRFreeCamera":
  11308. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11309. case "VRDeviceOrientationFreeCamera":
  11310. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11311. case "AnaglyphArcRotateCamera":
  11312. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11313. case "AnaglyphFreeCamera":
  11314. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11315. case "AnaglyphGamepadCamera":
  11316. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11317. case "AnaglyphUniversalCamera":
  11318. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11319. case "StereoscopicArcRotateCamera":
  11320. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11321. case "StereoscopicFreeCamera":
  11322. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11323. case "StereoscopicGamepadCamera":
  11324. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11325. case "StereoscopicUniversalCamera":
  11326. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11327. case "FreeCamera":
  11328. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11329. default:
  11330. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11331. }
  11332. };
  11333. Camera.Parse = function (parsedCamera, scene) {
  11334. var type = parsedCamera.type;
  11335. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11336. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11337. // Parent
  11338. if (parsedCamera.parentId) {
  11339. camera._waitingParentId = parsedCamera.parentId;
  11340. }
  11341. //If camera has an input manager, let it parse inputs settings
  11342. if (camera.inputs) {
  11343. camera.inputs.parse(parsedCamera);
  11344. }
  11345. // Target
  11346. if (parsedCamera.target) {
  11347. if (camera.setTarget) {
  11348. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11349. }
  11350. }
  11351. // Apply 3d rig, when found
  11352. if (parsedCamera.cameraRigMode) {
  11353. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11354. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11355. }
  11356. // Animations
  11357. if (parsedCamera.animations) {
  11358. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11359. var parsedAnimation = parsedCamera.animations[animationIndex];
  11360. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11361. }
  11362. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11363. }
  11364. if (parsedCamera.autoAnimate) {
  11365. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11366. }
  11367. return camera;
  11368. };
  11369. // Statics
  11370. Camera._PERSPECTIVE_CAMERA = 0;
  11371. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11372. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11373. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11374. Camera._RIG_MODE_NONE = 0;
  11375. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11376. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11377. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11378. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11379. Camera._RIG_MODE_VR = 20;
  11380. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11381. __decorate([
  11382. BABYLON.serializeAsVector3()
  11383. ], Camera.prototype, "position", void 0);
  11384. __decorate([
  11385. BABYLON.serializeAsVector3()
  11386. ], Camera.prototype, "upVector", void 0);
  11387. __decorate([
  11388. BABYLON.serialize()
  11389. ], Camera.prototype, "orthoLeft", void 0);
  11390. __decorate([
  11391. BABYLON.serialize()
  11392. ], Camera.prototype, "orthoRight", void 0);
  11393. __decorate([
  11394. BABYLON.serialize()
  11395. ], Camera.prototype, "orthoBottom", void 0);
  11396. __decorate([
  11397. BABYLON.serialize()
  11398. ], Camera.prototype, "orthoTop", void 0);
  11399. __decorate([
  11400. BABYLON.serialize()
  11401. ], Camera.prototype, "fov", void 0);
  11402. __decorate([
  11403. BABYLON.serialize()
  11404. ], Camera.prototype, "minZ", void 0);
  11405. __decorate([
  11406. BABYLON.serialize()
  11407. ], Camera.prototype, "maxZ", void 0);
  11408. __decorate([
  11409. BABYLON.serialize()
  11410. ], Camera.prototype, "inertia", void 0);
  11411. __decorate([
  11412. BABYLON.serialize()
  11413. ], Camera.prototype, "mode", void 0);
  11414. __decorate([
  11415. BABYLON.serialize()
  11416. ], Camera.prototype, "layerMask", void 0);
  11417. __decorate([
  11418. BABYLON.serialize()
  11419. ], Camera.prototype, "fovMode", void 0);
  11420. __decorate([
  11421. BABYLON.serialize()
  11422. ], Camera.prototype, "cameraRigMode", void 0);
  11423. __decorate([
  11424. BABYLON.serialize()
  11425. ], Camera.prototype, "interaxialDistance", void 0);
  11426. __decorate([
  11427. BABYLON.serialize()
  11428. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11429. return Camera;
  11430. })(BABYLON.Node);
  11431. BABYLON.Camera = Camera;
  11432. })(BABYLON || (BABYLON = {}));
  11433. var BABYLON;
  11434. (function (BABYLON) {
  11435. BABYLON.CameraInputTypes = {};
  11436. var CameraInputsManager = (function () {
  11437. function CameraInputsManager(camera) {
  11438. this.attached = {};
  11439. this.camera = camera;
  11440. this.checkInputs = function () { };
  11441. }
  11442. CameraInputsManager.prototype.add = function (input) {
  11443. var type = input.getSimpleName();
  11444. if (this.attached[type]) {
  11445. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11446. return;
  11447. }
  11448. this.attached[type] = input;
  11449. input.camera = this.camera;
  11450. //for checkInputs, we are dynamically creating a function
  11451. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11452. if (input.checkInputs) {
  11453. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11454. }
  11455. if (this.attachedElement) {
  11456. input.attachControl(this.attachedElement);
  11457. }
  11458. };
  11459. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11460. for (var cam in this.attached) {
  11461. var input = this.attached[cam];
  11462. if (input === inputToRemove) {
  11463. input.detachControl(this.attachedElement);
  11464. delete this.attached[cam];
  11465. this.rebuildInputCheck();
  11466. }
  11467. }
  11468. };
  11469. CameraInputsManager.prototype.removeByType = function (inputType) {
  11470. for (var cam in this.attached) {
  11471. var input = this.attached[cam];
  11472. if (input.getTypeName() === inputType) {
  11473. input.detachControl(this.attachedElement);
  11474. delete this.attached[cam];
  11475. this.rebuildInputCheck();
  11476. }
  11477. }
  11478. };
  11479. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11480. var current = this.checkInputs;
  11481. return function () {
  11482. current();
  11483. fn();
  11484. };
  11485. };
  11486. CameraInputsManager.prototype.attachInput = function (input) {
  11487. input.attachControl(this.attachedElement, this.noPreventDefault);
  11488. };
  11489. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11490. if (this.attachedElement) {
  11491. return;
  11492. }
  11493. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11494. this.attachedElement = element;
  11495. this.noPreventDefault = noPreventDefault;
  11496. for (var cam in this.attached) {
  11497. var input = this.attached[cam];
  11498. this.attached[cam].attachControl(element, noPreventDefault);
  11499. }
  11500. };
  11501. CameraInputsManager.prototype.detachElement = function (element) {
  11502. if (this.attachedElement !== element) {
  11503. return;
  11504. }
  11505. for (var cam in this.attached) {
  11506. var input = this.attached[cam];
  11507. this.attached[cam].detachControl(element);
  11508. }
  11509. this.attachedElement = null;
  11510. };
  11511. CameraInputsManager.prototype.rebuildInputCheck = function () {
  11512. this.checkInputs = function () { };
  11513. for (var cam in this.attached) {
  11514. var input = this.attached[cam];
  11515. if (input.checkInputs) {
  11516. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11517. }
  11518. }
  11519. };
  11520. CameraInputsManager.prototype.clear = function () {
  11521. if (this.attachedElement) {
  11522. this.detachElement(this.attachedElement);
  11523. }
  11524. this.attached = {};
  11525. this.attachedElement = null;
  11526. this.checkInputs = function () { };
  11527. };
  11528. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11529. var inputs = {};
  11530. for (var cam in this.attached) {
  11531. var input = this.attached[cam];
  11532. var res = BABYLON.SerializationHelper.Serialize(input);
  11533. inputs[input.getTypeName()] = res;
  11534. }
  11535. serializedCamera.inputsmgr = inputs;
  11536. };
  11537. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11538. var parsedInputs = parsedCamera.inputsmgr;
  11539. if (parsedInputs) {
  11540. this.clear();
  11541. for (var n in parsedInputs) {
  11542. var construct = BABYLON.CameraInputTypes[n];
  11543. if (construct) {
  11544. var parsedinput = parsedInputs[n];
  11545. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11546. this.add(input);
  11547. }
  11548. }
  11549. }
  11550. else {
  11551. //2016-03-08 this part is for managing backward compatibility
  11552. for (var n in this.attached) {
  11553. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11554. if (construct) {
  11555. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11556. this.remove(this.attached[n]);
  11557. this.add(input);
  11558. }
  11559. }
  11560. }
  11561. };
  11562. return CameraInputsManager;
  11563. })();
  11564. BABYLON.CameraInputsManager = CameraInputsManager;
  11565. })(BABYLON || (BABYLON = {}));
  11566. var BABYLON;
  11567. (function (BABYLON) {
  11568. var FreeCameraMouseInput = (function () {
  11569. function FreeCameraMouseInput() {
  11570. this.angularSensibility = 2000.0;
  11571. }
  11572. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11573. var _this = this;
  11574. if (!this._pointerInput) {
  11575. var camera = this.camera;
  11576. var engine = this.camera.getEngine();
  11577. this._pointerInput = function (p, s) {
  11578. var evt = p.event;
  11579. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11580. try {
  11581. evt.srcElement.setPointerCapture(evt.pointerId);
  11582. }
  11583. catch (e) {
  11584. }
  11585. _this.previousPosition = {
  11586. x: evt.clientX,
  11587. y: evt.clientY
  11588. };
  11589. if (!noPreventDefault) {
  11590. evt.preventDefault();
  11591. }
  11592. }
  11593. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11594. try {
  11595. evt.srcElement.releasePointerCapture(evt.pointerId);
  11596. }
  11597. catch (e) {
  11598. }
  11599. _this.previousPosition = null;
  11600. if (!noPreventDefault) {
  11601. evt.preventDefault();
  11602. }
  11603. }
  11604. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11605. if (!_this.previousPosition && !engine.isPointerLock) {
  11606. return;
  11607. }
  11608. var offsetX;
  11609. var offsetY;
  11610. if (!engine.isPointerLock) {
  11611. offsetX = evt.clientX - _this.previousPosition.x;
  11612. offsetY = evt.clientY - _this.previousPosition.y;
  11613. }
  11614. else {
  11615. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11616. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11617. }
  11618. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11619. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11620. _this.previousPosition = {
  11621. x: evt.clientX,
  11622. y: evt.clientY
  11623. };
  11624. if (!noPreventDefault) {
  11625. evt.preventDefault();
  11626. }
  11627. }
  11628. };
  11629. }
  11630. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11631. };
  11632. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11633. if (this._observer && element) {
  11634. this.camera.getScene().onPointerObservable.remove(this._observer);
  11635. this._observer = null;
  11636. this.previousPosition = null;
  11637. }
  11638. };
  11639. FreeCameraMouseInput.prototype.getTypeName = function () {
  11640. return "FreeCameraMouseInput";
  11641. };
  11642. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11643. return "mouse";
  11644. };
  11645. __decorate([
  11646. BABYLON.serialize()
  11647. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11648. return FreeCameraMouseInput;
  11649. })();
  11650. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11651. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11652. })(BABYLON || (BABYLON = {}));
  11653. var BABYLON;
  11654. (function (BABYLON) {
  11655. var FreeCameraKeyboardMoveInput = (function () {
  11656. function FreeCameraKeyboardMoveInput() {
  11657. this._keys = [];
  11658. this.keysUp = [38];
  11659. this.keysDown = [40];
  11660. this.keysLeft = [37];
  11661. this.keysRight = [39];
  11662. }
  11663. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11664. var _this = this;
  11665. if (!this._onKeyDown) {
  11666. this._onKeyDown = function (evt) {
  11667. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11668. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11669. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11670. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11671. var index = _this._keys.indexOf(evt.keyCode);
  11672. if (index === -1) {
  11673. _this._keys.push(evt.keyCode);
  11674. }
  11675. if (!noPreventDefault) {
  11676. evt.preventDefault();
  11677. }
  11678. }
  11679. };
  11680. this._onKeyUp = function (evt) {
  11681. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11682. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11683. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11684. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11685. var index = _this._keys.indexOf(evt.keyCode);
  11686. if (index >= 0) {
  11687. _this._keys.splice(index, 1);
  11688. }
  11689. if (!noPreventDefault) {
  11690. evt.preventDefault();
  11691. }
  11692. }
  11693. };
  11694. BABYLON.Tools.RegisterTopRootEvents([
  11695. { name: "keydown", handler: this._onKeyDown },
  11696. { name: "keyup", handler: this._onKeyUp },
  11697. { name: "blur", handler: this._onLostFocus }
  11698. ]);
  11699. }
  11700. };
  11701. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11702. if (this._onKeyDown) {
  11703. BABYLON.Tools.UnregisterTopRootEvents([
  11704. { name: "keydown", handler: this._onKeyDown },
  11705. { name: "keyup", handler: this._onKeyUp },
  11706. { name: "blur", handler: this._onLostFocus }
  11707. ]);
  11708. this._keys = [];
  11709. this._onKeyDown = null;
  11710. this._onKeyUp = null;
  11711. }
  11712. };
  11713. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11714. if (this._onKeyDown) {
  11715. var camera = this.camera;
  11716. // Keyboard
  11717. for (var index = 0; index < this._keys.length; index++) {
  11718. var keyCode = this._keys[index];
  11719. var speed = camera._computeLocalCameraSpeed();
  11720. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11721. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11722. }
  11723. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11724. camera._localDirection.copyFromFloats(0, 0, speed);
  11725. }
  11726. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11727. camera._localDirection.copyFromFloats(speed, 0, 0);
  11728. }
  11729. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11730. camera._localDirection.copyFromFloats(0, 0, -speed);
  11731. }
  11732. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11733. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11734. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11735. }
  11736. }
  11737. };
  11738. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11739. return "FreeCameraKeyboardMoveInput";
  11740. };
  11741. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11742. this._keys = [];
  11743. };
  11744. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11745. return "keyboard";
  11746. };
  11747. __decorate([
  11748. BABYLON.serialize()
  11749. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11750. __decorate([
  11751. BABYLON.serialize()
  11752. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11753. __decorate([
  11754. BABYLON.serialize()
  11755. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11756. __decorate([
  11757. BABYLON.serialize()
  11758. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11759. return FreeCameraKeyboardMoveInput;
  11760. })();
  11761. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11762. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11763. })(BABYLON || (BABYLON = {}));
  11764. var BABYLON;
  11765. (function (BABYLON) {
  11766. var FreeCameraTouchInput = (function () {
  11767. function FreeCameraTouchInput() {
  11768. this._offsetX = null;
  11769. this._offsetY = null;
  11770. this._pointerCount = 0;
  11771. this._pointerPressed = [];
  11772. this.touchAngularSensibility = 200000.0;
  11773. this.touchMoveSensibility = 250.0;
  11774. }
  11775. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11776. var _this = this;
  11777. var previousPosition;
  11778. if (this._pointerInput === undefined) {
  11779. this._onLostFocus = function (evt) {
  11780. _this._offsetX = null;
  11781. _this._offsetY = null;
  11782. };
  11783. this._pointerInput = function (p, s) {
  11784. var evt = p.event;
  11785. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11786. if (evt.pointerType === "mouse") {
  11787. return;
  11788. }
  11789. if (!noPreventDefault) {
  11790. evt.preventDefault();
  11791. }
  11792. // evt.srcElement.setPointerCapture(evt.pointerId);
  11793. _this._pointerPressed.push(evt.pointerId);
  11794. if (_this._pointerPressed.length !== 1) {
  11795. return;
  11796. }
  11797. previousPosition = {
  11798. x: evt.clientX,
  11799. y: evt.clientY
  11800. };
  11801. }
  11802. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11803. if (evt.pointerType === "mouse") {
  11804. return;
  11805. }
  11806. if (!noPreventDefault) {
  11807. evt.preventDefault();
  11808. }
  11809. // evt.srcElement.releasePointerCapture(evt.pointerId);
  11810. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11811. if (index === -1) {
  11812. return;
  11813. }
  11814. _this._pointerPressed.splice(index, 1);
  11815. if (index != 0) {
  11816. return;
  11817. }
  11818. previousPosition = null;
  11819. _this._offsetX = null;
  11820. _this._offsetY = null;
  11821. }
  11822. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11823. if (evt.pointerType === "mouse") {
  11824. return;
  11825. }
  11826. if (!noPreventDefault) {
  11827. evt.preventDefault();
  11828. }
  11829. if (!previousPosition) {
  11830. return;
  11831. }
  11832. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11833. if (index != 0) {
  11834. return;
  11835. }
  11836. _this._offsetX = evt.clientX - previousPosition.x;
  11837. _this._offsetY = -(evt.clientY - previousPosition.y);
  11838. }
  11839. };
  11840. }
  11841. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11842. element.addEventListener("blur", this._onLostFocus);
  11843. };
  11844. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11845. if (this._pointerInput && element) {
  11846. this.camera.getScene().onPointerObservable.remove(this._observer);
  11847. this._observer = null;
  11848. element.removeEventListener("blur", this._onLostFocus);
  11849. this._onLostFocus = null;
  11850. this._pointerPressed = [];
  11851. this._offsetX = null;
  11852. this._offsetY = null;
  11853. this._pointerCount = 0;
  11854. }
  11855. };
  11856. FreeCameraTouchInput.prototype.checkInputs = function () {
  11857. if (this._offsetX) {
  11858. var camera = this.camera;
  11859. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11860. if (this._pointerPressed.length > 1) {
  11861. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11862. }
  11863. else {
  11864. var speed = camera._computeLocalCameraSpeed();
  11865. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11866. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11867. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11868. }
  11869. }
  11870. };
  11871. FreeCameraTouchInput.prototype.getTypeName = function () {
  11872. return "FreeCameraTouchInput";
  11873. };
  11874. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11875. return "touch";
  11876. };
  11877. __decorate([
  11878. BABYLON.serialize()
  11879. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11880. __decorate([
  11881. BABYLON.serialize()
  11882. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11883. return FreeCameraTouchInput;
  11884. })();
  11885. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11886. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11887. })(BABYLON || (BABYLON = {}));
  11888. var BABYLON;
  11889. (function (BABYLON) {
  11890. var FreeCameraDeviceOrientationInput = (function () {
  11891. function FreeCameraDeviceOrientationInput() {
  11892. this._offsetX = null;
  11893. this._offsetY = null;
  11894. this._orientationGamma = 0;
  11895. this._orientationBeta = 0;
  11896. this._initialOrientationGamma = 0;
  11897. this._initialOrientationBeta = 0;
  11898. this.angularSensibility = 10000.0;
  11899. this.moveSensibility = 50.0;
  11900. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  11901. this._orientationChanged = this.orientationChanged.bind(this);
  11902. }
  11903. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11904. window.addEventListener("resize", this._resetOrientationGamma, false);
  11905. window.addEventListener("deviceorientation", this._orientationChanged);
  11906. };
  11907. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  11908. this._initialOrientationGamma = null;
  11909. };
  11910. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  11911. if (!this._initialOrientationGamma) {
  11912. this._initialOrientationGamma = evt.gamma;
  11913. this._initialOrientationBeta = evt.beta;
  11914. }
  11915. this._orientationGamma = evt.gamma;
  11916. this._orientationBeta = evt.beta;
  11917. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  11918. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  11919. };
  11920. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  11921. window.removeEventListener("resize", this._resetOrientationGamma);
  11922. window.removeEventListener("deviceorientation", this._orientationChanged);
  11923. this._orientationGamma = 0;
  11924. this._orientationBeta = 0;
  11925. this._initialOrientationGamma = 0;
  11926. this._initialOrientationBeta = 0;
  11927. this._offsetX = null;
  11928. this._offsetY = null;
  11929. };
  11930. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  11931. if (!this._offsetX) {
  11932. return;
  11933. }
  11934. var camera = this.camera;
  11935. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11936. var speed = camera._computeLocalCameraSpeed();
  11937. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11938. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11939. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11940. };
  11941. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  11942. return "FreeCameraDeviceOrientationInput";
  11943. };
  11944. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  11945. return "deviceOrientation";
  11946. };
  11947. __decorate([
  11948. BABYLON.serialize()
  11949. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  11950. __decorate([
  11951. BABYLON.serialize()
  11952. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  11953. return FreeCameraDeviceOrientationInput;
  11954. })();
  11955. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  11956. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  11957. })(BABYLON || (BABYLON = {}));
  11958. var BABYLON;
  11959. (function (BABYLON) {
  11960. var FreeCameraVRDeviceOrientationInput = (function () {
  11961. function FreeCameraVRDeviceOrientationInput() {
  11962. this.alphaCorrection = 1;
  11963. this.betaCorrection = 1;
  11964. this.gammaCorrection = 1;
  11965. this._alpha = 0;
  11966. this._beta = 0;
  11967. this._gamma = 0;
  11968. this._dirty = false;
  11969. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  11970. }
  11971. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11972. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  11973. };
  11974. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  11975. var camera = this.camera;
  11976. this._alpha = +evt.alpha | 0;
  11977. this._beta = +evt.beta | 0;
  11978. this._gamma = +evt.gamma | 0;
  11979. this._dirty = true;
  11980. };
  11981. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  11982. if (this._dirty) {
  11983. this._dirty = false;
  11984. var rotationX = this._gamma;
  11985. if (rotationX < 0) {
  11986. rotationX = 90 + rotationX;
  11987. }
  11988. else {
  11989. // Incline it in the correct angle.
  11990. rotationX = 270 - rotationX;
  11991. }
  11992. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  11993. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  11994. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  11995. }
  11996. };
  11997. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  11998. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  11999. };
  12000. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12001. return "FreeCameraVRDeviceOrientationInput";
  12002. };
  12003. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12004. return "VRDeviceOrientation";
  12005. };
  12006. return FreeCameraVRDeviceOrientationInput;
  12007. })();
  12008. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12009. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12010. })(BABYLON || (BABYLON = {}));
  12011. var BABYLON;
  12012. (function (BABYLON) {
  12013. var FreeCameraGamepadInput = (function () {
  12014. function FreeCameraGamepadInput() {
  12015. this.gamepadAngularSensibility = 200;
  12016. this.gamepadMoveSensibility = 40;
  12017. }
  12018. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12019. var _this = this;
  12020. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12021. };
  12022. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12023. if (this._gamepads) {
  12024. this._gamepads.dispose();
  12025. }
  12026. this.gamepad = null;
  12027. };
  12028. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12029. if (this.gamepad) {
  12030. var camera = this.camera;
  12031. var LSValues = this.gamepad.leftStick;
  12032. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12033. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12034. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12035. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12036. var RSValues = this.gamepad.rightStick;
  12037. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12038. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12039. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12040. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12041. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12042. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12043. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12044. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12045. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12046. }
  12047. };
  12048. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12049. // Only the first gamepad can control the camera
  12050. if (gamepad.index === 0) {
  12051. this.gamepad = gamepad;
  12052. }
  12053. };
  12054. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12055. return "FreeCameraGamepadInput";
  12056. };
  12057. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12058. return "gamepad";
  12059. };
  12060. __decorate([
  12061. BABYLON.serialize()
  12062. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12063. __decorate([
  12064. BABYLON.serialize()
  12065. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12066. return FreeCameraGamepadInput;
  12067. })();
  12068. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12069. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12070. })(BABYLON || (BABYLON = {}));
  12071. var BABYLON;
  12072. (function (BABYLON) {
  12073. var FreeCameraVirtualJoystickInput = (function () {
  12074. function FreeCameraVirtualJoystickInput() {
  12075. }
  12076. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  12077. return this._leftjoystick;
  12078. };
  12079. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  12080. return this._rightjoystick;
  12081. };
  12082. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  12083. if (this._leftjoystick) {
  12084. var camera = this.camera;
  12085. var speed = camera._computeLocalCameraSpeed() * 50;
  12086. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12087. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  12088. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12089. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  12090. if (!this._leftjoystick.pressed) {
  12091. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  12092. }
  12093. if (!this._rightjoystick.pressed) {
  12094. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  12095. }
  12096. }
  12097. };
  12098. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  12099. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  12100. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  12101. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  12102. this._leftjoystick.setJoystickSensibility(0.15);
  12103. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  12104. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  12105. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  12106. this._rightjoystick.reverseUpDown = true;
  12107. this._rightjoystick.setJoystickSensibility(0.05);
  12108. this._rightjoystick.setJoystickColor("yellow");
  12109. };
  12110. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  12111. this._leftjoystick.releaseCanvas();
  12112. this._rightjoystick.releaseCanvas();
  12113. };
  12114. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  12115. return "FreeCameraVirtualJoystickInput";
  12116. };
  12117. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  12118. return "virtualJoystick";
  12119. };
  12120. return FreeCameraVirtualJoystickInput;
  12121. })();
  12122. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  12123. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  12124. })(BABYLON || (BABYLON = {}));
  12125. var BABYLON;
  12126. (function (BABYLON) {
  12127. var ArcRotateCameraKeyboardMoveInput = (function () {
  12128. function ArcRotateCameraKeyboardMoveInput() {
  12129. this._keys = [];
  12130. this.keysUp = [38];
  12131. this.keysDown = [40];
  12132. this.keysLeft = [37];
  12133. this.keysRight = [39];
  12134. }
  12135. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12136. var _this = this;
  12137. this._onKeyDown = function (evt) {
  12138. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12139. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12140. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12141. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12142. var index = _this._keys.indexOf(evt.keyCode);
  12143. if (index === -1) {
  12144. _this._keys.push(evt.keyCode);
  12145. }
  12146. if (evt.preventDefault) {
  12147. if (!noPreventDefault) {
  12148. evt.preventDefault();
  12149. }
  12150. }
  12151. }
  12152. };
  12153. this._onKeyUp = function (evt) {
  12154. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12155. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12156. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12157. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12158. var index = _this._keys.indexOf(evt.keyCode);
  12159. if (index >= 0) {
  12160. _this._keys.splice(index, 1);
  12161. }
  12162. if (evt.preventDefault) {
  12163. if (!noPreventDefault) {
  12164. evt.preventDefault();
  12165. }
  12166. }
  12167. }
  12168. };
  12169. this._onLostFocus = function () {
  12170. _this._keys = [];
  12171. };
  12172. BABYLON.Tools.RegisterTopRootEvents([
  12173. { name: "keydown", handler: this._onKeyDown },
  12174. { name: "keyup", handler: this._onKeyUp },
  12175. { name: "blur", handler: this._onLostFocus }
  12176. ]);
  12177. };
  12178. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12179. BABYLON.Tools.UnregisterTopRootEvents([
  12180. { name: "keydown", handler: this._onKeyDown },
  12181. { name: "keyup", handler: this._onKeyUp },
  12182. { name: "blur", handler: this._onLostFocus }
  12183. ]);
  12184. this._keys = [];
  12185. this._onKeyDown = null;
  12186. this._onKeyUp = null;
  12187. this._onLostFocus = null;
  12188. };
  12189. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12190. if (this._onKeyDown) {
  12191. var camera = this.camera;
  12192. for (var index = 0; index < this._keys.length; index++) {
  12193. var keyCode = this._keys[index];
  12194. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12195. camera.inertialAlphaOffset -= 0.01;
  12196. }
  12197. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12198. camera.inertialBetaOffset -= 0.01;
  12199. }
  12200. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12201. camera.inertialAlphaOffset += 0.01;
  12202. }
  12203. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12204. camera.inertialBetaOffset += 0.01;
  12205. }
  12206. }
  12207. }
  12208. };
  12209. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12210. return "ArcRotateCameraKeyboardMoveInput";
  12211. };
  12212. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12213. return "keyboard";
  12214. };
  12215. __decorate([
  12216. BABYLON.serialize()
  12217. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12218. __decorate([
  12219. BABYLON.serialize()
  12220. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12221. __decorate([
  12222. BABYLON.serialize()
  12223. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12224. __decorate([
  12225. BABYLON.serialize()
  12226. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12227. return ArcRotateCameraKeyboardMoveInput;
  12228. })();
  12229. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12230. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12231. })(BABYLON || (BABYLON = {}));
  12232. var BABYLON;
  12233. (function (BABYLON) {
  12234. var ArcRotateCameraMouseWheelInput = (function () {
  12235. function ArcRotateCameraMouseWheelInput() {
  12236. this.wheelPrecision = 3.0;
  12237. }
  12238. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12239. var _this = this;
  12240. this._wheel = function (p, s) {
  12241. //sanity check - this should be a PointerWheel event.
  12242. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  12243. return;
  12244. var event = p.event;
  12245. var delta = 0;
  12246. if (event.wheelDelta) {
  12247. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12248. }
  12249. else if (event.detail) {
  12250. delta = -event.detail / _this.wheelPrecision;
  12251. }
  12252. if (delta)
  12253. _this.camera.inertialRadiusOffset += delta;
  12254. if (event.preventDefault) {
  12255. if (!noPreventDefault) {
  12256. event.preventDefault();
  12257. }
  12258. }
  12259. };
  12260. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  12261. };
  12262. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12263. if (this._observer && element) {
  12264. this.camera.getScene().onPointerObservable.remove(this._observer);
  12265. this._observer = null;
  12266. this._wheel = null;
  12267. }
  12268. };
  12269. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12270. return "ArcRotateCameraMouseWheelInput";
  12271. };
  12272. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12273. return "mousewheel";
  12274. };
  12275. __decorate([
  12276. BABYLON.serialize()
  12277. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12278. return ArcRotateCameraMouseWheelInput;
  12279. })();
  12280. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12281. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12282. })(BABYLON || (BABYLON = {}));
  12283. var BABYLON;
  12284. (function (BABYLON) {
  12285. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12286. var ArcRotateCameraPointersInput = (function () {
  12287. function ArcRotateCameraPointersInput() {
  12288. this.angularSensibilityX = 1000.0;
  12289. this.angularSensibilityY = 1000.0;
  12290. this.pinchPrecision = 6.0;
  12291. this.panningSensibility = 50.0;
  12292. this._isRightClick = false;
  12293. this._isCtrlPushed = false;
  12294. this.pinchInwards = true;
  12295. }
  12296. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12297. var _this = this;
  12298. var engine = this.camera.getEngine();
  12299. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12300. var pointers = new BABYLON.SmartCollection();
  12301. var previousPinchDistance = 0;
  12302. this._pointerInput = function (p, s) {
  12303. var evt = p.event;
  12304. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12305. try {
  12306. evt.srcElement.setPointerCapture(evt.pointerId);
  12307. }
  12308. catch (e) {
  12309. }
  12310. // Manage panning with right click
  12311. _this._isRightClick = evt.button === 2;
  12312. // manage pointers
  12313. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  12314. cacheSoloPointer = pointers.item(evt.pointerId);
  12315. if (!noPreventDefault) {
  12316. evt.preventDefault();
  12317. }
  12318. }
  12319. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12320. try {
  12321. evt.srcElement.releasePointerCapture(evt.pointerId);
  12322. }
  12323. catch (e) {
  12324. }
  12325. cacheSoloPointer = null;
  12326. previousPinchDistance = 0;
  12327. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12328. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12329. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12330. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12331. pointers.empty();
  12332. if (!noPreventDefault) {
  12333. evt.preventDefault();
  12334. }
  12335. }
  12336. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12337. if (!noPreventDefault) {
  12338. evt.preventDefault();
  12339. }
  12340. switch (pointers.count) {
  12341. case 1:
  12342. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) || (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12343. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12344. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12345. }
  12346. else {
  12347. var offsetX = evt.clientX - cacheSoloPointer.x;
  12348. var offsetY = evt.clientY - cacheSoloPointer.y;
  12349. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12350. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12351. }
  12352. cacheSoloPointer.x = evt.clientX;
  12353. cacheSoloPointer.y = evt.clientY;
  12354. break;
  12355. case 2:
  12356. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12357. pointers.item(evt.pointerId).x = evt.clientX;
  12358. pointers.item(evt.pointerId).y = evt.clientY;
  12359. var direction = _this.pinchInwards ? 1 : -1;
  12360. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  12361. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  12362. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12363. if (previousPinchDistance === 0) {
  12364. previousPinchDistance = pinchSquaredDistance;
  12365. return;
  12366. }
  12367. if (pinchSquaredDistance !== previousPinchDistance) {
  12368. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  12369. previousPinchDistance = pinchSquaredDistance;
  12370. }
  12371. break;
  12372. default:
  12373. if (pointers.item(evt.pointerId)) {
  12374. pointers.item(evt.pointerId).x = evt.clientX;
  12375. pointers.item(evt.pointerId).y = evt.clientY;
  12376. }
  12377. }
  12378. }
  12379. };
  12380. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12381. this._onContextMenu = function (evt) {
  12382. evt.preventDefault();
  12383. };
  12384. if (!this.camera._useCtrlForPanning) {
  12385. element.addEventListener("contextmenu", this._onContextMenu, false);
  12386. }
  12387. this._onLostFocus = function () {
  12388. //this._keys = [];
  12389. pointers.empty();
  12390. previousPinchDistance = 0;
  12391. cacheSoloPointer = null;
  12392. };
  12393. this._onKeyDown = function (evt) {
  12394. _this._isCtrlPushed = evt.ctrlKey;
  12395. };
  12396. this._onKeyUp = function (evt) {
  12397. _this._isCtrlPushed = evt.ctrlKey;
  12398. };
  12399. this._onMouseMove = function (evt) {
  12400. if (!engine.isPointerLock) {
  12401. return;
  12402. }
  12403. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12404. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12405. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12406. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12407. if (!noPreventDefault) {
  12408. evt.preventDefault();
  12409. }
  12410. };
  12411. this._onGestureStart = function (e) {
  12412. if (window.MSGesture === undefined) {
  12413. return;
  12414. }
  12415. if (!_this._MSGestureHandler) {
  12416. _this._MSGestureHandler = new MSGesture();
  12417. _this._MSGestureHandler.target = element;
  12418. }
  12419. _this._MSGestureHandler.addPointer(e.pointerId);
  12420. };
  12421. this._onGesture = function (e) {
  12422. _this.camera.radius *= e.scale;
  12423. if (e.preventDefault) {
  12424. if (!noPreventDefault) {
  12425. e.stopPropagation();
  12426. e.preventDefault();
  12427. }
  12428. }
  12429. };
  12430. element.addEventListener("mousemove", this._onMouseMove, false);
  12431. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12432. element.addEventListener("MSGestureChange", this._onGesture, false);
  12433. BABYLON.Tools.RegisterTopRootEvents([
  12434. { name: "keydown", handler: this._onKeyDown },
  12435. { name: "keyup", handler: this._onKeyUp },
  12436. { name: "blur", handler: this._onLostFocus }
  12437. ]);
  12438. };
  12439. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12440. if (element && this._observer) {
  12441. this.camera.getScene().onPointerObservable.remove(this._observer);
  12442. this._observer = null;
  12443. element.removeEventListener("contextmenu", this._onContextMenu);
  12444. element.removeEventListener("mousemove", this._onMouseMove);
  12445. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12446. element.removeEventListener("MSGestureChange", this._onGesture);
  12447. this._isRightClick = false;
  12448. this._isCtrlPushed = false;
  12449. this.pinchInwards = true;
  12450. this._onKeyDown = null;
  12451. this._onKeyUp = null;
  12452. this._onMouseMove = null;
  12453. this._onGestureStart = null;
  12454. this._onGesture = null;
  12455. this._MSGestureHandler = null;
  12456. this._onLostFocus = null;
  12457. this._onContextMenu = null;
  12458. }
  12459. BABYLON.Tools.UnregisterTopRootEvents([
  12460. { name: "keydown", handler: this._onKeyDown },
  12461. { name: "keyup", handler: this._onKeyUp },
  12462. { name: "blur", handler: this._onLostFocus }
  12463. ]);
  12464. };
  12465. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12466. return "ArcRotateCameraPointersInput";
  12467. };
  12468. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12469. return "pointers";
  12470. };
  12471. __decorate([
  12472. BABYLON.serialize()
  12473. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12474. __decorate([
  12475. BABYLON.serialize()
  12476. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12477. __decorate([
  12478. BABYLON.serialize()
  12479. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12480. __decorate([
  12481. BABYLON.serialize()
  12482. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12483. return ArcRotateCameraPointersInput;
  12484. })();
  12485. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12486. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12487. })(BABYLON || (BABYLON = {}));
  12488. var BABYLON;
  12489. (function (BABYLON) {
  12490. var ArcRotateCameraGamepadInput = (function () {
  12491. function ArcRotateCameraGamepadInput() {
  12492. this.gamepadRotationSensibility = 80;
  12493. this.gamepadMoveSensibility = 40;
  12494. }
  12495. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12496. var _this = this;
  12497. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12498. };
  12499. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12500. if (this._gamepads) {
  12501. this._gamepads.dispose();
  12502. }
  12503. this.gamepad = null;
  12504. };
  12505. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12506. if (this.gamepad) {
  12507. var camera = this.camera;
  12508. var RSValues = this.gamepad.rightStick;
  12509. if (RSValues.x != 0) {
  12510. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12511. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12512. camera.inertialAlphaOffset += normalizedRX;
  12513. }
  12514. }
  12515. if (RSValues.y != 0) {
  12516. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12517. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12518. camera.inertialBetaOffset += normalizedRY;
  12519. }
  12520. }
  12521. var LSValues = this.gamepad.leftStick;
  12522. if (LSValues.y != 0) {
  12523. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12524. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12525. this.camera.inertialRadiusOffset -= normalizedLY;
  12526. }
  12527. }
  12528. }
  12529. };
  12530. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12531. // Only the first gamepad can control the camera
  12532. if (gamepad.index === 0) {
  12533. this.gamepad = gamepad;
  12534. }
  12535. };
  12536. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12537. return "ArcRotateCameraGamepadInput";
  12538. };
  12539. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12540. return "gamepad";
  12541. };
  12542. __decorate([
  12543. BABYLON.serialize()
  12544. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12545. __decorate([
  12546. BABYLON.serialize()
  12547. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12548. return ArcRotateCameraGamepadInput;
  12549. })();
  12550. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12551. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12552. })(BABYLON || (BABYLON = {}));
  12553. var BABYLON;
  12554. (function (BABYLON) {
  12555. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  12556. function ArcRotateCameraVRDeviceOrientationInput() {
  12557. this.alphaCorrection = 1;
  12558. this.betaCorrection = 1;
  12559. this.gammaCorrection = 1;
  12560. this._alpha = 0;
  12561. this._beta = 0;
  12562. this._gamma = 0;
  12563. this._dirty = false;
  12564. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12565. }
  12566. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12567. this.camera.attachControl(element, noPreventDefault);
  12568. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12569. };
  12570. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12571. var camera = this.camera;
  12572. this._alpha = +evt.alpha | 0;
  12573. this._beta = +evt.beta | 0;
  12574. this._gamma = +evt.gamma | 0;
  12575. this._dirty = true;
  12576. };
  12577. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12578. if (this._dirty) {
  12579. this._dirty = false;
  12580. if (this._gamma < 0) {
  12581. this._gamma = 180 + this._gamma;
  12582. }
  12583. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  12584. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  12585. }
  12586. };
  12587. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12588. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12589. };
  12590. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12591. return "ArcRotateCameraVRDeviceOrientationInput";
  12592. };
  12593. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12594. return "VRDeviceOrientation";
  12595. };
  12596. return ArcRotateCameraVRDeviceOrientationInput;
  12597. })();
  12598. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  12599. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  12600. })(BABYLON || (BABYLON = {}));
  12601. var BABYLON;
  12602. (function (BABYLON) {
  12603. var TargetCamera = (function (_super) {
  12604. __extends(TargetCamera, _super);
  12605. function TargetCamera(name, position, scene) {
  12606. _super.call(this, name, position, scene);
  12607. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12608. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12609. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12610. this.speed = 2.0;
  12611. this.noRotationConstraint = false;
  12612. this.lockedTarget = null;
  12613. this._currentTarget = BABYLON.Vector3.Zero();
  12614. this._viewMatrix = BABYLON.Matrix.Zero();
  12615. this._camMatrix = BABYLON.Matrix.Zero();
  12616. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12617. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12618. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12619. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12620. this._lookAtTemp = BABYLON.Matrix.Zero();
  12621. this._tempMatrix = BABYLON.Matrix.Zero();
  12622. }
  12623. TargetCamera.prototype.getFrontPosition = function (distance) {
  12624. var direction = this.getTarget().subtract(this.position);
  12625. direction.normalize();
  12626. direction.scaleInPlace(distance);
  12627. return this.globalPosition.add(direction);
  12628. };
  12629. TargetCamera.prototype._getLockedTargetPosition = function () {
  12630. if (!this.lockedTarget) {
  12631. return null;
  12632. }
  12633. return this.lockedTarget.position || this.lockedTarget;
  12634. };
  12635. // Cache
  12636. TargetCamera.prototype._initCache = function () {
  12637. _super.prototype._initCache.call(this);
  12638. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12639. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12640. };
  12641. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12642. if (!ignoreParentClass) {
  12643. _super.prototype._updateCache.call(this);
  12644. }
  12645. var lockedTargetPosition = this._getLockedTargetPosition();
  12646. if (!lockedTargetPosition) {
  12647. this._cache.lockedTarget = null;
  12648. }
  12649. else {
  12650. if (!this._cache.lockedTarget) {
  12651. this._cache.lockedTarget = lockedTargetPosition.clone();
  12652. }
  12653. else {
  12654. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12655. }
  12656. }
  12657. this._cache.rotation.copyFrom(this.rotation);
  12658. };
  12659. // Synchronized
  12660. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12661. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12662. return false;
  12663. }
  12664. var lockedTargetPosition = this._getLockedTargetPosition();
  12665. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12666. && this._cache.rotation.equals(this.rotation);
  12667. };
  12668. // Methods
  12669. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12670. var engine = this.getEngine();
  12671. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12672. };
  12673. // Target
  12674. TargetCamera.prototype.setTarget = function (target) {
  12675. this.upVector.normalize();
  12676. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12677. this._camMatrix.invert();
  12678. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12679. var vDir = target.subtract(this.position);
  12680. if (vDir.x >= 0.0) {
  12681. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12682. }
  12683. else {
  12684. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12685. }
  12686. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12687. if (isNaN(this.rotation.x)) {
  12688. this.rotation.x = 0;
  12689. }
  12690. if (isNaN(this.rotation.y)) {
  12691. this.rotation.y = 0;
  12692. }
  12693. if (isNaN(this.rotation.z)) {
  12694. this.rotation.z = 0;
  12695. }
  12696. };
  12697. TargetCamera.prototype.getTarget = function () {
  12698. return this._currentTarget;
  12699. };
  12700. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12701. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12702. };
  12703. TargetCamera.prototype._updatePosition = function () {
  12704. this.position.addInPlace(this.cameraDirection);
  12705. };
  12706. TargetCamera.prototype._checkInputs = function () {
  12707. var needToMove = this._decideIfNeedsToMove();
  12708. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12709. // Move
  12710. if (needToMove) {
  12711. this._updatePosition();
  12712. }
  12713. // Rotate
  12714. if (needToRotate) {
  12715. this.rotation.x += this.cameraRotation.x;
  12716. this.rotation.y += this.cameraRotation.y;
  12717. if (!this.noRotationConstraint) {
  12718. var limit = (Math.PI / 2) * 0.95;
  12719. if (this.rotation.x > limit)
  12720. this.rotation.x = limit;
  12721. if (this.rotation.x < -limit)
  12722. this.rotation.x = -limit;
  12723. }
  12724. }
  12725. // Inertia
  12726. if (needToMove) {
  12727. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12728. this.cameraDirection.x = 0;
  12729. }
  12730. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12731. this.cameraDirection.y = 0;
  12732. }
  12733. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12734. this.cameraDirection.z = 0;
  12735. }
  12736. this.cameraDirection.scaleInPlace(this.inertia);
  12737. }
  12738. if (needToRotate) {
  12739. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12740. this.cameraRotation.x = 0;
  12741. }
  12742. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12743. this.cameraRotation.y = 0;
  12744. }
  12745. this.cameraRotation.scaleInPlace(this.inertia);
  12746. }
  12747. _super.prototype._checkInputs.call(this);
  12748. };
  12749. TargetCamera.prototype._getViewMatrix = function () {
  12750. if (!this.lockedTarget) {
  12751. // Compute
  12752. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12753. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12754. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12755. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12756. this._lookAtTemp.invert();
  12757. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12758. }
  12759. else {
  12760. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12761. }
  12762. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12763. // Computing target and final matrix
  12764. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12765. }
  12766. else {
  12767. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12768. }
  12769. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12770. return this._viewMatrix;
  12771. };
  12772. TargetCamera.prototype._getVRViewMatrix = function () {
  12773. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12774. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12775. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12776. // Computing target and final matrix
  12777. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12778. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12779. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12780. return this._viewMatrix;
  12781. };
  12782. /**
  12783. * @override
  12784. * Override Camera.createRigCamera
  12785. */
  12786. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12787. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12788. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12789. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12790. rigCamera._cameraRigParams = {};
  12791. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12792. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12793. }
  12794. return rigCamera;
  12795. }
  12796. return null;
  12797. };
  12798. /**
  12799. * @override
  12800. * Override Camera._updateRigCameras
  12801. */
  12802. TargetCamera.prototype._updateRigCameras = function () {
  12803. switch (this.cameraRigMode) {
  12804. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12805. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12806. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12807. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12808. case BABYLON.Camera.RIG_MODE_VR:
  12809. var camLeft = this._rigCameras[0];
  12810. var camRight = this._rigCameras[1];
  12811. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12812. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12813. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12814. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12815. camLeft.position.copyFrom(this.position);
  12816. camRight.position.copyFrom(this.position);
  12817. }
  12818. else {
  12819. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12820. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12821. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12822. camLeft.setTarget(this.getTarget());
  12823. camRight.setTarget(this.getTarget());
  12824. }
  12825. break;
  12826. }
  12827. _super.prototype._updateRigCameras.call(this);
  12828. };
  12829. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12830. if (!this._rigCamTransformMatrix) {
  12831. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12832. }
  12833. var target = this.getTarget();
  12834. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12835. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12836. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12837. };
  12838. TargetCamera.prototype.getTypeName = function () {
  12839. return "TargetCamera";
  12840. };
  12841. __decorate([
  12842. BABYLON.serializeAsVector3()
  12843. ], TargetCamera.prototype, "rotation", void 0);
  12844. __decorate([
  12845. BABYLON.serialize()
  12846. ], TargetCamera.prototype, "speed", void 0);
  12847. __decorate([
  12848. BABYLON.serializeAsMeshReference("lockedTargetId")
  12849. ], TargetCamera.prototype, "lockedTarget", void 0);
  12850. return TargetCamera;
  12851. })(BABYLON.Camera);
  12852. BABYLON.TargetCamera = TargetCamera;
  12853. })(BABYLON || (BABYLON = {}));
  12854. var BABYLON;
  12855. (function (BABYLON) {
  12856. var FreeCamera = (function (_super) {
  12857. __extends(FreeCamera, _super);
  12858. function FreeCamera(name, position, scene) {
  12859. var _this = this;
  12860. _super.call(this, name, position, scene);
  12861. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12862. this.checkCollisions = false;
  12863. this.applyGravity = false;
  12864. this._collider = new BABYLON.Collider();
  12865. this._needMoveForGravity = false;
  12866. this._oldPosition = BABYLON.Vector3.Zero();
  12867. this._diffPosition = BABYLON.Vector3.Zero();
  12868. this._newPosition = BABYLON.Vector3.Zero();
  12869. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12870. if (collidedMesh === void 0) { collidedMesh = null; }
  12871. //TODO move this to the collision coordinator!
  12872. if (_this.getScene().workerCollisions)
  12873. newPosition.multiplyInPlace(_this._collider.radius);
  12874. var updatePosition = function (newPos) {
  12875. _this._newPosition.copyFrom(newPos);
  12876. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12877. var oldPosition = _this.position.clone();
  12878. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12879. _this.position.addInPlace(_this._diffPosition);
  12880. if (_this.onCollide && collidedMesh) {
  12881. _this.onCollide(collidedMesh);
  12882. }
  12883. }
  12884. };
  12885. updatePosition(newPosition);
  12886. };
  12887. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12888. this.inputs.addKeyboard().addMouse();
  12889. }
  12890. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  12891. //-- begin properties for backward compatibility for inputs
  12892. get: function () {
  12893. var mouse = this.inputs.attached["mouse"];
  12894. if (mouse)
  12895. return mouse.angularSensibility;
  12896. },
  12897. set: function (value) {
  12898. var mouse = this.inputs.attached["mouse"];
  12899. if (mouse)
  12900. mouse.angularSensibility = value;
  12901. },
  12902. enumerable: true,
  12903. configurable: true
  12904. });
  12905. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  12906. get: function () {
  12907. var keyboard = this.inputs.attached["keyboard"];
  12908. if (keyboard)
  12909. return keyboard.keysUp;
  12910. },
  12911. set: function (value) {
  12912. var keyboard = this.inputs.attached["keyboard"];
  12913. if (keyboard)
  12914. keyboard.keysUp = value;
  12915. },
  12916. enumerable: true,
  12917. configurable: true
  12918. });
  12919. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  12920. get: function () {
  12921. var keyboard = this.inputs.attached["keyboard"];
  12922. if (keyboard)
  12923. return keyboard.keysDown;
  12924. },
  12925. set: function (value) {
  12926. var keyboard = this.inputs.attached["keyboard"];
  12927. if (keyboard)
  12928. keyboard.keysDown = value;
  12929. },
  12930. enumerable: true,
  12931. configurable: true
  12932. });
  12933. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  12934. get: function () {
  12935. var keyboard = this.inputs.attached["keyboard"];
  12936. if (keyboard)
  12937. return keyboard.keysLeft;
  12938. },
  12939. set: function (value) {
  12940. var keyboard = this.inputs.attached["keyboard"];
  12941. if (keyboard)
  12942. keyboard.keysLeft = value;
  12943. },
  12944. enumerable: true,
  12945. configurable: true
  12946. });
  12947. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  12948. get: function () {
  12949. var keyboard = this.inputs.attached["keyboard"];
  12950. if (keyboard)
  12951. return keyboard.keysRight;
  12952. },
  12953. set: function (value) {
  12954. var keyboard = this.inputs.attached["keyboard"];
  12955. if (keyboard)
  12956. keyboard.keysRight = value;
  12957. },
  12958. enumerable: true,
  12959. configurable: true
  12960. });
  12961. // Controls
  12962. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  12963. this.inputs.attachElement(element, noPreventDefault);
  12964. };
  12965. FreeCamera.prototype.detachControl = function (element) {
  12966. this.inputs.detachElement(element);
  12967. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12968. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12969. };
  12970. FreeCamera.prototype._collideWithWorld = function (velocity) {
  12971. var globalPosition;
  12972. if (this.parent) {
  12973. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  12974. }
  12975. else {
  12976. globalPosition = this.position;
  12977. }
  12978. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  12979. this._collider.radius = this.ellipsoid;
  12980. //no need for clone, as long as gravity is not on.
  12981. var actualVelocity = velocity;
  12982. //add gravity to the velocity to prevent the dual-collision checking
  12983. if (this.applyGravity) {
  12984. //this prevents mending with cameraDirection, a global variable of the free camera class.
  12985. actualVelocity = velocity.add(this.getScene().gravity);
  12986. }
  12987. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12988. };
  12989. FreeCamera.prototype._checkInputs = function () {
  12990. if (!this._localDirection) {
  12991. this._localDirection = BABYLON.Vector3.Zero();
  12992. this._transformedDirection = BABYLON.Vector3.Zero();
  12993. }
  12994. this.inputs.checkInputs();
  12995. _super.prototype._checkInputs.call(this);
  12996. };
  12997. FreeCamera.prototype._decideIfNeedsToMove = function () {
  12998. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12999. };
  13000. FreeCamera.prototype._updatePosition = function () {
  13001. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13002. this._collideWithWorld(this.cameraDirection);
  13003. }
  13004. else {
  13005. this.position.addInPlace(this.cameraDirection);
  13006. }
  13007. };
  13008. FreeCamera.prototype.dispose = function () {
  13009. this.inputs.clear();
  13010. _super.prototype.dispose.call(this);
  13011. };
  13012. FreeCamera.prototype.getTypeName = function () {
  13013. return "FreeCamera";
  13014. };
  13015. __decorate([
  13016. BABYLON.serializeAsVector3()
  13017. ], FreeCamera.prototype, "ellipsoid", void 0);
  13018. __decorate([
  13019. BABYLON.serialize()
  13020. ], FreeCamera.prototype, "checkCollisions", void 0);
  13021. __decorate([
  13022. BABYLON.serialize()
  13023. ], FreeCamera.prototype, "applyGravity", void 0);
  13024. return FreeCamera;
  13025. })(BABYLON.TargetCamera);
  13026. BABYLON.FreeCamera = FreeCamera;
  13027. })(BABYLON || (BABYLON = {}));
  13028. var BABYLON;
  13029. (function (BABYLON) {
  13030. var FreeCameraInputsManager = (function (_super) {
  13031. __extends(FreeCameraInputsManager, _super);
  13032. function FreeCameraInputsManager(camera) {
  13033. _super.call(this, camera);
  13034. }
  13035. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13036. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13037. return this;
  13038. };
  13039. FreeCameraInputsManager.prototype.addMouse = function () {
  13040. this.add(new BABYLON.FreeCameraMouseInput());
  13041. return this;
  13042. };
  13043. FreeCameraInputsManager.prototype.addGamepad = function () {
  13044. this.add(new BABYLON.FreeCameraGamepadInput());
  13045. return this;
  13046. };
  13047. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13048. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13049. return this;
  13050. };
  13051. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13052. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13053. return this;
  13054. };
  13055. FreeCameraInputsManager.prototype.addTouch = function () {
  13056. this.add(new BABYLON.FreeCameraTouchInput());
  13057. return this;
  13058. };
  13059. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13060. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13061. return this;
  13062. };
  13063. return FreeCameraInputsManager;
  13064. })(BABYLON.CameraInputsManager);
  13065. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13066. })(BABYLON || (BABYLON = {}));
  13067. var BABYLON;
  13068. (function (BABYLON) {
  13069. var FollowCamera = (function (_super) {
  13070. __extends(FollowCamera, _super);
  13071. function FollowCamera(name, position, scene, target) {
  13072. _super.call(this, name, position, scene);
  13073. this.radius = 12;
  13074. this.rotationOffset = 0;
  13075. this.heightOffset = 4;
  13076. this.cameraAcceleration = 0.05;
  13077. this.maxCameraSpeed = 20;
  13078. this.target = target;
  13079. }
  13080. FollowCamera.prototype.getRadians = function (degrees) {
  13081. return degrees * Math.PI / 180;
  13082. };
  13083. FollowCamera.prototype.follow = function (cameraTarget) {
  13084. if (!cameraTarget)
  13085. return;
  13086. var yRotation;
  13087. if (cameraTarget.rotationQuaternion) {
  13088. var rotMatrix = new BABYLON.Matrix();
  13089. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13090. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13091. }
  13092. else {
  13093. yRotation = cameraTarget.rotation.y;
  13094. }
  13095. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13096. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13097. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13098. var dx = targetX - this.position.x;
  13099. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13100. var dz = (targetZ) - this.position.z;
  13101. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13102. var vy = dy * this.cameraAcceleration;
  13103. var vz = dz * this.cameraAcceleration * 2;
  13104. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13105. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13106. }
  13107. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13108. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13109. }
  13110. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13111. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13112. }
  13113. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13114. this.setTarget(cameraTarget.position);
  13115. };
  13116. FollowCamera.prototype._checkInputs = function () {
  13117. _super.prototype._checkInputs.call(this);
  13118. this.follow(this.target);
  13119. };
  13120. FollowCamera.prototype.getTypeName = function () {
  13121. return "FollowCamera";
  13122. };
  13123. __decorate([
  13124. BABYLON.serialize()
  13125. ], FollowCamera.prototype, "radius", void 0);
  13126. __decorate([
  13127. BABYLON.serialize()
  13128. ], FollowCamera.prototype, "rotationOffset", void 0);
  13129. __decorate([
  13130. BABYLON.serialize()
  13131. ], FollowCamera.prototype, "heightOffset", void 0);
  13132. __decorate([
  13133. BABYLON.serialize()
  13134. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13135. __decorate([
  13136. BABYLON.serialize()
  13137. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13138. __decorate([
  13139. BABYLON.serializeAsMeshReference("lockedTargetId")
  13140. ], FollowCamera.prototype, "target", void 0);
  13141. return FollowCamera;
  13142. })(BABYLON.TargetCamera);
  13143. BABYLON.FollowCamera = FollowCamera;
  13144. var ArcFollowCamera = (function (_super) {
  13145. __extends(ArcFollowCamera, _super);
  13146. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13147. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13148. this.alpha = alpha;
  13149. this.beta = beta;
  13150. this.radius = radius;
  13151. this.target = target;
  13152. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13153. this.follow();
  13154. }
  13155. ArcFollowCamera.prototype.follow = function () {
  13156. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13157. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13158. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13159. this.position = this.target.position.add(this._cartesianCoordinates);
  13160. this.setTarget(this.target.position);
  13161. };
  13162. ArcFollowCamera.prototype._checkInputs = function () {
  13163. _super.prototype._checkInputs.call(this);
  13164. this.follow();
  13165. };
  13166. ArcFollowCamera.prototype.getTypeName = function () {
  13167. return "ArcFollowCamera";
  13168. };
  13169. return ArcFollowCamera;
  13170. })(BABYLON.TargetCamera);
  13171. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13172. })(BABYLON || (BABYLON = {}));
  13173. var BABYLON;
  13174. (function (BABYLON) {
  13175. // We're mainly based on the logic defined into the FreeCamera code
  13176. var TouchCamera = (function (_super) {
  13177. __extends(TouchCamera, _super);
  13178. //-- end properties for backward compatibility for inputs
  13179. function TouchCamera(name, position, scene) {
  13180. _super.call(this, name, position, scene);
  13181. this.inputs.addTouch();
  13182. }
  13183. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13184. //-- Begin properties for backward compatibility for inputs
  13185. get: function () {
  13186. var touch = this.inputs.attached["touch"];
  13187. if (touch)
  13188. return touch.touchAngularSensibility;
  13189. },
  13190. set: function (value) {
  13191. var touch = this.inputs.attached["touch"];
  13192. if (touch)
  13193. touch.touchAngularSensibility = value;
  13194. },
  13195. enumerable: true,
  13196. configurable: true
  13197. });
  13198. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13199. get: function () {
  13200. var touch = this.inputs.attached["touch"];
  13201. if (touch)
  13202. return touch.touchMoveSensibility;
  13203. },
  13204. set: function (value) {
  13205. var touch = this.inputs.attached["touch"];
  13206. if (touch)
  13207. touch.touchMoveSensibility = value;
  13208. },
  13209. enumerable: true,
  13210. configurable: true
  13211. });
  13212. TouchCamera.prototype.getTypeName = function () {
  13213. return "TouchCamera";
  13214. };
  13215. return TouchCamera;
  13216. })(BABYLON.FreeCamera);
  13217. BABYLON.TouchCamera = TouchCamera;
  13218. })(BABYLON || (BABYLON = {}));
  13219. var BABYLON;
  13220. (function (BABYLON) {
  13221. var ArcRotateCamera = (function (_super) {
  13222. __extends(ArcRotateCamera, _super);
  13223. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13224. var _this = this;
  13225. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13226. this.inertialAlphaOffset = 0;
  13227. this.inertialBetaOffset = 0;
  13228. this.inertialRadiusOffset = 0;
  13229. this.lowerAlphaLimit = null;
  13230. this.upperAlphaLimit = null;
  13231. this.lowerBetaLimit = 0.01;
  13232. this.upperBetaLimit = Math.PI;
  13233. this.lowerRadiusLimit = null;
  13234. this.upperRadiusLimit = null;
  13235. this.inertialPanningX = 0;
  13236. this.inertialPanningY = 0;
  13237. //-- end properties for backward compatibility for inputs
  13238. this.zoomOnFactor = 1;
  13239. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13240. this.allowUpsideDown = true;
  13241. this._viewMatrix = new BABYLON.Matrix();
  13242. // Panning
  13243. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13244. this.checkCollisions = false;
  13245. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13246. this._collider = new BABYLON.Collider();
  13247. this._previousPosition = BABYLON.Vector3.Zero();
  13248. this._collisionVelocity = BABYLON.Vector3.Zero();
  13249. this._newPosition = BABYLON.Vector3.Zero();
  13250. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13251. if (collidedMesh === void 0) { collidedMesh = null; }
  13252. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13253. newPosition.multiplyInPlace(_this._collider.radius);
  13254. }
  13255. if (!collidedMesh) {
  13256. _this._previousPosition.copyFrom(_this.position);
  13257. }
  13258. else {
  13259. _this.setPosition(newPosition);
  13260. if (_this.onCollide) {
  13261. _this.onCollide(collidedMesh);
  13262. }
  13263. }
  13264. // Recompute because of constraints
  13265. var cosa = Math.cos(_this.alpha);
  13266. var sina = Math.sin(_this.alpha);
  13267. var cosb = Math.cos(_this.beta);
  13268. var sinb = Math.sin(_this.beta);
  13269. if (sinb === 0) {
  13270. sinb = 0.0001;
  13271. }
  13272. var target = _this._getTargetPosition();
  13273. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13274. _this.position.copyFrom(_this._newPosition);
  13275. var up = _this.upVector;
  13276. if (_this.allowUpsideDown && _this.beta < 0) {
  13277. up = up.clone();
  13278. up = up.negate();
  13279. }
  13280. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13281. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13282. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13283. _this._collisionTriggered = false;
  13284. };
  13285. if (!target) {
  13286. this.target = BABYLON.Vector3.Zero();
  13287. }
  13288. else {
  13289. this.target = target;
  13290. }
  13291. this.alpha = alpha;
  13292. this.beta = beta;
  13293. this.radius = radius;
  13294. this.getViewMatrix();
  13295. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13296. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13297. }
  13298. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13299. //-- begin properties for backward compatibility for inputs
  13300. get: function () {
  13301. var pointers = this.inputs.attached["pointers"];
  13302. if (pointers)
  13303. return pointers.angularSensibilityX;
  13304. },
  13305. set: function (value) {
  13306. var pointers = this.inputs.attached["pointers"];
  13307. if (pointers) {
  13308. pointers.angularSensibilityX = value;
  13309. }
  13310. },
  13311. enumerable: true,
  13312. configurable: true
  13313. });
  13314. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13315. get: function () {
  13316. var pointers = this.inputs.attached["pointers"];
  13317. if (pointers)
  13318. return pointers.angularSensibilityY;
  13319. },
  13320. set: function (value) {
  13321. var pointers = this.inputs.attached["pointers"];
  13322. if (pointers) {
  13323. pointers.angularSensibilityY = value;
  13324. }
  13325. },
  13326. enumerable: true,
  13327. configurable: true
  13328. });
  13329. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13330. get: function () {
  13331. var pointers = this.inputs.attached["pointers"];
  13332. if (pointers)
  13333. return pointers.pinchPrecision;
  13334. },
  13335. set: function (value) {
  13336. var pointers = this.inputs.attached["pointers"];
  13337. if (pointers) {
  13338. pointers.pinchPrecision = value;
  13339. }
  13340. },
  13341. enumerable: true,
  13342. configurable: true
  13343. });
  13344. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13345. get: function () {
  13346. var pointers = this.inputs.attached["pointers"];
  13347. if (pointers)
  13348. return pointers.panningSensibility;
  13349. },
  13350. set: function (value) {
  13351. var pointers = this.inputs.attached["pointers"];
  13352. if (pointers) {
  13353. pointers.panningSensibility = value;
  13354. }
  13355. },
  13356. enumerable: true,
  13357. configurable: true
  13358. });
  13359. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13360. get: function () {
  13361. var keyboard = this.inputs.attached["keyboard"];
  13362. if (keyboard)
  13363. return keyboard.keysUp;
  13364. },
  13365. set: function (value) {
  13366. var keyboard = this.inputs.attached["keyboard"];
  13367. if (keyboard)
  13368. keyboard.keysUp = value;
  13369. },
  13370. enumerable: true,
  13371. configurable: true
  13372. });
  13373. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13374. get: function () {
  13375. var keyboard = this.inputs.attached["keyboard"];
  13376. if (keyboard)
  13377. return keyboard.keysDown;
  13378. },
  13379. set: function (value) {
  13380. var keyboard = this.inputs.attached["keyboard"];
  13381. if (keyboard)
  13382. keyboard.keysDown = value;
  13383. },
  13384. enumerable: true,
  13385. configurable: true
  13386. });
  13387. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13388. get: function () {
  13389. var keyboard = this.inputs.attached["keyboard"];
  13390. if (keyboard)
  13391. return keyboard.keysLeft;
  13392. },
  13393. set: function (value) {
  13394. var keyboard = this.inputs.attached["keyboard"];
  13395. if (keyboard)
  13396. keyboard.keysLeft = value;
  13397. },
  13398. enumerable: true,
  13399. configurable: true
  13400. });
  13401. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13402. get: function () {
  13403. var keyboard = this.inputs.attached["keyboard"];
  13404. if (keyboard)
  13405. return keyboard.keysRight;
  13406. },
  13407. set: function (value) {
  13408. var keyboard = this.inputs.attached["keyboard"];
  13409. if (keyboard)
  13410. keyboard.keysRight = value;
  13411. },
  13412. enumerable: true,
  13413. configurable: true
  13414. });
  13415. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13416. get: function () {
  13417. var mousewheel = this.inputs.attached["mousewheel"];
  13418. if (mousewheel)
  13419. return mousewheel.wheelPrecision;
  13420. },
  13421. set: function (value) {
  13422. var mousewheel = this.inputs.attached["mousewheel"];
  13423. if (mousewheel)
  13424. mousewheel.wheelPrecision = value;
  13425. },
  13426. enumerable: true,
  13427. configurable: true
  13428. });
  13429. // Cache
  13430. ArcRotateCamera.prototype._initCache = function () {
  13431. _super.prototype._initCache.call(this);
  13432. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13433. this._cache.alpha = undefined;
  13434. this._cache.beta = undefined;
  13435. this._cache.radius = undefined;
  13436. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13437. };
  13438. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13439. if (!ignoreParentClass) {
  13440. _super.prototype._updateCache.call(this);
  13441. }
  13442. this._cache.target.copyFrom(this._getTargetPosition());
  13443. this._cache.alpha = this.alpha;
  13444. this._cache.beta = this.beta;
  13445. this._cache.radius = this.radius;
  13446. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13447. };
  13448. ArcRotateCamera.prototype._getTargetPosition = function () {
  13449. if (this.target.getAbsolutePosition) {
  13450. return this.target.getAbsolutePosition();
  13451. }
  13452. return this.target;
  13453. };
  13454. // Synchronized
  13455. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13456. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13457. return false;
  13458. return this._cache.target.equals(this.target)
  13459. && this._cache.alpha === this.alpha
  13460. && this._cache.beta === this.beta
  13461. && this._cache.radius === this.radius
  13462. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13463. };
  13464. // Methods
  13465. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13466. var _this = this;
  13467. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13468. this._useCtrlForPanning = useCtrlForPanning;
  13469. this.inputs.attachElement(element, noPreventDefault);
  13470. this._reset = function () {
  13471. _this.inertialAlphaOffset = 0;
  13472. _this.inertialBetaOffset = 0;
  13473. _this.inertialRadiusOffset = 0;
  13474. };
  13475. };
  13476. ArcRotateCamera.prototype.detachControl = function (element) {
  13477. this.inputs.detachElement(element);
  13478. if (this._reset) {
  13479. this._reset();
  13480. }
  13481. };
  13482. ArcRotateCamera.prototype._checkInputs = function () {
  13483. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13484. if (this._collisionTriggered) {
  13485. return;
  13486. }
  13487. this.inputs.checkInputs();
  13488. // Inertia
  13489. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13490. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13491. this.beta += this.inertialBetaOffset;
  13492. this.radius -= this.inertialRadiusOffset;
  13493. this.inertialAlphaOffset *= this.inertia;
  13494. this.inertialBetaOffset *= this.inertia;
  13495. this.inertialRadiusOffset *= this.inertia;
  13496. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13497. this.inertialAlphaOffset = 0;
  13498. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13499. this.inertialBetaOffset = 0;
  13500. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13501. this.inertialRadiusOffset = 0;
  13502. }
  13503. // Panning inertia
  13504. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13505. if (!this._localDirection) {
  13506. this._localDirection = BABYLON.Vector3.Zero();
  13507. this._transformedDirection = BABYLON.Vector3.Zero();
  13508. }
  13509. this.inertialPanningX *= this.inertia;
  13510. this.inertialPanningY *= this.inertia;
  13511. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13512. this.inertialPanningX = 0;
  13513. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13514. this.inertialPanningY = 0;
  13515. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13516. this._localDirection.multiplyInPlace(this.panningAxis);
  13517. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13518. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13519. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13520. if (!this.panningAxis.y) {
  13521. this._transformedDirection.y = 0;
  13522. }
  13523. this.target.addInPlace(this._transformedDirection);
  13524. }
  13525. // Limits
  13526. this._checkLimits();
  13527. _super.prototype._checkInputs.call(this);
  13528. };
  13529. ArcRotateCamera.prototype._checkLimits = function () {
  13530. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13531. if (this.allowUpsideDown && this.beta > Math.PI) {
  13532. this.beta = this.beta - (2 * Math.PI);
  13533. }
  13534. }
  13535. else {
  13536. if (this.beta < this.lowerBetaLimit) {
  13537. this.beta = this.lowerBetaLimit;
  13538. }
  13539. }
  13540. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13541. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13542. this.beta = this.beta + (2 * Math.PI);
  13543. }
  13544. }
  13545. else {
  13546. if (this.beta > this.upperBetaLimit) {
  13547. this.beta = this.upperBetaLimit;
  13548. }
  13549. }
  13550. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13551. this.alpha = this.lowerAlphaLimit;
  13552. }
  13553. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13554. this.alpha = this.upperAlphaLimit;
  13555. }
  13556. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13557. this.radius = this.lowerRadiusLimit;
  13558. }
  13559. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13560. this.radius = this.upperRadiusLimit;
  13561. }
  13562. };
  13563. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13564. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13565. this.radius = radiusv3.length();
  13566. // Alpha
  13567. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13568. if (radiusv3.z < 0) {
  13569. this.alpha = 2 * Math.PI - this.alpha;
  13570. }
  13571. // Beta
  13572. this.beta = Math.acos(radiusv3.y / this.radius);
  13573. this._checkLimits();
  13574. };
  13575. ArcRotateCamera.prototype.setPosition = function (position) {
  13576. if (this.position.equals(position)) {
  13577. return;
  13578. }
  13579. this.position = position;
  13580. this.rebuildAnglesAndRadius();
  13581. };
  13582. ArcRotateCamera.prototype.setTarget = function (target) {
  13583. if (this._getTargetPosition().equals(target)) {
  13584. return;
  13585. }
  13586. this.target = target;
  13587. this.rebuildAnglesAndRadius();
  13588. };
  13589. ArcRotateCamera.prototype._getViewMatrix = function () {
  13590. // Compute
  13591. var cosa = Math.cos(this.alpha);
  13592. var sina = Math.sin(this.alpha);
  13593. var cosb = Math.cos(this.beta);
  13594. var sinb = Math.sin(this.beta);
  13595. if (sinb === 0) {
  13596. sinb = 0.0001;
  13597. }
  13598. var target = this._getTargetPosition();
  13599. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13600. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13601. this._collider.radius = this.collisionRadius;
  13602. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13603. this._collisionTriggered = true;
  13604. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13605. }
  13606. else {
  13607. this.position.copyFrom(this._newPosition);
  13608. var up = this.upVector;
  13609. if (this.allowUpsideDown && this.beta < 0) {
  13610. up = up.clone();
  13611. up = up.negate();
  13612. }
  13613. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13614. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13615. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13616. }
  13617. return this._viewMatrix;
  13618. };
  13619. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13620. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13621. meshes = meshes || this.getScene().meshes;
  13622. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13623. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13624. this.radius = distance * this.zoomOnFactor;
  13625. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13626. };
  13627. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13628. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13629. var meshesOrMinMaxVector;
  13630. var distance;
  13631. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13632. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13633. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13634. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13635. }
  13636. else {
  13637. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13638. distance = meshesOrMinMaxVectorAndDistance.distance;
  13639. }
  13640. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13641. if (!doNotUpdateMaxZ) {
  13642. this.maxZ = distance * 2;
  13643. }
  13644. };
  13645. /**
  13646. * @override
  13647. * Override Camera.createRigCamera
  13648. */
  13649. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13650. switch (this.cameraRigMode) {
  13651. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13652. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13653. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13654. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13655. case BABYLON.Camera.RIG_MODE_VR:
  13656. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13657. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13658. rigCam._cameraRigParams = {};
  13659. return rigCam;
  13660. }
  13661. return null;
  13662. };
  13663. /**
  13664. * @override
  13665. * Override Camera._updateRigCameras
  13666. */
  13667. ArcRotateCamera.prototype._updateRigCameras = function () {
  13668. switch (this.cameraRigMode) {
  13669. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13670. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13671. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13672. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13673. case BABYLON.Camera.RIG_MODE_VR:
  13674. var camLeft = this._rigCameras[0];
  13675. var camRight = this._rigCameras[1];
  13676. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13677. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13678. camLeft.beta = camRight.beta = this.beta;
  13679. camLeft.radius = camRight.radius = this.radius;
  13680. break;
  13681. }
  13682. _super.prototype._updateRigCameras.call(this);
  13683. };
  13684. ArcRotateCamera.prototype.dispose = function () {
  13685. this.inputs.clear();
  13686. _super.prototype.dispose.call(this);
  13687. };
  13688. ArcRotateCamera.prototype.getTypeName = function () {
  13689. return "ArcRotateCamera";
  13690. };
  13691. __decorate([
  13692. BABYLON.serialize()
  13693. ], ArcRotateCamera.prototype, "alpha", void 0);
  13694. __decorate([
  13695. BABYLON.serialize()
  13696. ], ArcRotateCamera.prototype, "beta", void 0);
  13697. __decorate([
  13698. BABYLON.serialize()
  13699. ], ArcRotateCamera.prototype, "radius", void 0);
  13700. __decorate([
  13701. BABYLON.serializeAsVector3()
  13702. ], ArcRotateCamera.prototype, "target", void 0);
  13703. __decorate([
  13704. BABYLON.serialize()
  13705. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13706. __decorate([
  13707. BABYLON.serialize()
  13708. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13709. __decorate([
  13710. BABYLON.serialize()
  13711. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13712. __decorate([
  13713. BABYLON.serialize()
  13714. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13715. __decorate([
  13716. BABYLON.serialize()
  13717. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13718. __decorate([
  13719. BABYLON.serialize()
  13720. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13721. __decorate([
  13722. BABYLON.serialize()
  13723. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13724. __decorate([
  13725. BABYLON.serialize()
  13726. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13727. __decorate([
  13728. BABYLON.serialize()
  13729. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13730. __decorate([
  13731. BABYLON.serialize()
  13732. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13733. __decorate([
  13734. BABYLON.serialize()
  13735. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13736. __decorate([
  13737. BABYLON.serialize()
  13738. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13739. __decorate([
  13740. BABYLON.serialize()
  13741. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13742. return ArcRotateCamera;
  13743. })(BABYLON.TargetCamera);
  13744. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13745. })(BABYLON || (BABYLON = {}));
  13746. var BABYLON;
  13747. (function (BABYLON) {
  13748. var ArcRotateCameraInputsManager = (function (_super) {
  13749. __extends(ArcRotateCameraInputsManager, _super);
  13750. function ArcRotateCameraInputsManager(camera) {
  13751. _super.call(this, camera);
  13752. }
  13753. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13754. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13755. return this;
  13756. };
  13757. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13758. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13759. return this;
  13760. };
  13761. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13762. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13763. return this;
  13764. };
  13765. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13766. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13767. return this;
  13768. };
  13769. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13770. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  13771. return this;
  13772. };
  13773. return ArcRotateCameraInputsManager;
  13774. })(BABYLON.CameraInputsManager);
  13775. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13776. })(BABYLON || (BABYLON = {}));
  13777. var BABYLON;
  13778. (function (BABYLON) {
  13779. var RenderingManager = (function () {
  13780. function RenderingManager(scene) {
  13781. this._renderingGroups = new Array();
  13782. this._scene = scene;
  13783. }
  13784. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13785. if (this._scene._activeParticleSystems.length === 0) {
  13786. return;
  13787. }
  13788. // Particles
  13789. var activeCamera = this._scene.activeCamera;
  13790. var beforeParticlesDate = BABYLON.Tools.Now;
  13791. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13792. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13793. if (particleSystem.renderingGroupId !== index) {
  13794. continue;
  13795. }
  13796. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13797. continue;
  13798. }
  13799. this._clearDepthBuffer();
  13800. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13801. this._scene._activeParticles += particleSystem.render();
  13802. }
  13803. }
  13804. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13805. };
  13806. RenderingManager.prototype._renderSprites = function (index) {
  13807. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13808. return;
  13809. }
  13810. // Sprites
  13811. var activeCamera = this._scene.activeCamera;
  13812. var beforeSpritessDate = BABYLON.Tools.Now;
  13813. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13814. var spriteManager = this._scene.spriteManagers[id];
  13815. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13816. this._clearDepthBuffer();
  13817. spriteManager.render();
  13818. }
  13819. }
  13820. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13821. };
  13822. RenderingManager.prototype._clearDepthBuffer = function () {
  13823. if (this._depthBufferAlreadyCleaned) {
  13824. return;
  13825. }
  13826. this._scene.getEngine().clear(0, false, true);
  13827. this._depthBufferAlreadyCleaned = true;
  13828. };
  13829. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13830. if (this._currentRenderSprites) {
  13831. this._renderSprites(this._currentIndex);
  13832. }
  13833. if (this._currentRenderParticles) {
  13834. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13835. }
  13836. };
  13837. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13838. this._currentActiveMeshes = activeMeshes;
  13839. this._currentRenderParticles = renderParticles;
  13840. this._currentRenderSprites = renderSprites;
  13841. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13842. this._depthBufferAlreadyCleaned = index == 0;
  13843. var renderingGroup = this._renderingGroups[index];
  13844. var needToStepBack = false;
  13845. this._currentIndex = index;
  13846. if (renderingGroup) {
  13847. this._clearDepthBuffer();
  13848. if (!renderingGroup.onBeforeTransparentRendering) {
  13849. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13850. }
  13851. if (!renderingGroup.render(customRenderFunction)) {
  13852. this._renderingGroups.splice(index, 1);
  13853. needToStepBack = true;
  13854. this._renderSpritesAndParticles();
  13855. }
  13856. }
  13857. else {
  13858. this._renderSpritesAndParticles();
  13859. }
  13860. if (needToStepBack) {
  13861. index--;
  13862. }
  13863. }
  13864. };
  13865. RenderingManager.prototype.reset = function () {
  13866. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13867. if (renderingGroup) {
  13868. renderingGroup.prepare();
  13869. }
  13870. });
  13871. };
  13872. RenderingManager.prototype.dispatch = function (subMesh) {
  13873. var mesh = subMesh.getMesh();
  13874. var renderingGroupId = mesh.renderingGroupId || 0;
  13875. if (!this._renderingGroups[renderingGroupId]) {
  13876. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13877. }
  13878. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13879. };
  13880. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13881. return RenderingManager;
  13882. })();
  13883. BABYLON.RenderingManager = RenderingManager;
  13884. })(BABYLON || (BABYLON = {}));
  13885. var BABYLON;
  13886. (function (BABYLON) {
  13887. var RenderingGroup = (function () {
  13888. function RenderingGroup(index, scene) {
  13889. this.index = index;
  13890. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13891. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13892. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13893. this._scene = scene;
  13894. }
  13895. RenderingGroup.prototype.render = function (customRenderFunction) {
  13896. if (customRenderFunction) {
  13897. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13898. return true;
  13899. }
  13900. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  13901. if (this.onBeforeTransparentRendering) {
  13902. this.onBeforeTransparentRendering();
  13903. }
  13904. return false;
  13905. }
  13906. var engine = this._scene.getEngine();
  13907. // Opaque
  13908. var subIndex;
  13909. var submesh;
  13910. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  13911. submesh = this._opaqueSubMeshes.data[subIndex];
  13912. submesh.render(false);
  13913. }
  13914. // Alpha test
  13915. engine.setAlphaTesting(true);
  13916. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  13917. submesh = this._alphaTestSubMeshes.data[subIndex];
  13918. submesh.render(false);
  13919. }
  13920. engine.setAlphaTesting(false);
  13921. if (this.onBeforeTransparentRendering) {
  13922. this.onBeforeTransparentRendering();
  13923. }
  13924. // Transparent
  13925. if (this._transparentSubMeshes.length) {
  13926. // Sorting
  13927. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  13928. submesh = this._transparentSubMeshes.data[subIndex];
  13929. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  13930. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  13931. }
  13932. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  13933. sortedArray.sort(function (a, b) {
  13934. // Alpha index first
  13935. if (a._alphaIndex > b._alphaIndex) {
  13936. return 1;
  13937. }
  13938. if (a._alphaIndex < b._alphaIndex) {
  13939. return -1;
  13940. }
  13941. // Then distance to camera
  13942. if (a._distanceToCamera < b._distanceToCamera) {
  13943. return 1;
  13944. }
  13945. if (a._distanceToCamera > b._distanceToCamera) {
  13946. return -1;
  13947. }
  13948. return 0;
  13949. });
  13950. // Rendering
  13951. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  13952. submesh = sortedArray[subIndex];
  13953. submesh.render(true);
  13954. }
  13955. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13956. }
  13957. return true;
  13958. };
  13959. RenderingGroup.prototype.prepare = function () {
  13960. this._opaqueSubMeshes.reset();
  13961. this._transparentSubMeshes.reset();
  13962. this._alphaTestSubMeshes.reset();
  13963. };
  13964. RenderingGroup.prototype.dispatch = function (subMesh) {
  13965. var material = subMesh.getMaterial();
  13966. var mesh = subMesh.getMesh();
  13967. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  13968. this._transparentSubMeshes.push(subMesh);
  13969. }
  13970. else if (material.needAlphaTesting()) {
  13971. this._alphaTestSubMeshes.push(subMesh);
  13972. }
  13973. else {
  13974. this._opaqueSubMeshes.push(subMesh); // Opaque
  13975. }
  13976. };
  13977. return RenderingGroup;
  13978. })();
  13979. BABYLON.RenderingGroup = RenderingGroup;
  13980. })(BABYLON || (BABYLON = {}));
  13981. var BABYLON;
  13982. (function (BABYLON) {
  13983. var PointerEventTypes = (function () {
  13984. function PointerEventTypes() {
  13985. }
  13986. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  13987. get: function () {
  13988. return PointerEventTypes._POINTERDOWN;
  13989. },
  13990. enumerable: true,
  13991. configurable: true
  13992. });
  13993. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  13994. get: function () {
  13995. return PointerEventTypes._POINTERUP;
  13996. },
  13997. enumerable: true,
  13998. configurable: true
  13999. });
  14000. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14001. get: function () {
  14002. return PointerEventTypes._POINTERMOVE;
  14003. },
  14004. enumerable: true,
  14005. configurable: true
  14006. });
  14007. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14008. get: function () {
  14009. return PointerEventTypes._POINTERWHEEL;
  14010. },
  14011. enumerable: true,
  14012. configurable: true
  14013. });
  14014. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14015. get: function () {
  14016. return PointerEventTypes._POINTERPICK;
  14017. },
  14018. enumerable: true,
  14019. configurable: true
  14020. });
  14021. PointerEventTypes._POINTERDOWN = 0x01;
  14022. PointerEventTypes._POINTERUP = 0x02;
  14023. PointerEventTypes._POINTERMOVE = 0x04;
  14024. PointerEventTypes._POINTERWHEEL = 0x08;
  14025. PointerEventTypes._POINTERPICK = 0x10;
  14026. return PointerEventTypes;
  14027. })();
  14028. BABYLON.PointerEventTypes = PointerEventTypes;
  14029. /**
  14030. * This type contains all the data related to a pointer event in Babylon.js.
  14031. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The differents event types can be found in the PointerEventTypes class.
  14032. */
  14033. var PointerInfo = (function () {
  14034. function PointerInfo(type, event, pickInfo) {
  14035. this.type = type;
  14036. this.event = event;
  14037. this.pickInfo = pickInfo;
  14038. }
  14039. return PointerInfo;
  14040. })();
  14041. BABYLON.PointerInfo = PointerInfo;
  14042. /**
  14043. * Represents a scene to be rendered by the engine.
  14044. * @see http://doc.babylonjs.com/page.php?p=21911
  14045. */
  14046. var Scene = (function () {
  14047. /**
  14048. * @constructor
  14049. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14050. */
  14051. function Scene(engine) {
  14052. // Members
  14053. this.autoClear = true;
  14054. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14055. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14056. this.forceWireframe = false;
  14057. this.forcePointsCloud = false;
  14058. this.forceShowBoundingBoxes = false;
  14059. this.animationsEnabled = true;
  14060. this.constantlyUpdateMeshUnderPointer = false;
  14061. // Events
  14062. /**
  14063. * An event triggered when the scene is disposed.
  14064. * @type {BABYLON.Observable}
  14065. */
  14066. this.onDisposeObservable = new BABYLON.Observable();
  14067. /**
  14068. * An event triggered before rendering the scene
  14069. * @type {BABYLON.Observable}
  14070. */
  14071. this.onBeforeRenderObservable = new BABYLON.Observable();
  14072. /**
  14073. * An event triggered after rendering the scene
  14074. * @type {BABYLON.Observable}
  14075. */
  14076. this.onAfterRenderObservable = new BABYLON.Observable();
  14077. /**
  14078. * An event triggered when the scene is ready
  14079. * @type {BABYLON.Observable}
  14080. */
  14081. this.onReadyObservable = new BABYLON.Observable();
  14082. /**
  14083. * An event triggered before rendering a camera
  14084. * @type {BABYLON.Observable}
  14085. */
  14086. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14087. /**
  14088. * An event triggered after rendering a camera
  14089. * @type {BABYLON.Observable}
  14090. */
  14091. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14092. /**
  14093. * An event triggered when a camera is created
  14094. * @type {BABYLON.Observable}
  14095. */
  14096. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14097. /**
  14098. * An event triggered when a camera is removed
  14099. * @type {BABYLON.Observable}
  14100. */
  14101. this.onCameraRemovedObservable = new BABYLON.Observable();
  14102. /**
  14103. * An event triggered when a light is created
  14104. * @type {BABYLON.Observable}
  14105. */
  14106. this.onNewLightAddedObservable = new BABYLON.Observable();
  14107. /**
  14108. * An event triggered when a light is removed
  14109. * @type {BABYLON.Observable}
  14110. */
  14111. this.onLightRemovedObservable = new BABYLON.Observable();
  14112. /**
  14113. * An event triggered when a geometry is created
  14114. * @type {BABYLON.Observable}
  14115. */
  14116. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14117. /**
  14118. * An event triggered when a geometry is removed
  14119. * @type {BABYLON.Observable}
  14120. */
  14121. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14122. /**
  14123. * An event triggered when a mesh is created
  14124. * @type {BABYLON.Observable}
  14125. */
  14126. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14127. /**
  14128. * An event triggered when a mesh is removed
  14129. * @type {BABYLON.Observable}
  14130. */
  14131. this.onMeshRemovedObservable = new BABYLON.Observable();
  14132. // Animations
  14133. this.animations = [];
  14134. /**
  14135. * Observable event triggered each time an input event is received from the rendering canvas
  14136. */
  14137. this.onPointerObservable = new BABYLON.Observable();
  14138. 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
  14139. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14140. this._startingPointerTime = 0;
  14141. // Fog
  14142. /**
  14143. * is fog enabled on this scene.
  14144. * @type {boolean}
  14145. */
  14146. this.fogEnabled = true;
  14147. this.fogMode = Scene.FOGMODE_NONE;
  14148. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14149. this.fogDensity = 0.1;
  14150. this.fogStart = 0;
  14151. this.fogEnd = 1000.0;
  14152. // Lights
  14153. /**
  14154. * is shadow enabled on this scene.
  14155. * @type {boolean}
  14156. */
  14157. this.shadowsEnabled = true;
  14158. /**
  14159. * is light enabled on this scene.
  14160. * @type {boolean}
  14161. */
  14162. this.lightsEnabled = true;
  14163. /**
  14164. * All of the lights added to this scene.
  14165. * @see BABYLON.Light
  14166. * @type {BABYLON.Light[]}
  14167. */
  14168. this.lights = new Array();
  14169. // Cameras
  14170. /**
  14171. * All of the cameras added to this scene.
  14172. * @see BABYLON.Camera
  14173. * @type {BABYLON.Camera[]}
  14174. */
  14175. this.cameras = new Array();
  14176. this.activeCameras = new Array();
  14177. // Meshes
  14178. /**
  14179. * All of the (abstract) meshes added to this scene.
  14180. * @see BABYLON.AbstractMesh
  14181. * @type {BABYLON.AbstractMesh[]}
  14182. */
  14183. this.meshes = new Array();
  14184. // Geometries
  14185. this._geometries = new Array();
  14186. this.materials = new Array();
  14187. this.multiMaterials = new Array();
  14188. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14189. // Textures
  14190. this.texturesEnabled = true;
  14191. this.textures = new Array();
  14192. // Particles
  14193. this.particlesEnabled = true;
  14194. this.particleSystems = new Array();
  14195. // Sprites
  14196. this.spritesEnabled = true;
  14197. this.spriteManagers = new Array();
  14198. // Layers
  14199. this.layers = new Array();
  14200. // Skeletons
  14201. this.skeletonsEnabled = true;
  14202. this.skeletons = new Array();
  14203. // Lens flares
  14204. this.lensFlaresEnabled = true;
  14205. this.lensFlareSystems = new Array();
  14206. // Collisions
  14207. this.collisionsEnabled = true;
  14208. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14209. // Postprocesses
  14210. this.postProcessesEnabled = true;
  14211. // Customs render targets
  14212. this.renderTargetsEnabled = true;
  14213. this.dumpNextRenderTargets = false;
  14214. this.customRenderTargets = new Array();
  14215. // Imported meshes
  14216. this.importedMeshesFiles = new Array();
  14217. // Probes
  14218. this.probesEnabled = true;
  14219. this.reflectionProbes = new Array();
  14220. this._actionManagers = new Array();
  14221. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14222. // Procedural textures
  14223. this.proceduralTexturesEnabled = true;
  14224. this._proceduralTextures = new Array();
  14225. this.soundTracks = new Array();
  14226. this._audioEnabled = true;
  14227. this._headphone = false;
  14228. this._totalVertices = 0;
  14229. this._activeIndices = 0;
  14230. this._activeParticles = 0;
  14231. this._lastFrameDuration = 0;
  14232. this._evaluateActiveMeshesDuration = 0;
  14233. this._renderTargetsDuration = 0;
  14234. this._particlesDuration = 0;
  14235. this._renderDuration = 0;
  14236. this._spritesDuration = 0;
  14237. this._animationRatio = 0;
  14238. this._renderId = 0;
  14239. this._executeWhenReadyTimeoutId = -1;
  14240. this._intermediateRendering = false;
  14241. this._toBeDisposed = new BABYLON.SmartArray(256);
  14242. this._pendingData = []; //ANY
  14243. this._activeMeshes = new BABYLON.SmartArray(256);
  14244. this._processedMaterials = new BABYLON.SmartArray(256);
  14245. this._renderTargets = new BABYLON.SmartArray(256);
  14246. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14247. this._activeSkeletons = new BABYLON.SmartArray(32);
  14248. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14249. this._activeBones = 0;
  14250. this._activeAnimatables = new Array();
  14251. this._transformMatrix = BABYLON.Matrix.Zero();
  14252. this._edgesRenderers = new BABYLON.SmartArray(16);
  14253. this._uniqueIdCounter = 0;
  14254. this._engine = engine;
  14255. engine.scenes.push(this);
  14256. this._renderingManager = new BABYLON.RenderingManager(this);
  14257. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14258. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14259. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14260. if (BABYLON.OutlineRenderer) {
  14261. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14262. }
  14263. this.attachControl();
  14264. this._debugLayer = new BABYLON.DebugLayer(this);
  14265. if (BABYLON.SoundTrack) {
  14266. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14267. }
  14268. //simplification queue
  14269. if (BABYLON.SimplificationQueue) {
  14270. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14271. }
  14272. //collision coordinator initialization. For now legacy per default.
  14273. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14274. }
  14275. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14276. get: function () {
  14277. return Scene._FOGMODE_NONE;
  14278. },
  14279. enumerable: true,
  14280. configurable: true
  14281. });
  14282. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14283. get: function () {
  14284. return Scene._FOGMODE_EXP;
  14285. },
  14286. enumerable: true,
  14287. configurable: true
  14288. });
  14289. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14290. get: function () {
  14291. return Scene._FOGMODE_EXP2;
  14292. },
  14293. enumerable: true,
  14294. configurable: true
  14295. });
  14296. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14297. get: function () {
  14298. return Scene._FOGMODE_LINEAR;
  14299. },
  14300. enumerable: true,
  14301. configurable: true
  14302. });
  14303. Object.defineProperty(Scene.prototype, "onDispose", {
  14304. set: function (callback) {
  14305. if (this._onDisposeObserver) {
  14306. this.onDisposeObservable.remove(this._onDisposeObserver);
  14307. }
  14308. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14309. },
  14310. enumerable: true,
  14311. configurable: true
  14312. });
  14313. Object.defineProperty(Scene.prototype, "beforeRender", {
  14314. set: function (callback) {
  14315. if (this._onBeforeRenderObserver) {
  14316. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14317. }
  14318. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14319. },
  14320. enumerable: true,
  14321. configurable: true
  14322. });
  14323. Object.defineProperty(Scene.prototype, "afterRender", {
  14324. set: function (callback) {
  14325. if (this._onAfterRenderObserver) {
  14326. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14327. }
  14328. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14329. },
  14330. enumerable: true,
  14331. configurable: true
  14332. });
  14333. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14334. set: function (callback) {
  14335. if (this._onBeforeCameraRenderObserver) {
  14336. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14337. }
  14338. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14339. },
  14340. enumerable: true,
  14341. configurable: true
  14342. });
  14343. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14344. set: function (callback) {
  14345. if (this._onAfterCameraRenderObserver) {
  14346. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14347. }
  14348. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14349. },
  14350. enumerable: true,
  14351. configurable: true
  14352. });
  14353. Object.defineProperty(Scene.prototype, "debugLayer", {
  14354. // Properties
  14355. get: function () {
  14356. return this._debugLayer;
  14357. },
  14358. enumerable: true,
  14359. configurable: true
  14360. });
  14361. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14362. get: function () {
  14363. return this._workerCollisions;
  14364. },
  14365. set: function (enabled) {
  14366. enabled = (enabled && !!Worker);
  14367. this._workerCollisions = enabled;
  14368. if (this.collisionCoordinator) {
  14369. this.collisionCoordinator.destroy();
  14370. }
  14371. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14372. this.collisionCoordinator.init(this);
  14373. },
  14374. enumerable: true,
  14375. configurable: true
  14376. });
  14377. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14378. get: function () {
  14379. return this._selectionOctree;
  14380. },
  14381. enumerable: true,
  14382. configurable: true
  14383. });
  14384. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14385. /**
  14386. * The mesh that is currently under the pointer.
  14387. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14388. */
  14389. get: function () {
  14390. return this._pointerOverMesh;
  14391. },
  14392. enumerable: true,
  14393. configurable: true
  14394. });
  14395. Object.defineProperty(Scene.prototype, "pointerX", {
  14396. /**
  14397. * Current on-screen X position of the pointer
  14398. * @return {number} X position of the pointer
  14399. */
  14400. get: function () {
  14401. return this._pointerX;
  14402. },
  14403. enumerable: true,
  14404. configurable: true
  14405. });
  14406. Object.defineProperty(Scene.prototype, "pointerY", {
  14407. /**
  14408. * Current on-screen Y position of the pointer
  14409. * @return {number} Y position of the pointer
  14410. */
  14411. get: function () {
  14412. return this._pointerY;
  14413. },
  14414. enumerable: true,
  14415. configurable: true
  14416. });
  14417. Scene.prototype.getCachedMaterial = function () {
  14418. return this._cachedMaterial;
  14419. };
  14420. Scene.prototype.getBoundingBoxRenderer = function () {
  14421. return this._boundingBoxRenderer;
  14422. };
  14423. Scene.prototype.getOutlineRenderer = function () {
  14424. return this._outlineRenderer;
  14425. };
  14426. Scene.prototype.getEngine = function () {
  14427. return this._engine;
  14428. };
  14429. Scene.prototype.getTotalVertices = function () {
  14430. return this._totalVertices;
  14431. };
  14432. Scene.prototype.getActiveIndices = function () {
  14433. return this._activeIndices;
  14434. };
  14435. Scene.prototype.getActiveParticles = function () {
  14436. return this._activeParticles;
  14437. };
  14438. Scene.prototype.getActiveBones = function () {
  14439. return this._activeBones;
  14440. };
  14441. // Stats
  14442. Scene.prototype.getLastFrameDuration = function () {
  14443. return this._lastFrameDuration;
  14444. };
  14445. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14446. return this._evaluateActiveMeshesDuration;
  14447. };
  14448. Scene.prototype.getActiveMeshes = function () {
  14449. return this._activeMeshes;
  14450. };
  14451. Scene.prototype.getRenderTargetsDuration = function () {
  14452. return this._renderTargetsDuration;
  14453. };
  14454. Scene.prototype.getRenderDuration = function () {
  14455. return this._renderDuration;
  14456. };
  14457. Scene.prototype.getParticlesDuration = function () {
  14458. return this._particlesDuration;
  14459. };
  14460. Scene.prototype.getSpritesDuration = function () {
  14461. return this._spritesDuration;
  14462. };
  14463. Scene.prototype.getAnimationRatio = function () {
  14464. return this._animationRatio;
  14465. };
  14466. Scene.prototype.getRenderId = function () {
  14467. return this._renderId;
  14468. };
  14469. Scene.prototype.incrementRenderId = function () {
  14470. this._renderId++;
  14471. };
  14472. Scene.prototype._updatePointerPosition = function (evt) {
  14473. var canvasRect = this._engine.getRenderingCanvasClientRect();
  14474. this._pointerX = evt.clientX - canvasRect.left;
  14475. this._pointerY = evt.clientY - canvasRect.top;
  14476. this._unTranslatedPointerX = this._pointerX;
  14477. this._unTranslatedPointerY = this._pointerY;
  14478. if (this.cameraToUseForPointers) {
  14479. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  14480. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  14481. }
  14482. };
  14483. // Pointers handling
  14484. /**
  14485. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  14486. * @param attachUp defines if you want to attach events to pointerup
  14487. * @param attachDown defines if you want to attach events to pointerdown
  14488. * @param attachMove defines if you want to attach events to pointermove
  14489. */
  14490. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  14491. var _this = this;
  14492. if (attachUp === void 0) { attachUp = true; }
  14493. if (attachDown === void 0) { attachDown = true; }
  14494. if (attachMove === void 0) { attachMove = true; }
  14495. var spritePredicate = function (sprite) {
  14496. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  14497. };
  14498. this._onPointerMove = function (evt) {
  14499. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14500. return;
  14501. }
  14502. var canvas = _this._engine.getRenderingCanvas();
  14503. _this._updatePointerPosition(evt);
  14504. if (!_this.pointerMovePredicate) {
  14505. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  14506. }
  14507. // Meshes
  14508. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  14509. if (pickResult.hit && pickResult.pickedMesh) {
  14510. _this.setPointerOverSprite(null);
  14511. _this.setPointerOverMesh(pickResult.pickedMesh);
  14512. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  14513. canvas.style.cursor = "pointer";
  14514. }
  14515. else {
  14516. canvas.style.cursor = "";
  14517. }
  14518. }
  14519. else {
  14520. _this.setPointerOverMesh(null);
  14521. // Sprites
  14522. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14523. if (pickResult.hit && pickResult.pickedSprite) {
  14524. canvas.style.cursor = "pointer";
  14525. _this.setPointerOverSprite(pickResult.pickedSprite);
  14526. }
  14527. else {
  14528. _this.setPointerOverSprite(null);
  14529. // Restore pointer
  14530. canvas.style.cursor = "";
  14531. }
  14532. }
  14533. if (_this.onPointerMove) {
  14534. _this.onPointerMove(evt, pickResult);
  14535. }
  14536. if (_this.onPointerObservable.hasObservers()) {
  14537. var type = evt.type === "mousewheel" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  14538. var pi = new PointerInfo(type, evt, pickResult);
  14539. _this.onPointerObservable.notifyObservers(pi, type);
  14540. }
  14541. };
  14542. this._onPointerDown = function (evt) {
  14543. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14544. return;
  14545. }
  14546. _this._updatePointerPosition(evt);
  14547. _this._startingPointerPosition.x = _this._pointerX;
  14548. _this._startingPointerPosition.y = _this._pointerY;
  14549. _this._startingPointerTime = new Date().getTime();
  14550. if (!_this.pointerDownPredicate) {
  14551. _this.pointerDownPredicate = function (mesh) {
  14552. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  14553. };
  14554. }
  14555. // Meshes
  14556. _this._pickedDownMesh = null;
  14557. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  14558. if (pickResult.hit && pickResult.pickedMesh) {
  14559. if (pickResult.pickedMesh.actionManager) {
  14560. _this._pickedDownMesh = pickResult.pickedMesh;
  14561. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  14562. switch (evt.button) {
  14563. case 0:
  14564. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14565. break;
  14566. case 1:
  14567. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14568. break;
  14569. case 2:
  14570. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14571. break;
  14572. }
  14573. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14574. }
  14575. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  14576. var that = _this;
  14577. window.setTimeout(function () {
  14578. 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);
  14579. if (pickResult.hit && pickResult.pickedMesh) {
  14580. if (pickResult.pickedMesh.actionManager) {
  14581. 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)) {
  14582. that._startingPointerTime = 0;
  14583. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14584. }
  14585. }
  14586. }
  14587. }, BABYLON.ActionManager.LongPressDelay);
  14588. }
  14589. }
  14590. }
  14591. if (_this.onPointerDown) {
  14592. _this.onPointerDown(evt, pickResult);
  14593. }
  14594. if (_this.onPointerObservable.hasObservers()) {
  14595. var type = PointerEventTypes.POINTERDOWN;
  14596. var pi = new PointerInfo(type, evt, pickResult);
  14597. _this.onPointerObservable.notifyObservers(pi, type);
  14598. }
  14599. // Sprites
  14600. _this._pickedDownSprite = null;
  14601. if (_this.spriteManagers.length > 0) {
  14602. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14603. if (pickResult.hit && pickResult.pickedSprite) {
  14604. if (pickResult.pickedSprite.actionManager) {
  14605. _this._pickedDownSprite = pickResult.pickedSprite;
  14606. switch (evt.button) {
  14607. case 0:
  14608. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14609. break;
  14610. case 1:
  14611. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14612. break;
  14613. case 2:
  14614. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14615. break;
  14616. }
  14617. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14618. }
  14619. }
  14620. }
  14621. };
  14622. this._onPointerUp = function (evt) {
  14623. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14624. return;
  14625. }
  14626. _this._updatePointerPosition(evt);
  14627. if (!_this.pointerUpPredicate) {
  14628. _this.pointerUpPredicate = function (mesh) {
  14629. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14630. };
  14631. }
  14632. // Meshes
  14633. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14634. if (pickResult.hit && pickResult.pickedMesh) {
  14635. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14636. if (_this.onPointerPick) {
  14637. _this.onPointerPick(evt, pickResult);
  14638. }
  14639. if (_this.onPointerObservable.hasObservers()) {
  14640. var type = PointerEventTypes.POINTERPICK;
  14641. var pi = new PointerInfo(type, evt, pickResult);
  14642. _this.onPointerObservable.notifyObservers(pi, type);
  14643. }
  14644. }
  14645. if (pickResult.pickedMesh.actionManager) {
  14646. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14647. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14648. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14649. }
  14650. }
  14651. }
  14652. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14653. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14654. }
  14655. if (_this.onPointerUp) {
  14656. _this.onPointerUp(evt, pickResult);
  14657. }
  14658. if (_this.onPointerObservable.hasObservers()) {
  14659. var type = PointerEventTypes.POINTERUP;
  14660. var pi = new PointerInfo(type, evt, pickResult);
  14661. _this.onPointerObservable.notifyObservers(pi, type);
  14662. }
  14663. _this._startingPointerTime = 0;
  14664. // Sprites
  14665. if (_this.spriteManagers.length > 0) {
  14666. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14667. if (pickResult.hit && pickResult.pickedSprite) {
  14668. if (pickResult.pickedSprite.actionManager) {
  14669. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14670. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14671. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14672. }
  14673. }
  14674. }
  14675. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14676. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14677. }
  14678. }
  14679. };
  14680. this._onKeyDown = function (evt) {
  14681. if (_this.actionManager) {
  14682. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14683. }
  14684. };
  14685. this._onKeyUp = function (evt) {
  14686. if (_this.actionManager) {
  14687. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14688. }
  14689. };
  14690. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14691. if (attachMove) {
  14692. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14693. // Wheel
  14694. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14695. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14696. }
  14697. if (attachDown) {
  14698. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14699. }
  14700. if (attachUp) {
  14701. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14702. }
  14703. BABYLON.Tools.RegisterTopRootEvents([
  14704. { name: "keydown", handler: this._onKeyDown },
  14705. { name: "keyup", handler: this._onKeyUp }
  14706. ]);
  14707. };
  14708. Scene.prototype.detachControl = function () {
  14709. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14710. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14711. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14712. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14713. // Wheel
  14714. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14715. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14716. BABYLON.Tools.UnregisterTopRootEvents([
  14717. { name: "keydown", handler: this._onKeyDown },
  14718. { name: "keyup", handler: this._onKeyUp }
  14719. ]);
  14720. };
  14721. // Ready
  14722. Scene.prototype.isReady = function () {
  14723. if (this._pendingData.length > 0) {
  14724. return false;
  14725. }
  14726. var index;
  14727. for (index = 0; index < this._geometries.length; index++) {
  14728. var geometry = this._geometries[index];
  14729. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14730. return false;
  14731. }
  14732. }
  14733. for (index = 0; index < this.meshes.length; index++) {
  14734. var mesh = this.meshes[index];
  14735. if (!mesh.isReady()) {
  14736. return false;
  14737. }
  14738. var mat = mesh.material;
  14739. if (mat) {
  14740. if (!mat.isReady(mesh)) {
  14741. return false;
  14742. }
  14743. }
  14744. }
  14745. return true;
  14746. };
  14747. Scene.prototype.resetCachedMaterial = function () {
  14748. this._cachedMaterial = null;
  14749. };
  14750. Scene.prototype.registerBeforeRender = function (func) {
  14751. this.onBeforeRenderObservable.add(func);
  14752. };
  14753. Scene.prototype.unregisterBeforeRender = function (func) {
  14754. this.onBeforeRenderObservable.removeCallback(func);
  14755. };
  14756. Scene.prototype.registerAfterRender = function (func) {
  14757. this.onAfterRenderObservable.add(func);
  14758. };
  14759. Scene.prototype.unregisterAfterRender = function (func) {
  14760. this.onAfterRenderObservable.removeCallback(func);
  14761. };
  14762. Scene.prototype._addPendingData = function (data) {
  14763. this._pendingData.push(data);
  14764. };
  14765. Scene.prototype._removePendingData = function (data) {
  14766. var index = this._pendingData.indexOf(data);
  14767. if (index !== -1) {
  14768. this._pendingData.splice(index, 1);
  14769. }
  14770. };
  14771. Scene.prototype.getWaitingItemsCount = function () {
  14772. return this._pendingData.length;
  14773. };
  14774. /**
  14775. * Registers a function to be executed when the scene is ready.
  14776. * @param {Function} func - the function to be executed.
  14777. */
  14778. Scene.prototype.executeWhenReady = function (func) {
  14779. var _this = this;
  14780. this.onReadyObservable.add(func);
  14781. if (this._executeWhenReadyTimeoutId !== -1) {
  14782. return;
  14783. }
  14784. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14785. _this._checkIsReady();
  14786. }, 150);
  14787. };
  14788. Scene.prototype._checkIsReady = function () {
  14789. var _this = this;
  14790. if (this.isReady()) {
  14791. this.onReadyObservable.notifyObservers(this);
  14792. this.onReadyObservable.clear();
  14793. this._executeWhenReadyTimeoutId = -1;
  14794. return;
  14795. }
  14796. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14797. _this._checkIsReady();
  14798. }, 150);
  14799. };
  14800. // Animations
  14801. /**
  14802. * Will start the animation sequence of a given target
  14803. * @param target - the target
  14804. * @param {number} from - from which frame should animation start
  14805. * @param {number} to - till which frame should animation run.
  14806. * @param {boolean} [loop] - should the animation loop
  14807. * @param {number} [speedRatio] - the speed in which to run the animation
  14808. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14809. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14810. * @return {BABYLON.Animatable} the animatable object created for this animation
  14811. * @see BABYLON.Animatable
  14812. * @see http://doc.babylonjs.com/page.php?p=22081
  14813. */
  14814. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14815. if (speedRatio === void 0) { speedRatio = 1.0; }
  14816. this.stopAnimation(target);
  14817. if (!animatable) {
  14818. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14819. }
  14820. // Local animations
  14821. if (target.animations) {
  14822. animatable.appendAnimations(target, target.animations);
  14823. }
  14824. // Children animations
  14825. if (target.getAnimatables) {
  14826. var animatables = target.getAnimatables();
  14827. for (var index = 0; index < animatables.length; index++) {
  14828. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14829. }
  14830. }
  14831. animatable.reset();
  14832. return animatable;
  14833. };
  14834. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14835. if (speedRatio === undefined) {
  14836. speedRatio = 1.0;
  14837. }
  14838. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14839. return animatable;
  14840. };
  14841. Scene.prototype.getAnimatableByTarget = function (target) {
  14842. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14843. if (this._activeAnimatables[index].target === target) {
  14844. return this._activeAnimatables[index];
  14845. }
  14846. }
  14847. return null;
  14848. };
  14849. Object.defineProperty(Scene.prototype, "Animatables", {
  14850. get: function () {
  14851. return this._activeAnimatables;
  14852. },
  14853. enumerable: true,
  14854. configurable: true
  14855. });
  14856. /**
  14857. * Will stop the animation of the given target
  14858. * @param target - the target
  14859. * @see beginAnimation
  14860. */
  14861. Scene.prototype.stopAnimation = function (target) {
  14862. var animatable = this.getAnimatableByTarget(target);
  14863. if (animatable) {
  14864. animatable.stop();
  14865. }
  14866. };
  14867. Scene.prototype._animate = function () {
  14868. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14869. return;
  14870. }
  14871. if (!this._animationStartDate) {
  14872. if (this._pendingData.length > 0) {
  14873. return;
  14874. }
  14875. this._animationStartDate = BABYLON.Tools.Now;
  14876. }
  14877. // Getting time
  14878. var now = BABYLON.Tools.Now;
  14879. var delay = now - this._animationStartDate;
  14880. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14881. this._activeAnimatables[index]._animate(delay);
  14882. }
  14883. };
  14884. // Matrix
  14885. Scene.prototype.getViewMatrix = function () {
  14886. return this._viewMatrix;
  14887. };
  14888. Scene.prototype.getProjectionMatrix = function () {
  14889. return this._projectionMatrix;
  14890. };
  14891. Scene.prototype.getTransformMatrix = function () {
  14892. return this._transformMatrix;
  14893. };
  14894. Scene.prototype.setTransformMatrix = function (view, projection) {
  14895. this._viewMatrix = view;
  14896. this._projectionMatrix = projection;
  14897. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14898. };
  14899. // Methods
  14900. Scene.prototype.addMesh = function (newMesh) {
  14901. newMesh.uniqueId = this._uniqueIdCounter++;
  14902. var position = this.meshes.push(newMesh);
  14903. //notify the collision coordinator
  14904. this.collisionCoordinator.onMeshAdded(newMesh);
  14905. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  14906. };
  14907. Scene.prototype.removeMesh = function (toRemove) {
  14908. var index = this.meshes.indexOf(toRemove);
  14909. if (index !== -1) {
  14910. // Remove from the scene if mesh found
  14911. this.meshes.splice(index, 1);
  14912. }
  14913. //notify the collision coordinator
  14914. this.collisionCoordinator.onMeshRemoved(toRemove);
  14915. this.onMeshRemovedObservable.notifyObservers(toRemove);
  14916. return index;
  14917. };
  14918. Scene.prototype.removeSkeleton = function (toRemove) {
  14919. var index = this.skeletons.indexOf(toRemove);
  14920. if (index !== -1) {
  14921. // Remove from the scene if mesh found
  14922. this.skeletons.splice(index, 1);
  14923. }
  14924. return index;
  14925. };
  14926. Scene.prototype.removeLight = function (toRemove) {
  14927. var index = this.lights.indexOf(toRemove);
  14928. if (index !== -1) {
  14929. // Remove from the scene if mesh found
  14930. this.lights.splice(index, 1);
  14931. }
  14932. this.onLightRemovedObservable.notifyObservers(toRemove);
  14933. return index;
  14934. };
  14935. Scene.prototype.removeCamera = function (toRemove) {
  14936. var index = this.cameras.indexOf(toRemove);
  14937. if (index !== -1) {
  14938. // Remove from the scene if mesh found
  14939. this.cameras.splice(index, 1);
  14940. }
  14941. // Remove from activeCameras
  14942. var index2 = this.activeCameras.indexOf(toRemove);
  14943. if (index2 !== -1) {
  14944. // Remove from the scene if mesh found
  14945. this.activeCameras.splice(index2, 1);
  14946. }
  14947. // Reset the activeCamera
  14948. if (this.activeCamera === toRemove) {
  14949. if (this.cameras.length > 0) {
  14950. this.activeCamera = this.cameras[0];
  14951. }
  14952. else {
  14953. this.activeCamera = null;
  14954. }
  14955. }
  14956. this.onCameraRemovedObservable.notifyObservers(toRemove);
  14957. return index;
  14958. };
  14959. Scene.prototype.addLight = function (newLight) {
  14960. newLight.uniqueId = this._uniqueIdCounter++;
  14961. var position = this.lights.push(newLight);
  14962. this.onNewLightAddedObservable.notifyObservers(newLight);
  14963. };
  14964. Scene.prototype.addCamera = function (newCamera) {
  14965. newCamera.uniqueId = this._uniqueIdCounter++;
  14966. var position = this.cameras.push(newCamera);
  14967. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  14968. };
  14969. /**
  14970. * Switch active camera
  14971. * @param {Camera} newCamera - new active camera
  14972. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  14973. */
  14974. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  14975. if (attachControl === void 0) { attachControl = true; }
  14976. var canvas = this._engine.getRenderingCanvas();
  14977. this.activeCamera.detachControl(canvas);
  14978. this.activeCamera = newCamera;
  14979. if (attachControl) {
  14980. newCamera.attachControl(canvas);
  14981. }
  14982. };
  14983. /**
  14984. * sets the active camera of the scene using its ID
  14985. * @param {string} id - the camera's ID
  14986. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14987. * @see activeCamera
  14988. */
  14989. Scene.prototype.setActiveCameraByID = function (id) {
  14990. var camera = this.getCameraByID(id);
  14991. if (camera) {
  14992. this.activeCamera = camera;
  14993. return camera;
  14994. }
  14995. return null;
  14996. };
  14997. /**
  14998. * sets the active camera of the scene using its name
  14999. * @param {string} name - the camera's name
  15000. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15001. * @see activeCamera
  15002. */
  15003. Scene.prototype.setActiveCameraByName = function (name) {
  15004. var camera = this.getCameraByName(name);
  15005. if (camera) {
  15006. this.activeCamera = camera;
  15007. return camera;
  15008. }
  15009. return null;
  15010. };
  15011. /**
  15012. * get a material using its id
  15013. * @param {string} the material's ID
  15014. * @return {BABYLON.Material|null} the material or null if none found.
  15015. */
  15016. Scene.prototype.getMaterialByID = function (id) {
  15017. for (var index = 0; index < this.materials.length; index++) {
  15018. if (this.materials[index].id === id) {
  15019. return this.materials[index];
  15020. }
  15021. }
  15022. return null;
  15023. };
  15024. /**
  15025. * get a material using its name
  15026. * @param {string} the material's name
  15027. * @return {BABYLON.Material|null} the material or null if none found.
  15028. */
  15029. Scene.prototype.getMaterialByName = function (name) {
  15030. for (var index = 0; index < this.materials.length; index++) {
  15031. if (this.materials[index].name === name) {
  15032. return this.materials[index];
  15033. }
  15034. }
  15035. return null;
  15036. };
  15037. Scene.prototype.getLensFlareSystemByName = function (name) {
  15038. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15039. if (this.lensFlareSystems[index].name === name) {
  15040. return this.lensFlareSystems[index];
  15041. }
  15042. }
  15043. return null;
  15044. };
  15045. Scene.prototype.getLensFlareSystemByID = function (id) {
  15046. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15047. if (this.lensFlareSystems[index].id === id) {
  15048. return this.lensFlareSystems[index];
  15049. }
  15050. }
  15051. return null;
  15052. };
  15053. Scene.prototype.getCameraByID = function (id) {
  15054. for (var index = 0; index < this.cameras.length; index++) {
  15055. if (this.cameras[index].id === id) {
  15056. return this.cameras[index];
  15057. }
  15058. }
  15059. return null;
  15060. };
  15061. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15062. for (var index = 0; index < this.cameras.length; index++) {
  15063. if (this.cameras[index].uniqueId === uniqueId) {
  15064. return this.cameras[index];
  15065. }
  15066. }
  15067. return null;
  15068. };
  15069. /**
  15070. * get a camera using its name
  15071. * @param {string} the camera's name
  15072. * @return {BABYLON.Camera|null} the camera or null if none found.
  15073. */
  15074. Scene.prototype.getCameraByName = function (name) {
  15075. for (var index = 0; index < this.cameras.length; index++) {
  15076. if (this.cameras[index].name === name) {
  15077. return this.cameras[index];
  15078. }
  15079. }
  15080. return null;
  15081. };
  15082. /**
  15083. * get a bone using its id
  15084. * @param {string} the bone's id
  15085. * @return {BABYLON.Bone|null} the bone or null if not found
  15086. */
  15087. Scene.prototype.getBoneByID = function (id) {
  15088. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15089. var skeleton = this.skeletons[skeletonIndex];
  15090. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15091. if (skeleton.bones[boneIndex].id === id) {
  15092. return skeleton.bones[boneIndex];
  15093. }
  15094. }
  15095. }
  15096. return null;
  15097. };
  15098. /**
  15099. * get a bone using its id
  15100. * @param {string} the bone's name
  15101. * @return {BABYLON.Bone|null} the bone or null if not found
  15102. */
  15103. Scene.prototype.getBoneByName = function (name) {
  15104. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15105. var skeleton = this.skeletons[skeletonIndex];
  15106. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15107. if (skeleton.bones[boneIndex].name === name) {
  15108. return skeleton.bones[boneIndex];
  15109. }
  15110. }
  15111. }
  15112. return null;
  15113. };
  15114. /**
  15115. * get a light node using its name
  15116. * @param {string} the light's name
  15117. * @return {BABYLON.Light|null} the light or null if none found.
  15118. */
  15119. Scene.prototype.getLightByName = function (name) {
  15120. for (var index = 0; index < this.lights.length; index++) {
  15121. if (this.lights[index].name === name) {
  15122. return this.lights[index];
  15123. }
  15124. }
  15125. return null;
  15126. };
  15127. /**
  15128. * get a light node using its ID
  15129. * @param {string} the light's id
  15130. * @return {BABYLON.Light|null} the light or null if none found.
  15131. */
  15132. Scene.prototype.getLightByID = function (id) {
  15133. for (var index = 0; index < this.lights.length; index++) {
  15134. if (this.lights[index].id === id) {
  15135. return this.lights[index];
  15136. }
  15137. }
  15138. return null;
  15139. };
  15140. /**
  15141. * get a light node using its scene-generated unique ID
  15142. * @param {number} the light's unique id
  15143. * @return {BABYLON.Light|null} the light or null if none found.
  15144. */
  15145. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15146. for (var index = 0; index < this.lights.length; index++) {
  15147. if (this.lights[index].uniqueId === uniqueId) {
  15148. return this.lights[index];
  15149. }
  15150. }
  15151. return null;
  15152. };
  15153. /**
  15154. * get a particle system by id
  15155. * @param id {number} the particle system id
  15156. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15157. */
  15158. Scene.prototype.getParticleSystemByID = function (id) {
  15159. for (var index = 0; index < this.particleSystems.length; index++) {
  15160. if (this.particleSystems[index].id === id) {
  15161. return this.particleSystems[index];
  15162. }
  15163. }
  15164. return null;
  15165. };
  15166. /**
  15167. * get a geometry using its ID
  15168. * @param {string} the geometry's id
  15169. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15170. */
  15171. Scene.prototype.getGeometryByID = function (id) {
  15172. for (var index = 0; index < this._geometries.length; index++) {
  15173. if (this._geometries[index].id === id) {
  15174. return this._geometries[index];
  15175. }
  15176. }
  15177. return null;
  15178. };
  15179. /**
  15180. * add a new geometry to this scene.
  15181. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15182. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15183. * @return {boolean} was the geometry added or not
  15184. */
  15185. Scene.prototype.pushGeometry = function (geometry, force) {
  15186. if (!force && this.getGeometryByID(geometry.id)) {
  15187. return false;
  15188. }
  15189. this._geometries.push(geometry);
  15190. //notify the collision coordinator
  15191. this.collisionCoordinator.onGeometryAdded(geometry);
  15192. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15193. return true;
  15194. };
  15195. /**
  15196. * Removes an existing geometry
  15197. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15198. * @return {boolean} was the geometry removed or not
  15199. */
  15200. Scene.prototype.removeGeometry = function (geometry) {
  15201. var index = this._geometries.indexOf(geometry);
  15202. if (index > -1) {
  15203. this._geometries.splice(index, 1);
  15204. //notify the collision coordinator
  15205. this.collisionCoordinator.onGeometryDeleted(geometry);
  15206. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15207. return true;
  15208. }
  15209. return false;
  15210. };
  15211. Scene.prototype.getGeometries = function () {
  15212. return this._geometries;
  15213. };
  15214. /**
  15215. * Get the first added mesh found of a given ID
  15216. * @param {string} id - the id to search for
  15217. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15218. */
  15219. Scene.prototype.getMeshByID = function (id) {
  15220. for (var index = 0; index < this.meshes.length; index++) {
  15221. if (this.meshes[index].id === id) {
  15222. return this.meshes[index];
  15223. }
  15224. }
  15225. return null;
  15226. };
  15227. /**
  15228. * Get a mesh with its auto-generated unique id
  15229. * @param {number} uniqueId - the unique id to search for
  15230. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15231. */
  15232. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15233. for (var index = 0; index < this.meshes.length; index++) {
  15234. if (this.meshes[index].uniqueId === uniqueId) {
  15235. return this.meshes[index];
  15236. }
  15237. }
  15238. return null;
  15239. };
  15240. /**
  15241. * Get a the last added mesh found of a given ID
  15242. * @param {string} id - the id to search for
  15243. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15244. */
  15245. Scene.prototype.getLastMeshByID = function (id) {
  15246. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15247. if (this.meshes[index].id === id) {
  15248. return this.meshes[index];
  15249. }
  15250. }
  15251. return null;
  15252. };
  15253. /**
  15254. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15255. * @param {string} id - the id to search for
  15256. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15257. */
  15258. Scene.prototype.getLastEntryByID = function (id) {
  15259. var index;
  15260. for (index = this.meshes.length - 1; index >= 0; index--) {
  15261. if (this.meshes[index].id === id) {
  15262. return this.meshes[index];
  15263. }
  15264. }
  15265. for (index = this.cameras.length - 1; index >= 0; index--) {
  15266. if (this.cameras[index].id === id) {
  15267. return this.cameras[index];
  15268. }
  15269. }
  15270. for (index = this.lights.length - 1; index >= 0; index--) {
  15271. if (this.lights[index].id === id) {
  15272. return this.lights[index];
  15273. }
  15274. }
  15275. return null;
  15276. };
  15277. Scene.prototype.getNodeByID = function (id) {
  15278. var mesh = this.getMeshByID(id);
  15279. if (mesh) {
  15280. return mesh;
  15281. }
  15282. var light = this.getLightByID(id);
  15283. if (light) {
  15284. return light;
  15285. }
  15286. var camera = this.getCameraByID(id);
  15287. if (camera) {
  15288. return camera;
  15289. }
  15290. var bone = this.getBoneByID(id);
  15291. return bone;
  15292. };
  15293. Scene.prototype.getNodeByName = function (name) {
  15294. var mesh = this.getMeshByName(name);
  15295. if (mesh) {
  15296. return mesh;
  15297. }
  15298. var light = this.getLightByName(name);
  15299. if (light) {
  15300. return light;
  15301. }
  15302. var camera = this.getCameraByName(name);
  15303. if (camera) {
  15304. return camera;
  15305. }
  15306. var bone = this.getBoneByName(name);
  15307. return bone;
  15308. };
  15309. Scene.prototype.getMeshByName = function (name) {
  15310. for (var index = 0; index < this.meshes.length; index++) {
  15311. if (this.meshes[index].name === name) {
  15312. return this.meshes[index];
  15313. }
  15314. }
  15315. return null;
  15316. };
  15317. Scene.prototype.getSoundByName = function (name) {
  15318. var index;
  15319. if (BABYLON.AudioEngine) {
  15320. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15321. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15322. return this.mainSoundTrack.soundCollection[index];
  15323. }
  15324. }
  15325. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15326. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15327. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15328. return this.soundTracks[sdIndex].soundCollection[index];
  15329. }
  15330. }
  15331. }
  15332. }
  15333. return null;
  15334. };
  15335. Scene.prototype.getLastSkeletonByID = function (id) {
  15336. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15337. if (this.skeletons[index].id === id) {
  15338. return this.skeletons[index];
  15339. }
  15340. }
  15341. return null;
  15342. };
  15343. Scene.prototype.getSkeletonById = function (id) {
  15344. for (var index = 0; index < this.skeletons.length; index++) {
  15345. if (this.skeletons[index].id === id) {
  15346. return this.skeletons[index];
  15347. }
  15348. }
  15349. return null;
  15350. };
  15351. Scene.prototype.getSkeletonByName = function (name) {
  15352. for (var index = 0; index < this.skeletons.length; index++) {
  15353. if (this.skeletons[index].name === name) {
  15354. return this.skeletons[index];
  15355. }
  15356. }
  15357. return null;
  15358. };
  15359. Scene.prototype.isActiveMesh = function (mesh) {
  15360. return (this._activeMeshes.indexOf(mesh) !== -1);
  15361. };
  15362. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15363. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15364. var material = subMesh.getMaterial();
  15365. if (mesh.showSubMeshesBoundingBox) {
  15366. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15367. }
  15368. if (material) {
  15369. // Render targets
  15370. if (material.getRenderTargetTextures) {
  15371. if (this._processedMaterials.indexOf(material) === -1) {
  15372. this._processedMaterials.push(material);
  15373. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15374. }
  15375. }
  15376. // Dispatch
  15377. this._activeIndices += subMesh.indexCount;
  15378. this._renderingManager.dispatch(subMesh);
  15379. }
  15380. }
  15381. };
  15382. Scene.prototype._isInIntermediateRendering = function () {
  15383. return this._intermediateRendering;
  15384. };
  15385. Scene.prototype._evaluateActiveMeshes = function () {
  15386. this.activeCamera._activeMeshes.reset();
  15387. this._activeMeshes.reset();
  15388. this._renderingManager.reset();
  15389. this._processedMaterials.reset();
  15390. this._activeParticleSystems.reset();
  15391. this._activeSkeletons.reset();
  15392. this._softwareSkinnedMeshes.reset();
  15393. this._boundingBoxRenderer.reset();
  15394. this._edgesRenderers.reset();
  15395. if (!this._frustumPlanes) {
  15396. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15397. }
  15398. else {
  15399. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15400. }
  15401. // Meshes
  15402. var meshes;
  15403. var len;
  15404. if (this._selectionOctree) {
  15405. var selection = this._selectionOctree.select(this._frustumPlanes);
  15406. meshes = selection.data;
  15407. len = selection.length;
  15408. }
  15409. else {
  15410. len = this.meshes.length;
  15411. meshes = this.meshes;
  15412. }
  15413. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15414. var mesh = meshes[meshIndex];
  15415. if (mesh.isBlocked) {
  15416. continue;
  15417. }
  15418. this._totalVertices += mesh.getTotalVertices();
  15419. if (!mesh.isReady() || !mesh.isEnabled()) {
  15420. continue;
  15421. }
  15422. mesh.computeWorldMatrix();
  15423. // Intersections
  15424. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15425. this._meshesForIntersections.pushNoDuplicate(mesh);
  15426. }
  15427. // Switch to current LOD
  15428. var meshLOD = mesh.getLOD(this.activeCamera);
  15429. if (!meshLOD) {
  15430. continue;
  15431. }
  15432. mesh._preActivate();
  15433. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15434. this._activeMeshes.push(mesh);
  15435. this.activeCamera._activeMeshes.push(mesh);
  15436. mesh._activate(this._renderId);
  15437. this._activeMesh(meshLOD);
  15438. }
  15439. }
  15440. // Particle systems
  15441. var beforeParticlesDate = BABYLON.Tools.Now;
  15442. if (this.particlesEnabled) {
  15443. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  15444. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  15445. var particleSystem = this.particleSystems[particleIndex];
  15446. if (!particleSystem.isStarted()) {
  15447. continue;
  15448. }
  15449. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  15450. this._activeParticleSystems.push(particleSystem);
  15451. particleSystem.animate();
  15452. }
  15453. }
  15454. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  15455. }
  15456. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  15457. };
  15458. Scene.prototype._activeMesh = function (mesh) {
  15459. if (mesh.skeleton && this.skeletonsEnabled) {
  15460. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  15461. if (!mesh.computeBonesUsingShaders) {
  15462. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  15463. }
  15464. }
  15465. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  15466. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  15467. }
  15468. if (mesh._edgesRenderer) {
  15469. this._edgesRenderers.push(mesh._edgesRenderer);
  15470. }
  15471. if (mesh && mesh.subMeshes) {
  15472. // Submeshes Octrees
  15473. var len;
  15474. var subMeshes;
  15475. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  15476. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  15477. len = intersections.length;
  15478. subMeshes = intersections.data;
  15479. }
  15480. else {
  15481. subMeshes = mesh.subMeshes;
  15482. len = subMeshes.length;
  15483. }
  15484. for (var subIndex = 0; subIndex < len; subIndex++) {
  15485. var subMesh = subMeshes[subIndex];
  15486. this._evaluateSubMesh(subMesh, mesh);
  15487. }
  15488. }
  15489. };
  15490. Scene.prototype.updateTransformMatrix = function (force) {
  15491. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  15492. };
  15493. Scene.prototype._renderForCamera = function (camera) {
  15494. var engine = this._engine;
  15495. this.activeCamera = camera;
  15496. if (!this.activeCamera)
  15497. throw new Error("Active camera not set");
  15498. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15499. // Viewport
  15500. engine.setViewport(this.activeCamera.viewport);
  15501. // Camera
  15502. this.resetCachedMaterial();
  15503. this._renderId++;
  15504. this.updateTransformMatrix();
  15505. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  15506. // Meshes
  15507. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  15508. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  15509. this._evaluateActiveMeshes();
  15510. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  15511. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  15512. // Skeletons
  15513. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  15514. var skeleton = this._activeSkeletons.data[skeletonIndex];
  15515. skeleton.prepare();
  15516. }
  15517. // Software skinning
  15518. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  15519. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  15520. mesh.applySkeleton(mesh.skeleton);
  15521. }
  15522. // Render targets
  15523. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15524. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  15525. this._intermediateRendering = true;
  15526. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15527. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  15528. var renderTarget = this._renderTargets.data[renderIndex];
  15529. if (renderTarget._shouldRender()) {
  15530. this._renderId++;
  15531. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  15532. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  15533. }
  15534. }
  15535. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15536. this._intermediateRendering = false;
  15537. this._renderId++;
  15538. engine.restoreDefaultFramebuffer(); // Restore back buffer
  15539. }
  15540. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15541. // Prepare Frame
  15542. this.postProcessManager._prepareFrame();
  15543. var beforeRenderDate = BABYLON.Tools.Now;
  15544. // Backgrounds
  15545. var layerIndex;
  15546. var layer;
  15547. if (this.layers.length) {
  15548. engine.setDepthBuffer(false);
  15549. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15550. layer = this.layers[layerIndex];
  15551. if (layer.isBackground) {
  15552. layer.render();
  15553. }
  15554. }
  15555. engine.setDepthBuffer(true);
  15556. }
  15557. // Render
  15558. BABYLON.Tools.StartPerformanceCounter("Main render");
  15559. this._renderingManager.render(null, null, true, true);
  15560. BABYLON.Tools.EndPerformanceCounter("Main render");
  15561. // Bounding boxes
  15562. this._boundingBoxRenderer.render();
  15563. // Edges
  15564. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15565. this._edgesRenderers.data[edgesRendererIndex].render();
  15566. }
  15567. // Lens flares
  15568. if (this.lensFlaresEnabled) {
  15569. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15570. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  15571. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  15572. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  15573. lensFlareSystem.render();
  15574. }
  15575. }
  15576. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15577. }
  15578. // Foregrounds
  15579. if (this.layers.length) {
  15580. engine.setDepthBuffer(false);
  15581. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15582. layer = this.layers[layerIndex];
  15583. if (!layer.isBackground) {
  15584. layer.render();
  15585. }
  15586. }
  15587. engine.setDepthBuffer(true);
  15588. }
  15589. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  15590. // Finalize frame
  15591. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  15592. // Update camera
  15593. this.activeCamera._updateFromScene();
  15594. // Reset some special arrays
  15595. this._renderTargets.reset();
  15596. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  15597. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15598. };
  15599. Scene.prototype._processSubCameras = function (camera) {
  15600. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  15601. this._renderForCamera(camera);
  15602. return;
  15603. }
  15604. // rig cameras
  15605. for (var index = 0; index < camera._rigCameras.length; index++) {
  15606. this._renderForCamera(camera._rigCameras[index]);
  15607. }
  15608. this.activeCamera = camera;
  15609. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  15610. // Update camera
  15611. this.activeCamera._updateFromScene();
  15612. };
  15613. Scene.prototype._checkIntersections = function () {
  15614. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  15615. var sourceMesh = this._meshesForIntersections.data[index];
  15616. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  15617. var action = sourceMesh.actionManager.actions[actionIndex];
  15618. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15619. var parameters = action.getTriggerParameter();
  15620. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  15621. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  15622. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15623. if (areIntersecting && currentIntersectionInProgress === -1) {
  15624. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15625. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15626. sourceMesh._intersectionsInProgress.push(otherMesh);
  15627. }
  15628. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15629. sourceMesh._intersectionsInProgress.push(otherMesh);
  15630. }
  15631. }
  15632. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15633. //They intersected, and now they don't.
  15634. //is this trigger an exit trigger? execute an event.
  15635. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15636. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15637. }
  15638. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15639. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15640. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15641. }
  15642. }
  15643. }
  15644. }
  15645. }
  15646. };
  15647. Scene.prototype.render = function () {
  15648. var startDate = BABYLON.Tools.Now;
  15649. this._particlesDuration = 0;
  15650. this._spritesDuration = 0;
  15651. this._activeParticles = 0;
  15652. this._renderDuration = 0;
  15653. this._renderTargetsDuration = 0;
  15654. this._evaluateActiveMeshesDuration = 0;
  15655. this._totalVertices = 0;
  15656. this._activeIndices = 0;
  15657. this._activeBones = 0;
  15658. this.getEngine().resetDrawCalls();
  15659. this._meshesForIntersections.reset();
  15660. this.resetCachedMaterial();
  15661. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15662. // Actions
  15663. if (this.actionManager) {
  15664. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15665. }
  15666. //Simplification Queue
  15667. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15668. this.simplificationQueue.executeNext();
  15669. }
  15670. // Animations
  15671. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15672. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15673. this._animate();
  15674. // Physics
  15675. if (this._physicsEngine) {
  15676. BABYLON.Tools.StartPerformanceCounter("Physics");
  15677. this._physicsEngine._step(deltaTime / 1000.0);
  15678. BABYLON.Tools.EndPerformanceCounter("Physics");
  15679. }
  15680. // Before render
  15681. this.onBeforeRenderObservable.notifyObservers(this);
  15682. // Customs render targets
  15683. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15684. var engine = this.getEngine();
  15685. var currentActiveCamera = this.activeCamera;
  15686. if (this.renderTargetsEnabled) {
  15687. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15688. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15689. var renderTarget = this.customRenderTargets[customIndex];
  15690. if (renderTarget._shouldRender()) {
  15691. this._renderId++;
  15692. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15693. if (!this.activeCamera)
  15694. throw new Error("Active camera not set");
  15695. // Viewport
  15696. engine.setViewport(this.activeCamera.viewport);
  15697. // Camera
  15698. this.updateTransformMatrix();
  15699. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15700. }
  15701. }
  15702. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15703. this._renderId++;
  15704. }
  15705. if (this.customRenderTargets.length > 0) {
  15706. engine.restoreDefaultFramebuffer();
  15707. }
  15708. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15709. this.activeCamera = currentActiveCamera;
  15710. // Procedural textures
  15711. if (this.proceduralTexturesEnabled) {
  15712. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15713. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15714. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15715. if (proceduralTexture._shouldRender()) {
  15716. proceduralTexture.render();
  15717. }
  15718. }
  15719. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15720. }
  15721. // Clear
  15722. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15723. // Shadows
  15724. if (this.shadowsEnabled) {
  15725. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15726. var light = this.lights[lightIndex];
  15727. var shadowGenerator = light.getShadowGenerator();
  15728. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15729. this._renderTargets.push(shadowGenerator.getShadowMap());
  15730. }
  15731. }
  15732. }
  15733. // Depth renderer
  15734. if (this._depthRenderer) {
  15735. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15736. }
  15737. // RenderPipeline
  15738. this.postProcessRenderPipelineManager.update();
  15739. // Multi-cameras?
  15740. if (this.activeCameras.length > 0) {
  15741. var currentRenderId = this._renderId;
  15742. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15743. this._renderId = currentRenderId;
  15744. if (cameraIndex > 0) {
  15745. this._engine.clear(0, false, true);
  15746. }
  15747. this._processSubCameras(this.activeCameras[cameraIndex]);
  15748. }
  15749. }
  15750. else {
  15751. if (!this.activeCamera) {
  15752. throw new Error("No camera defined");
  15753. }
  15754. this._processSubCameras(this.activeCamera);
  15755. }
  15756. // Intersection checks
  15757. this._checkIntersections();
  15758. // Update the audio listener attached to the camera
  15759. if (BABYLON.AudioEngine) {
  15760. this._updateAudioParameters();
  15761. }
  15762. // After render
  15763. if (this.afterRender) {
  15764. this.afterRender();
  15765. }
  15766. this.onAfterRenderObservable.notifyObservers(this);
  15767. // Cleaning
  15768. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15769. this._toBeDisposed.data[index].dispose();
  15770. this._toBeDisposed[index] = null;
  15771. }
  15772. this._toBeDisposed.reset();
  15773. if (this.dumpNextRenderTargets) {
  15774. this.dumpNextRenderTargets = false;
  15775. }
  15776. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15777. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15778. };
  15779. Scene.prototype._updateAudioParameters = function () {
  15780. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15781. return;
  15782. }
  15783. var listeningCamera;
  15784. var audioEngine = BABYLON.Engine.audioEngine;
  15785. if (this.activeCameras.length > 0) {
  15786. listeningCamera = this.activeCameras[0];
  15787. }
  15788. else {
  15789. listeningCamera = this.activeCamera;
  15790. }
  15791. if (listeningCamera && audioEngine.canUseWebAudio) {
  15792. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15793. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15794. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15795. cameraDirection.normalize();
  15796. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15797. var i;
  15798. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15799. var sound = this.mainSoundTrack.soundCollection[i];
  15800. if (sound.useCustomAttenuation) {
  15801. sound.updateDistanceFromListener();
  15802. }
  15803. }
  15804. for (i = 0; i < this.soundTracks.length; i++) {
  15805. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15806. sound = this.soundTracks[i].soundCollection[j];
  15807. if (sound.useCustomAttenuation) {
  15808. sound.updateDistanceFromListener();
  15809. }
  15810. }
  15811. }
  15812. }
  15813. };
  15814. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15815. // Audio
  15816. get: function () {
  15817. return this._audioEnabled;
  15818. },
  15819. set: function (value) {
  15820. this._audioEnabled = value;
  15821. if (BABYLON.AudioEngine) {
  15822. if (this._audioEnabled) {
  15823. this._enableAudio();
  15824. }
  15825. else {
  15826. this._disableAudio();
  15827. }
  15828. }
  15829. },
  15830. enumerable: true,
  15831. configurable: true
  15832. });
  15833. Scene.prototype._disableAudio = function () {
  15834. var i;
  15835. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15836. this.mainSoundTrack.soundCollection[i].pause();
  15837. }
  15838. for (i = 0; i < this.soundTracks.length; i++) {
  15839. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15840. this.soundTracks[i].soundCollection[j].pause();
  15841. }
  15842. }
  15843. };
  15844. Scene.prototype._enableAudio = function () {
  15845. var i;
  15846. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15847. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15848. this.mainSoundTrack.soundCollection[i].play();
  15849. }
  15850. }
  15851. for (i = 0; i < this.soundTracks.length; i++) {
  15852. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15853. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15854. this.soundTracks[i].soundCollection[j].play();
  15855. }
  15856. }
  15857. }
  15858. };
  15859. Object.defineProperty(Scene.prototype, "headphone", {
  15860. get: function () {
  15861. return this._headphone;
  15862. },
  15863. set: function (value) {
  15864. this._headphone = value;
  15865. if (BABYLON.AudioEngine) {
  15866. if (this._headphone) {
  15867. this._switchAudioModeForHeadphones();
  15868. }
  15869. else {
  15870. this._switchAudioModeForNormalSpeakers();
  15871. }
  15872. }
  15873. },
  15874. enumerable: true,
  15875. configurable: true
  15876. });
  15877. Scene.prototype._switchAudioModeForHeadphones = function () {
  15878. this.mainSoundTrack.switchPanningModelToHRTF();
  15879. for (var i = 0; i < this.soundTracks.length; i++) {
  15880. this.soundTracks[i].switchPanningModelToHRTF();
  15881. }
  15882. };
  15883. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  15884. this.mainSoundTrack.switchPanningModelToEqualPower();
  15885. for (var i = 0; i < this.soundTracks.length; i++) {
  15886. this.soundTracks[i].switchPanningModelToEqualPower();
  15887. }
  15888. };
  15889. Scene.prototype.enableDepthRenderer = function () {
  15890. if (this._depthRenderer) {
  15891. return this._depthRenderer;
  15892. }
  15893. this._depthRenderer = new BABYLON.DepthRenderer(this);
  15894. return this._depthRenderer;
  15895. };
  15896. Scene.prototype.disableDepthRenderer = function () {
  15897. if (!this._depthRenderer) {
  15898. return;
  15899. }
  15900. this._depthRenderer.dispose();
  15901. this._depthRenderer = null;
  15902. };
  15903. Scene.prototype.freezeMaterials = function () {
  15904. for (var i = 0; i < this.materials.length; i++) {
  15905. this.materials[i].freeze();
  15906. }
  15907. };
  15908. Scene.prototype.unfreezeMaterials = function () {
  15909. for (var i = 0; i < this.materials.length; i++) {
  15910. this.materials[i].unfreeze();
  15911. }
  15912. };
  15913. Scene.prototype.dispose = function () {
  15914. this.beforeRender = null;
  15915. this.afterRender = null;
  15916. this.skeletons = [];
  15917. this._boundingBoxRenderer.dispose();
  15918. if (this._depthRenderer) {
  15919. this._depthRenderer.dispose();
  15920. }
  15921. // Debug layer
  15922. this.debugLayer.hide();
  15923. // Events
  15924. if (this.onDispose) {
  15925. this.onDispose();
  15926. }
  15927. this.onBeforeRenderObservable.clear();
  15928. this.onAfterRenderObservable.clear();
  15929. this.detachControl();
  15930. // Release sounds & sounds tracks
  15931. if (BABYLON.AudioEngine) {
  15932. this.disposeSounds();
  15933. }
  15934. // Detach cameras
  15935. var canvas = this._engine.getRenderingCanvas();
  15936. var index;
  15937. for (index = 0; index < this.cameras.length; index++) {
  15938. this.cameras[index].detachControl(canvas);
  15939. }
  15940. // Release lights
  15941. while (this.lights.length) {
  15942. this.lights[0].dispose();
  15943. }
  15944. // Release meshes
  15945. while (this.meshes.length) {
  15946. this.meshes[0].dispose(true);
  15947. }
  15948. // Release cameras
  15949. while (this.cameras.length) {
  15950. this.cameras[0].dispose();
  15951. }
  15952. // Release materials
  15953. while (this.materials.length) {
  15954. this.materials[0].dispose();
  15955. }
  15956. // Release particles
  15957. while (this.particleSystems.length) {
  15958. this.particleSystems[0].dispose();
  15959. }
  15960. // Release sprites
  15961. while (this.spriteManagers.length) {
  15962. this.spriteManagers[0].dispose();
  15963. }
  15964. // Release layers
  15965. while (this.layers.length) {
  15966. this.layers[0].dispose();
  15967. }
  15968. // Release textures
  15969. while (this.textures.length) {
  15970. this.textures[0].dispose();
  15971. }
  15972. // Post-processes
  15973. this.postProcessManager.dispose();
  15974. // Physics
  15975. if (this._physicsEngine) {
  15976. this.disablePhysicsEngine();
  15977. }
  15978. // Remove from engine
  15979. index = this._engine.scenes.indexOf(this);
  15980. if (index > -1) {
  15981. this._engine.scenes.splice(index, 1);
  15982. }
  15983. this._engine.wipeCaches();
  15984. };
  15985. // Release sounds & sounds tracks
  15986. Scene.prototype.disposeSounds = function () {
  15987. this.mainSoundTrack.dispose();
  15988. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  15989. this.soundTracks[scIndex].dispose();
  15990. }
  15991. };
  15992. // Octrees
  15993. Scene.prototype.getWorldExtends = function () {
  15994. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15995. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15996. for (var index = 0; index < this.meshes.length; index++) {
  15997. var mesh = this.meshes[index];
  15998. mesh.computeWorldMatrix(true);
  15999. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16000. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16001. BABYLON.Tools.CheckExtends(minBox, min, max);
  16002. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16003. }
  16004. return {
  16005. min: min,
  16006. max: max
  16007. };
  16008. };
  16009. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16010. if (maxCapacity === void 0) { maxCapacity = 64; }
  16011. if (maxDepth === void 0) { maxDepth = 2; }
  16012. if (!this._selectionOctree) {
  16013. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16014. }
  16015. var worldExtends = this.getWorldExtends();
  16016. // Update octree
  16017. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16018. return this._selectionOctree;
  16019. };
  16020. // Picking
  16021. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16022. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16023. var engine = this._engine;
  16024. if (!camera) {
  16025. if (!this.activeCamera)
  16026. throw new Error("Active camera not set");
  16027. camera = this.activeCamera;
  16028. }
  16029. var cameraViewport = camera.viewport;
  16030. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16031. // Moving coordinates to local viewport world
  16032. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16033. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16034. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  16035. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  16036. };
  16037. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  16038. var engine = this._engine;
  16039. if (!camera) {
  16040. if (!this.activeCamera)
  16041. throw new Error("Active camera not set");
  16042. camera = this.activeCamera;
  16043. }
  16044. var cameraViewport = camera.viewport;
  16045. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16046. var identity = BABYLON.Matrix.Identity();
  16047. // Moving coordinates to local viewport world
  16048. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16049. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16050. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  16051. };
  16052. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  16053. var pickingInfo = null;
  16054. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  16055. var mesh = this.meshes[meshIndex];
  16056. if (predicate) {
  16057. if (!predicate(mesh)) {
  16058. continue;
  16059. }
  16060. }
  16061. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  16062. continue;
  16063. }
  16064. var world = mesh.getWorldMatrix();
  16065. var ray = rayFunction(world);
  16066. var result = mesh.intersects(ray, fastCheck);
  16067. if (!result || !result.hit)
  16068. continue;
  16069. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16070. continue;
  16071. pickingInfo = result;
  16072. if (fastCheck) {
  16073. break;
  16074. }
  16075. }
  16076. return pickingInfo || new BABYLON.PickingInfo();
  16077. };
  16078. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  16079. var pickingInfo = null;
  16080. camera = camera || this.activeCamera;
  16081. if (this.spriteManagers.length > 0) {
  16082. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  16083. var spriteManager = this.spriteManagers[spriteIndex];
  16084. if (!spriteManager.isPickable) {
  16085. continue;
  16086. }
  16087. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16088. if (!result || !result.hit)
  16089. continue;
  16090. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16091. continue;
  16092. pickingInfo = result;
  16093. if (fastCheck) {
  16094. break;
  16095. }
  16096. }
  16097. }
  16098. return pickingInfo || new BABYLON.PickingInfo();
  16099. };
  16100. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16101. var _this = this;
  16102. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16103. /// <param name="x">X position on screen</param>
  16104. /// <param name="y">Y position on screen</param>
  16105. /// <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>
  16106. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16107. /// <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>
  16108. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16109. };
  16110. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16111. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16112. /// <param name="x">X position on screen</param>
  16113. /// <param name="y">Y position on screen</param>
  16114. /// <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>
  16115. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16116. /// <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>
  16117. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16118. };
  16119. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16120. var _this = this;
  16121. return this._internalPick(function (world) {
  16122. if (!_this._pickWithRayInverseMatrix) {
  16123. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16124. }
  16125. world.invertToRef(_this._pickWithRayInverseMatrix);
  16126. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16127. }, predicate, fastCheck);
  16128. };
  16129. Scene.prototype.setPointerOverMesh = function (mesh) {
  16130. if (this._pointerOverMesh === mesh) {
  16131. return;
  16132. }
  16133. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16134. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16135. }
  16136. this._pointerOverMesh = mesh;
  16137. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16138. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16139. }
  16140. };
  16141. Scene.prototype.getPointerOverMesh = function () {
  16142. return this._pointerOverMesh;
  16143. };
  16144. Scene.prototype.setPointerOverSprite = function (sprite) {
  16145. if (this._pointerOverSprite === sprite) {
  16146. return;
  16147. }
  16148. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16149. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16150. }
  16151. this._pointerOverSprite = sprite;
  16152. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16153. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16154. }
  16155. };
  16156. Scene.prototype.getPointerOverSprite = function () {
  16157. return this._pointerOverSprite;
  16158. };
  16159. // Physics
  16160. Scene.prototype.getPhysicsEngine = function () {
  16161. return this._physicsEngine;
  16162. };
  16163. /**
  16164. * Enables physics to the current scene
  16165. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16166. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16167. * @return {boolean} was the physics engine initialized
  16168. */
  16169. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16170. if (this._physicsEngine) {
  16171. return true;
  16172. }
  16173. try {
  16174. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16175. return true;
  16176. }
  16177. catch (e) {
  16178. BABYLON.Tools.Error(e.message);
  16179. return false;
  16180. }
  16181. };
  16182. Scene.prototype.disablePhysicsEngine = function () {
  16183. if (!this._physicsEngine) {
  16184. return;
  16185. }
  16186. this._physicsEngine.dispose();
  16187. this._physicsEngine = undefined;
  16188. };
  16189. Scene.prototype.isPhysicsEnabled = function () {
  16190. return this._physicsEngine !== undefined;
  16191. };
  16192. /**
  16193. *
  16194. * Sets the gravity of the physics engine (and NOT of the scene)
  16195. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16196. */
  16197. Scene.prototype.setGravity = function (gravity) {
  16198. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16199. if (!this._physicsEngine) {
  16200. return;
  16201. }
  16202. this._physicsEngine.setGravity(gravity);
  16203. };
  16204. /**
  16205. * Legacy support, using the new API
  16206. * @Deprecated
  16207. */
  16208. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16209. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16210. if (parts.parts) {
  16211. options = parts;
  16212. parts = parts.parts;
  16213. }
  16214. var mainMesh = parts[0].mesh;
  16215. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16216. for (var index = 1; index < parts.length; index++) {
  16217. var mesh = parts[index].mesh;
  16218. if (mesh.parent !== mainMesh) {
  16219. mesh.position = mesh.position.subtract(mainMesh.position);
  16220. mesh.parent = mainMesh;
  16221. }
  16222. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16223. }
  16224. mainMesh.physicsImpostor.forceUpdate();
  16225. };
  16226. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16227. var mesh = compound.parts[0].mesh;
  16228. mesh.physicsImpostor.dispose();
  16229. mesh.physicsImpostor = null;
  16230. };
  16231. // Misc.
  16232. Scene.prototype.createDefaultCameraOrLight = function () {
  16233. // Light
  16234. if (this.lights.length === 0) {
  16235. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16236. }
  16237. // Camera
  16238. if (!this.activeCamera) {
  16239. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16240. // Compute position
  16241. var worldExtends = this.getWorldExtends();
  16242. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16243. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16244. camera.setTarget(worldCenter);
  16245. this.activeCamera = camera;
  16246. }
  16247. };
  16248. // Tags
  16249. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16250. if (tagsQuery === undefined) {
  16251. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16252. return list;
  16253. }
  16254. var listByTags = [];
  16255. forEach = forEach || (function (item) { return; });
  16256. for (var i in list) {
  16257. var item = list[i];
  16258. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16259. listByTags.push(item);
  16260. forEach(item);
  16261. }
  16262. }
  16263. return listByTags;
  16264. };
  16265. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16266. return this._getByTags(this.meshes, tagsQuery, forEach);
  16267. };
  16268. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16269. return this._getByTags(this.cameras, tagsQuery, forEach);
  16270. };
  16271. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16272. return this._getByTags(this.lights, tagsQuery, forEach);
  16273. };
  16274. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16275. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16276. };
  16277. // Statics
  16278. Scene._FOGMODE_NONE = 0;
  16279. Scene._FOGMODE_EXP = 1;
  16280. Scene._FOGMODE_EXP2 = 2;
  16281. Scene._FOGMODE_LINEAR = 3;
  16282. Scene.MinDeltaTime = 1.0;
  16283. Scene.MaxDeltaTime = 1000.0;
  16284. return Scene;
  16285. })();
  16286. BABYLON.Scene = Scene;
  16287. })(BABYLON || (BABYLON = {}));
  16288. var BABYLON;
  16289. (function (BABYLON) {
  16290. var VertexBuffer = (function () {
  16291. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16292. if (engine instanceof BABYLON.Mesh) {
  16293. this._engine = engine.getScene().getEngine();
  16294. }
  16295. else {
  16296. this._engine = engine;
  16297. }
  16298. this._updatable = updatable;
  16299. this._data = data;
  16300. if (!postponeInternalCreation) {
  16301. this.create();
  16302. }
  16303. this._kind = kind;
  16304. if (stride) {
  16305. this._strideSize = stride;
  16306. return;
  16307. }
  16308. // Deduce stride from kind
  16309. switch (kind) {
  16310. case VertexBuffer.PositionKind:
  16311. this._strideSize = 3;
  16312. break;
  16313. case VertexBuffer.NormalKind:
  16314. this._strideSize = 3;
  16315. break;
  16316. case VertexBuffer.UVKind:
  16317. case VertexBuffer.UV2Kind:
  16318. case VertexBuffer.UV3Kind:
  16319. case VertexBuffer.UV4Kind:
  16320. case VertexBuffer.UV5Kind:
  16321. case VertexBuffer.UV6Kind:
  16322. this._strideSize = 2;
  16323. break;
  16324. case VertexBuffer.ColorKind:
  16325. this._strideSize = 4;
  16326. break;
  16327. case VertexBuffer.MatricesIndicesKind:
  16328. case VertexBuffer.MatricesIndicesExtraKind:
  16329. this._strideSize = 4;
  16330. break;
  16331. case VertexBuffer.MatricesWeightsKind:
  16332. case VertexBuffer.MatricesWeightsExtraKind:
  16333. this._strideSize = 4;
  16334. break;
  16335. }
  16336. }
  16337. // Properties
  16338. VertexBuffer.prototype.isUpdatable = function () {
  16339. return this._updatable;
  16340. };
  16341. VertexBuffer.prototype.getData = function () {
  16342. return this._data;
  16343. };
  16344. VertexBuffer.prototype.getBuffer = function () {
  16345. return this._buffer;
  16346. };
  16347. VertexBuffer.prototype.getStrideSize = function () {
  16348. return this._strideSize;
  16349. };
  16350. // Methods
  16351. VertexBuffer.prototype.create = function (data) {
  16352. if (!data && this._buffer) {
  16353. return; // nothing to do
  16354. }
  16355. data = data || this._data;
  16356. if (!this._buffer) {
  16357. if (this._updatable) {
  16358. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16359. }
  16360. else {
  16361. this._buffer = this._engine.createVertexBuffer(data);
  16362. }
  16363. }
  16364. if (this._updatable) {
  16365. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16366. this._data = data;
  16367. }
  16368. };
  16369. VertexBuffer.prototype.update = function (data) {
  16370. this.create(data);
  16371. };
  16372. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16373. if (!this._buffer) {
  16374. return;
  16375. }
  16376. if (this._updatable) {
  16377. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16378. this._data = null;
  16379. }
  16380. };
  16381. VertexBuffer.prototype.dispose = function () {
  16382. if (!this._buffer) {
  16383. return;
  16384. }
  16385. if (this._engine._releaseBuffer(this._buffer)) {
  16386. this._buffer = null;
  16387. }
  16388. };
  16389. Object.defineProperty(VertexBuffer, "PositionKind", {
  16390. get: function () {
  16391. return VertexBuffer._PositionKind;
  16392. },
  16393. enumerable: true,
  16394. configurable: true
  16395. });
  16396. Object.defineProperty(VertexBuffer, "NormalKind", {
  16397. get: function () {
  16398. return VertexBuffer._NormalKind;
  16399. },
  16400. enumerable: true,
  16401. configurable: true
  16402. });
  16403. Object.defineProperty(VertexBuffer, "UVKind", {
  16404. get: function () {
  16405. return VertexBuffer._UVKind;
  16406. },
  16407. enumerable: true,
  16408. configurable: true
  16409. });
  16410. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16411. get: function () {
  16412. return VertexBuffer._UV2Kind;
  16413. },
  16414. enumerable: true,
  16415. configurable: true
  16416. });
  16417. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16418. get: function () {
  16419. return VertexBuffer._UV3Kind;
  16420. },
  16421. enumerable: true,
  16422. configurable: true
  16423. });
  16424. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16425. get: function () {
  16426. return VertexBuffer._UV4Kind;
  16427. },
  16428. enumerable: true,
  16429. configurable: true
  16430. });
  16431. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16432. get: function () {
  16433. return VertexBuffer._UV5Kind;
  16434. },
  16435. enumerable: true,
  16436. configurable: true
  16437. });
  16438. Object.defineProperty(VertexBuffer, "UV6Kind", {
  16439. get: function () {
  16440. return VertexBuffer._UV6Kind;
  16441. },
  16442. enumerable: true,
  16443. configurable: true
  16444. });
  16445. Object.defineProperty(VertexBuffer, "ColorKind", {
  16446. get: function () {
  16447. return VertexBuffer._ColorKind;
  16448. },
  16449. enumerable: true,
  16450. configurable: true
  16451. });
  16452. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  16453. get: function () {
  16454. return VertexBuffer._MatricesIndicesKind;
  16455. },
  16456. enumerable: true,
  16457. configurable: true
  16458. });
  16459. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  16460. get: function () {
  16461. return VertexBuffer._MatricesWeightsKind;
  16462. },
  16463. enumerable: true,
  16464. configurable: true
  16465. });
  16466. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  16467. get: function () {
  16468. return VertexBuffer._MatricesIndicesExtraKind;
  16469. },
  16470. enumerable: true,
  16471. configurable: true
  16472. });
  16473. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  16474. get: function () {
  16475. return VertexBuffer._MatricesWeightsExtraKind;
  16476. },
  16477. enumerable: true,
  16478. configurable: true
  16479. });
  16480. // Enums
  16481. VertexBuffer._PositionKind = "position";
  16482. VertexBuffer._NormalKind = "normal";
  16483. VertexBuffer._UVKind = "uv";
  16484. VertexBuffer._UV2Kind = "uv2";
  16485. VertexBuffer._UV3Kind = "uv3";
  16486. VertexBuffer._UV4Kind = "uv4";
  16487. VertexBuffer._UV5Kind = "uv5";
  16488. VertexBuffer._UV6Kind = "uv6";
  16489. VertexBuffer._ColorKind = "color";
  16490. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  16491. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  16492. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  16493. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  16494. return VertexBuffer;
  16495. })();
  16496. BABYLON.VertexBuffer = VertexBuffer;
  16497. })(BABYLON || (BABYLON = {}));
  16498. var BABYLON;
  16499. (function (BABYLON) {
  16500. /**
  16501. * Creates an instance based on a source mesh.
  16502. */
  16503. var InstancedMesh = (function (_super) {
  16504. __extends(InstancedMesh, _super);
  16505. function InstancedMesh(name, source) {
  16506. _super.call(this, name, source.getScene());
  16507. source.instances.push(this);
  16508. this._sourceMesh = source;
  16509. this.position.copyFrom(source.position);
  16510. this.rotation.copyFrom(source.rotation);
  16511. this.scaling.copyFrom(source.scaling);
  16512. if (source.rotationQuaternion) {
  16513. this.rotationQuaternion = source.rotationQuaternion.clone();
  16514. }
  16515. this.infiniteDistance = source.infiniteDistance;
  16516. this.setPivotMatrix(source.getPivotMatrix());
  16517. this.refreshBoundingInfo();
  16518. this._syncSubMeshes();
  16519. }
  16520. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  16521. // Methods
  16522. get: function () {
  16523. return this._sourceMesh.receiveShadows;
  16524. },
  16525. enumerable: true,
  16526. configurable: true
  16527. });
  16528. Object.defineProperty(InstancedMesh.prototype, "material", {
  16529. get: function () {
  16530. return this._sourceMesh.material;
  16531. },
  16532. enumerable: true,
  16533. configurable: true
  16534. });
  16535. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  16536. get: function () {
  16537. return this._sourceMesh.visibility;
  16538. },
  16539. enumerable: true,
  16540. configurable: true
  16541. });
  16542. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  16543. get: function () {
  16544. return this._sourceMesh.skeleton;
  16545. },
  16546. enumerable: true,
  16547. configurable: true
  16548. });
  16549. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  16550. get: function () {
  16551. return this._sourceMesh.renderingGroupId;
  16552. },
  16553. enumerable: true,
  16554. configurable: true
  16555. });
  16556. InstancedMesh.prototype.getTotalVertices = function () {
  16557. return this._sourceMesh.getTotalVertices();
  16558. };
  16559. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  16560. get: function () {
  16561. return this._sourceMesh;
  16562. },
  16563. enumerable: true,
  16564. configurable: true
  16565. });
  16566. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16567. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  16568. };
  16569. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  16570. return this._sourceMesh.isVerticesDataPresent(kind);
  16571. };
  16572. InstancedMesh.prototype.getIndices = function () {
  16573. return this._sourceMesh.getIndices();
  16574. };
  16575. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  16576. get: function () {
  16577. return this._sourceMesh._positions;
  16578. },
  16579. enumerable: true,
  16580. configurable: true
  16581. });
  16582. InstancedMesh.prototype.refreshBoundingInfo = function () {
  16583. var meshBB = this._sourceMesh.getBoundingInfo();
  16584. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  16585. this._updateBoundingInfo();
  16586. };
  16587. InstancedMesh.prototype._preActivate = function () {
  16588. if (this._currentLOD) {
  16589. this._currentLOD._preActivate();
  16590. }
  16591. };
  16592. InstancedMesh.prototype._activate = function (renderId) {
  16593. if (this._currentLOD) {
  16594. this._currentLOD._registerInstanceForRenderId(this, renderId);
  16595. }
  16596. };
  16597. InstancedMesh.prototype.getLOD = function (camera) {
  16598. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  16599. if (this._currentLOD === this.sourceMesh) {
  16600. return this;
  16601. }
  16602. return this._currentLOD;
  16603. };
  16604. InstancedMesh.prototype._syncSubMeshes = function () {
  16605. this.releaseSubMeshes();
  16606. if (this._sourceMesh.subMeshes) {
  16607. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  16608. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  16609. }
  16610. }
  16611. };
  16612. InstancedMesh.prototype._generatePointsArray = function () {
  16613. return this._sourceMesh._generatePointsArray();
  16614. };
  16615. // Clone
  16616. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16617. var result = this._sourceMesh.createInstance(name);
  16618. // Deep copy
  16619. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  16620. // Bounding info
  16621. this.refreshBoundingInfo();
  16622. // Parent
  16623. if (newParent) {
  16624. result.parent = newParent;
  16625. }
  16626. if (!doNotCloneChildren) {
  16627. // Children
  16628. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16629. var mesh = this.getScene().meshes[index];
  16630. if (mesh.parent === this) {
  16631. mesh.clone(mesh.name, result);
  16632. }
  16633. }
  16634. }
  16635. result.computeWorldMatrix(true);
  16636. return result;
  16637. };
  16638. // Dispoe
  16639. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16640. // Remove from mesh
  16641. var index = this._sourceMesh.instances.indexOf(this);
  16642. this._sourceMesh.instances.splice(index, 1);
  16643. _super.prototype.dispose.call(this, doNotRecurse);
  16644. };
  16645. return InstancedMesh;
  16646. })(BABYLON.AbstractMesh);
  16647. BABYLON.InstancedMesh = InstancedMesh;
  16648. })(BABYLON || (BABYLON = {}));
  16649. var BABYLON;
  16650. (function (BABYLON) {
  16651. var _InstancesBatch = (function () {
  16652. function _InstancesBatch() {
  16653. this.mustReturn = false;
  16654. this.visibleInstances = new Array();
  16655. this.renderSelf = new Array();
  16656. }
  16657. return _InstancesBatch;
  16658. })();
  16659. BABYLON._InstancesBatch = _InstancesBatch;
  16660. var Mesh = (function (_super) {
  16661. __extends(Mesh, _super);
  16662. /**
  16663. * @constructor
  16664. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16665. * @param {Scene} scene - The scene to add this mesh to.
  16666. * @param {Node} parent - The parent of this mesh, if it has one
  16667. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16668. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16669. * When false, achieved by calling a clone(), also passing False.
  16670. * This will make creation of children, recursive.
  16671. */
  16672. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  16673. if (parent === void 0) { parent = null; }
  16674. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  16675. _super.call(this, name, scene);
  16676. // Events
  16677. /**
  16678. * An event triggered before rendering the mesh
  16679. * @type {BABYLON.Observable}
  16680. */
  16681. this.onBeforeRenderObservable = new BABYLON.Observable();
  16682. /**
  16683. * An event triggered after rendering the mesh
  16684. * @type {BABYLON.Observable}
  16685. */
  16686. this.onAfterRenderObservable = new BABYLON.Observable();
  16687. /**
  16688. * An event triggered before drawing the mesh
  16689. * @type {BABYLON.Observable}
  16690. */
  16691. this.onBeforeDrawObservable = new BABYLON.Observable();
  16692. // Members
  16693. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16694. this.instances = new Array();
  16695. this._LODLevels = new Array();
  16696. this._visibleInstances = {};
  16697. this._renderIdForInstances = new Array();
  16698. this._batchCache = new _InstancesBatch();
  16699. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16700. this._sideOrientation = Mesh._DEFAULTSIDE;
  16701. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16702. if (source) {
  16703. // Geometry
  16704. if (source._geometry) {
  16705. source._geometry.applyToMesh(this);
  16706. }
  16707. // Deep copy
  16708. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16709. // Pivot
  16710. this.setPivotMatrix(source.getPivotMatrix());
  16711. this.id = name + "." + source.id;
  16712. // Material
  16713. this.material = source.material;
  16714. var index;
  16715. if (!doNotCloneChildren) {
  16716. // Children
  16717. for (index = 0; index < scene.meshes.length; index++) {
  16718. var mesh = scene.meshes[index];
  16719. if (mesh.parent === source) {
  16720. // doNotCloneChildren is always going to be False
  16721. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16722. }
  16723. }
  16724. }
  16725. // Physics clone
  16726. var physicsEngine = this.getScene().getPhysicsEngine();
  16727. if (clonePhysicsImpostor && physicsEngine) {
  16728. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  16729. if (impostor) {
  16730. this.physicsImpostor = impostor.clone(this);
  16731. }
  16732. }
  16733. // Particles
  16734. for (index = 0; index < scene.particleSystems.length; index++) {
  16735. var system = scene.particleSystems[index];
  16736. if (system.emitter === source) {
  16737. system.clone(system.name, this);
  16738. }
  16739. }
  16740. this.computeWorldMatrix(true);
  16741. }
  16742. // Parent
  16743. if (parent !== null) {
  16744. this.parent = parent;
  16745. }
  16746. }
  16747. Object.defineProperty(Mesh, "FRONTSIDE", {
  16748. /**
  16749. * Mesh side orientation : usually the external or front surface
  16750. */
  16751. get: function () {
  16752. return Mesh._FRONTSIDE;
  16753. },
  16754. enumerable: true,
  16755. configurable: true
  16756. });
  16757. Object.defineProperty(Mesh, "BACKSIDE", {
  16758. /**
  16759. * Mesh side orientation : usually the internal or back surface
  16760. */
  16761. get: function () {
  16762. return Mesh._BACKSIDE;
  16763. },
  16764. enumerable: true,
  16765. configurable: true
  16766. });
  16767. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16768. /**
  16769. * Mesh side orientation : both internal and external or front and back surfaces
  16770. */
  16771. get: function () {
  16772. return Mesh._DOUBLESIDE;
  16773. },
  16774. enumerable: true,
  16775. configurable: true
  16776. });
  16777. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16778. /**
  16779. * Mesh side orientation : by default, `FRONTSIDE`
  16780. */
  16781. get: function () {
  16782. return Mesh._DEFAULTSIDE;
  16783. },
  16784. enumerable: true,
  16785. configurable: true
  16786. });
  16787. Object.defineProperty(Mesh, "NO_CAP", {
  16788. /**
  16789. * Mesh cap setting : no cap
  16790. */
  16791. get: function () {
  16792. return Mesh._NO_CAP;
  16793. },
  16794. enumerable: true,
  16795. configurable: true
  16796. });
  16797. Object.defineProperty(Mesh, "CAP_START", {
  16798. /**
  16799. * Mesh cap setting : one cap at the beginning of the mesh
  16800. */
  16801. get: function () {
  16802. return Mesh._CAP_START;
  16803. },
  16804. enumerable: true,
  16805. configurable: true
  16806. });
  16807. Object.defineProperty(Mesh, "CAP_END", {
  16808. /**
  16809. * Mesh cap setting : one cap at the end of the mesh
  16810. */
  16811. get: function () {
  16812. return Mesh._CAP_END;
  16813. },
  16814. enumerable: true,
  16815. configurable: true
  16816. });
  16817. Object.defineProperty(Mesh, "CAP_ALL", {
  16818. /**
  16819. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  16820. */
  16821. get: function () {
  16822. return Mesh._CAP_ALL;
  16823. },
  16824. enumerable: true,
  16825. configurable: true
  16826. });
  16827. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  16828. set: function (callback) {
  16829. if (this._onBeforeDrawObserver) {
  16830. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  16831. }
  16832. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  16833. },
  16834. enumerable: true,
  16835. configurable: true
  16836. });
  16837. // Methods
  16838. /**
  16839. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16840. */
  16841. Mesh.prototype.toString = function (fullDetails) {
  16842. var ret = _super.prototype.toString.call(this, fullDetails);
  16843. ret += ", n vertices: " + this.getTotalVertices();
  16844. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16845. if (this.animations) {
  16846. for (var i = 0; i < this.animations.length; i++) {
  16847. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16848. }
  16849. }
  16850. if (fullDetails) {
  16851. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16852. }
  16853. return ret;
  16854. };
  16855. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16856. get: function () {
  16857. return this._LODLevels.length > 0;
  16858. },
  16859. enumerable: true,
  16860. configurable: true
  16861. });
  16862. Mesh.prototype._sortLODLevels = function () {
  16863. this._LODLevels.sort(function (a, b) {
  16864. if (a.distance < b.distance) {
  16865. return 1;
  16866. }
  16867. if (a.distance > b.distance) {
  16868. return -1;
  16869. }
  16870. return 0;
  16871. });
  16872. };
  16873. /**
  16874. * Add a mesh as LOD level triggered at the given distance.
  16875. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16876. * @param {number} distance - the distance from the center of the object to show this level
  16877. * @param {Mesh} mesh - the mesh to be added as LOD level
  16878. * @return {Mesh} this mesh (for chaining)
  16879. */
  16880. Mesh.prototype.addLODLevel = function (distance, mesh) {
  16881. if (mesh && mesh._masterMesh) {
  16882. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  16883. return this;
  16884. }
  16885. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  16886. this._LODLevels.push(level);
  16887. if (mesh) {
  16888. mesh._masterMesh = this;
  16889. }
  16890. this._sortLODLevels();
  16891. return this;
  16892. };
  16893. /**
  16894. * Returns the LOD level mesh at the passed distance or null if not found.
  16895. * It is related to the method `addLODLevel(distance, mesh)`.
  16896. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16897. */
  16898. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  16899. for (var index = 0; index < this._LODLevels.length; index++) {
  16900. var level = this._LODLevels[index];
  16901. if (level.distance === distance) {
  16902. return level.mesh;
  16903. }
  16904. }
  16905. return null;
  16906. };
  16907. /**
  16908. * Remove a mesh from the LOD array
  16909. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16910. * @param {Mesh} mesh - the mesh to be removed.
  16911. * @return {Mesh} this mesh (for chaining)
  16912. */
  16913. Mesh.prototype.removeLODLevel = function (mesh) {
  16914. for (var index = 0; index < this._LODLevels.length; index++) {
  16915. if (this._LODLevels[index].mesh === mesh) {
  16916. this._LODLevels.splice(index, 1);
  16917. if (mesh) {
  16918. mesh._masterMesh = null;
  16919. }
  16920. }
  16921. }
  16922. this._sortLODLevels();
  16923. return this;
  16924. };
  16925. /**
  16926. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  16927. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16928. */
  16929. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  16930. if (!this._LODLevels || this._LODLevels.length === 0) {
  16931. return this;
  16932. }
  16933. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  16934. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  16935. if (this.onLODLevelSelection) {
  16936. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  16937. }
  16938. return this;
  16939. }
  16940. for (var index = 0; index < this._LODLevels.length; index++) {
  16941. var level = this._LODLevels[index];
  16942. if (level.distance < distanceToCamera) {
  16943. if (level.mesh) {
  16944. level.mesh._preActivate();
  16945. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16946. }
  16947. if (this.onLODLevelSelection) {
  16948. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  16949. }
  16950. return level.mesh;
  16951. }
  16952. }
  16953. if (this.onLODLevelSelection) {
  16954. this.onLODLevelSelection(distanceToCamera, this, this);
  16955. }
  16956. return this;
  16957. };
  16958. Object.defineProperty(Mesh.prototype, "geometry", {
  16959. /**
  16960. * Returns the mesh internal `Geometry` object.
  16961. */
  16962. get: function () {
  16963. return this._geometry;
  16964. },
  16965. enumerable: true,
  16966. configurable: true
  16967. });
  16968. /**
  16969. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  16970. */
  16971. Mesh.prototype.getTotalVertices = function () {
  16972. if (!this._geometry) {
  16973. return 0;
  16974. }
  16975. return this._geometry.getTotalVertices();
  16976. };
  16977. /**
  16978. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  16979. * If `copywhenShared` is true (default false) and if the mesh has submeshes, the submesh data are duplicated in the returned array.
  16980. * Returns null if the mesh has no geometry or no vertex buffer.
  16981. * Possible `kind` values :
  16982. * - BABYLON.VertexBuffer.PositionKind
  16983. * - BABYLON.VertexBuffer.UVKind
  16984. * - BABYLON.VertexBuffer.UV2Kind
  16985. * - BABYLON.VertexBuffer.UV3Kind
  16986. * - BABYLON.VertexBuffer.UV4Kind
  16987. * - BABYLON.VertexBuffer.UV5Kind
  16988. * - BABYLON.VertexBuffer.UV6Kind
  16989. * - BABYLON.VertexBuffer.ColorKind
  16990. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16991. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16992. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16993. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16994. */
  16995. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16996. if (!this._geometry) {
  16997. return null;
  16998. }
  16999. return this._geometry.getVerticesData(kind, copyWhenShared);
  17000. };
  17001. /**
  17002. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  17003. * Returns `undefined` if the mesh has no geometry.
  17004. * Possible `kind` values :
  17005. * - BABYLON.VertexBuffer.PositionKind
  17006. * - BABYLON.VertexBuffer.UVKind
  17007. * - BABYLON.VertexBuffer.UV2Kind
  17008. * - BABYLON.VertexBuffer.UV3Kind
  17009. * - BABYLON.VertexBuffer.UV4Kind
  17010. * - BABYLON.VertexBuffer.UV5Kind
  17011. * - BABYLON.VertexBuffer.UV6Kind
  17012. * - BABYLON.VertexBuffer.ColorKind
  17013. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17014. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17015. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17016. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17017. */
  17018. Mesh.prototype.getVertexBuffer = function (kind) {
  17019. if (!this._geometry) {
  17020. return undefined;
  17021. }
  17022. return this._geometry.getVertexBuffer(kind);
  17023. };
  17024. /**
  17025. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  17026. * Possible `kind` values :
  17027. * - BABYLON.VertexBuffer.PositionKind
  17028. * - BABYLON.VertexBuffer.UVKind
  17029. * - BABYLON.VertexBuffer.UV2Kind
  17030. * - BABYLON.VertexBuffer.UV3Kind
  17031. * - BABYLON.VertexBuffer.UV4Kind
  17032. * - BABYLON.VertexBuffer.UV5Kind
  17033. * - BABYLON.VertexBuffer.UV6Kind
  17034. * - BABYLON.VertexBuffer.ColorKind
  17035. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17036. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17037. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17038. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17039. */
  17040. Mesh.prototype.isVerticesDataPresent = function (kind) {
  17041. if (!this._geometry) {
  17042. if (this._delayInfo) {
  17043. return this._delayInfo.indexOf(kind) !== -1;
  17044. }
  17045. return false;
  17046. }
  17047. return this._geometry.isVerticesDataPresent(kind);
  17048. };
  17049. /**
  17050. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  17051. * Possible `kind` values :
  17052. * - BABYLON.VertexBuffer.PositionKind
  17053. * - BABYLON.VertexBuffer.UVKind
  17054. * - BABYLON.VertexBuffer.UV2Kind
  17055. * - BABYLON.VertexBuffer.UV3Kind
  17056. * - BABYLON.VertexBuffer.UV4Kind
  17057. * - BABYLON.VertexBuffer.UV5Kind
  17058. * - BABYLON.VertexBuffer.UV6Kind
  17059. * - BABYLON.VertexBuffer.ColorKind
  17060. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17061. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17062. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17063. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17064. */
  17065. Mesh.prototype.getVerticesDataKinds = function () {
  17066. if (!this._geometry) {
  17067. var result = [];
  17068. if (this._delayInfo) {
  17069. for (var kind in this._delayInfo) {
  17070. result.push(kind);
  17071. }
  17072. }
  17073. return result;
  17074. }
  17075. return this._geometry.getVerticesDataKinds();
  17076. };
  17077. /**
  17078. * Returns a positive integer : the total number of indices in this mesh geometry.
  17079. * Returns zero if the mesh has no geometry.
  17080. */
  17081. Mesh.prototype.getTotalIndices = function () {
  17082. if (!this._geometry) {
  17083. return 0;
  17084. }
  17085. return this._geometry.getTotalIndices();
  17086. };
  17087. /**
  17088. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17089. * If the parameter `copyWhenShared` is true (default false) and if the mesh has submeshes, the submesh indices are duplicated in the returned array.
  17090. * Returns an empty array if the mesh has no geometry.
  17091. */
  17092. Mesh.prototype.getIndices = function (copyWhenShared) {
  17093. if (!this._geometry) {
  17094. return [];
  17095. }
  17096. return this._geometry.getIndices(copyWhenShared);
  17097. };
  17098. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17099. get: function () {
  17100. return this._masterMesh !== null && this._masterMesh !== undefined;
  17101. },
  17102. enumerable: true,
  17103. configurable: true
  17104. });
  17105. /**
  17106. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17107. */
  17108. Mesh.prototype.isReady = function () {
  17109. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17110. return false;
  17111. }
  17112. return _super.prototype.isReady.call(this);
  17113. };
  17114. /**
  17115. * Boolean : true if the mesh has been disposed.
  17116. */
  17117. Mesh.prototype.isDisposed = function () {
  17118. return this._isDisposed;
  17119. };
  17120. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17121. get: function () {
  17122. return this._sideOrientation;
  17123. },
  17124. /**
  17125. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17126. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17127. */
  17128. set: function (sideO) {
  17129. this._sideOrientation = sideO;
  17130. },
  17131. enumerable: true,
  17132. configurable: true
  17133. });
  17134. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17135. /**
  17136. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17137. * This property is pertinent only for updatable parametric shapes.
  17138. */
  17139. get: function () {
  17140. return this._areNormalsFrozen;
  17141. },
  17142. enumerable: true,
  17143. configurable: true
  17144. });
  17145. /**
  17146. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17147. * It has no effect at all on other shapes.
  17148. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17149. */
  17150. Mesh.prototype.freezeNormals = function () {
  17151. this._areNormalsFrozen = true;
  17152. };
  17153. /**
  17154. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17155. * It has no effect at all on other shapes.
  17156. * It reactivates the mesh normals computation if it was previously frozen.
  17157. */
  17158. Mesh.prototype.unfreezeNormals = function () {
  17159. this._areNormalsFrozen = false;
  17160. };
  17161. // Methods
  17162. Mesh.prototype._preActivate = function () {
  17163. var sceneRenderId = this.getScene().getRenderId();
  17164. if (this._preActivateId === sceneRenderId) {
  17165. return;
  17166. }
  17167. this._preActivateId = sceneRenderId;
  17168. this._visibleInstances = null;
  17169. };
  17170. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17171. if (this._visibleInstances) {
  17172. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17173. }
  17174. };
  17175. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17176. if (!this._visibleInstances) {
  17177. this._visibleInstances = {};
  17178. this._visibleInstances.defaultRenderId = renderId;
  17179. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17180. }
  17181. if (!this._visibleInstances[renderId]) {
  17182. this._visibleInstances[renderId] = new Array();
  17183. }
  17184. this._visibleInstances[renderId].push(instance);
  17185. };
  17186. /**
  17187. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  17188. * This means the mesh underlying bounding box and shpere are recomputed.
  17189. */
  17190. Mesh.prototype.refreshBoundingInfo = function () {
  17191. if (this._boundingInfo.isLocked) {
  17192. return;
  17193. }
  17194. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17195. if (data) {
  17196. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17197. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17198. }
  17199. if (this.subMeshes) {
  17200. for (var index = 0; index < this.subMeshes.length; index++) {
  17201. this.subMeshes[index].refreshBoundingInfo();
  17202. }
  17203. }
  17204. this._updateBoundingInfo();
  17205. };
  17206. Mesh.prototype._createGlobalSubMesh = function () {
  17207. var totalVertices = this.getTotalVertices();
  17208. if (!totalVertices || !this.getIndices()) {
  17209. return null;
  17210. }
  17211. this.releaseSubMeshes();
  17212. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17213. };
  17214. Mesh.prototype.subdivide = function (count) {
  17215. if (count < 1) {
  17216. return;
  17217. }
  17218. var totalIndices = this.getTotalIndices();
  17219. var subdivisionSize = (totalIndices / count) | 0;
  17220. var offset = 0;
  17221. // Ensure that subdivisionSize is a multiple of 3
  17222. while (subdivisionSize % 3 !== 0) {
  17223. subdivisionSize++;
  17224. }
  17225. this.releaseSubMeshes();
  17226. for (var index = 0; index < count; index++) {
  17227. if (offset >= totalIndices) {
  17228. break;
  17229. }
  17230. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17231. offset += subdivisionSize;
  17232. }
  17233. this.synchronizeInstances();
  17234. };
  17235. /**
  17236. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17237. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  17238. * The `data` are either a numeric array either a Float32Array.
  17239. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  17240. * Note that a new underlying `VertexBuffer` object is created each call.
  17241. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17242. * The same for the mesh submeshes if any.
  17243. *
  17244. * Possible `kind` values :
  17245. * - BABYLON.VertexBuffer.PositionKind
  17246. * - BABYLON.VertexBuffer.UVKind
  17247. * - BABYLON.VertexBuffer.UV2Kind
  17248. * - BABYLON.VertexBuffer.UV3Kind
  17249. * - BABYLON.VertexBuffer.UV4Kind
  17250. * - BABYLON.VertexBuffer.UV5Kind
  17251. * - BABYLON.VertexBuffer.UV6Kind
  17252. * - BABYLON.VertexBuffer.ColorKind
  17253. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17254. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17255. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17256. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17257. */
  17258. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17259. if (!this._geometry) {
  17260. var vertexData = new BABYLON.VertexData();
  17261. vertexData.set(data, kind);
  17262. var scene = this.getScene();
  17263. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17264. }
  17265. else {
  17266. this._geometry.setVerticesData(kind, data, updatable, stride);
  17267. }
  17268. };
  17269. /**
  17270. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17271. * If the mesh has no geometry, it is simply returned as it is.
  17272. * The `data` are either a numeric array either a Float32Array.
  17273. * No new underlying `VertexBuffer` object is created.
  17274. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17275. * The same for the mesh submeshes if any.
  17276. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17277. *
  17278. * Possible `kind` values :
  17279. * - BABYLON.VertexBuffer.PositionKind
  17280. * - BABYLON.VertexBuffer.UVKind
  17281. * - BABYLON.VertexBuffer.UV2Kind
  17282. * - BABYLON.VertexBuffer.UV3Kind
  17283. * - BABYLON.VertexBuffer.UV4Kind
  17284. * - BABYLON.VertexBuffer.UV5Kind
  17285. * - BABYLON.VertexBuffer.UV6Kind
  17286. * - BABYLON.VertexBuffer.ColorKind
  17287. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17288. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17289. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17290. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17291. */
  17292. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17293. if (!this._geometry) {
  17294. return;
  17295. }
  17296. if (!makeItUnique) {
  17297. this._geometry.updateVerticesData(kind, data, updateExtends);
  17298. }
  17299. else {
  17300. this.makeGeometryUnique();
  17301. this.updateVerticesData(kind, data, updateExtends, false);
  17302. }
  17303. };
  17304. /**
  17305. * Deprecated since BabylonJS v2.3
  17306. */
  17307. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17308. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17309. if (!this._geometry) {
  17310. return;
  17311. }
  17312. if (!makeItUnique) {
  17313. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17314. }
  17315. else {
  17316. this.makeGeometryUnique();
  17317. this.updateVerticesDataDirectly(kind, data, offset, false);
  17318. }
  17319. };
  17320. /**
  17321. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  17322. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  17323. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  17324. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  17325. */
  17326. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  17327. if (computeNormals === void 0) { computeNormals = true; }
  17328. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17329. positionFunction(positions);
  17330. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17331. if (computeNormals) {
  17332. var indices = this.getIndices();
  17333. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17334. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17335. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17336. }
  17337. };
  17338. Mesh.prototype.makeGeometryUnique = function () {
  17339. if (!this._geometry) {
  17340. return;
  17341. }
  17342. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  17343. geometry.applyToMesh(this);
  17344. };
  17345. /**
  17346. * Sets the mesh indices.
  17347. * Expects an array populated with integers or a Int32Array.
  17348. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  17349. * This method creates a new index buffer each call.
  17350. */
  17351. Mesh.prototype.setIndices = function (indices, totalVertices) {
  17352. if (!this._geometry) {
  17353. var vertexData = new BABYLON.VertexData();
  17354. vertexData.indices = indices;
  17355. var scene = this.getScene();
  17356. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  17357. }
  17358. else {
  17359. this._geometry.setIndices(indices, totalVertices);
  17360. }
  17361. };
  17362. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  17363. var engine = this.getScene().getEngine();
  17364. // Wireframe
  17365. var indexToBind;
  17366. if (this._unIndexed) {
  17367. indexToBind = null;
  17368. }
  17369. else {
  17370. switch (fillMode) {
  17371. case BABYLON.Material.PointFillMode:
  17372. indexToBind = null;
  17373. break;
  17374. case BABYLON.Material.WireFrameFillMode:
  17375. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  17376. break;
  17377. default:
  17378. case BABYLON.Material.TriangleFillMode:
  17379. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  17380. break;
  17381. }
  17382. }
  17383. // VBOs
  17384. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  17385. };
  17386. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  17387. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17388. return;
  17389. }
  17390. this.onBeforeDrawObservable.notifyObservers(this);
  17391. var engine = this.getScene().getEngine();
  17392. // Draw order
  17393. switch (fillMode) {
  17394. case BABYLON.Material.PointFillMode:
  17395. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17396. break;
  17397. case BABYLON.Material.WireFrameFillMode:
  17398. if (this._unIndexed) {
  17399. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17400. }
  17401. else {
  17402. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  17403. }
  17404. break;
  17405. default:
  17406. if (this._unIndexed) {
  17407. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17408. }
  17409. else {
  17410. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  17411. }
  17412. }
  17413. };
  17414. /**
  17415. * Registers a javascript function for this mesh that will be called just before the rendering process.
  17416. * This function is passed the current mesh and doesn't return anything.
  17417. */
  17418. Mesh.prototype.registerBeforeRender = function (func) {
  17419. this.onBeforeRenderObservable.add(func);
  17420. };
  17421. /**
  17422. * Disposes a previously registered javascript function called before the rendering.
  17423. * This function is passed the current mesh and doesn't return anything.
  17424. */
  17425. Mesh.prototype.unregisterBeforeRender = function (func) {
  17426. this.onBeforeRenderObservable.removeCallback(func);
  17427. };
  17428. /**
  17429. * Registers a javascript function for this mesh that will be called just after the rendering is complete.
  17430. * This function is passed the current mesh and doesn't return anything.
  17431. */
  17432. Mesh.prototype.registerAfterRender = function (func) {
  17433. this.onAfterRenderObservable.add(func);
  17434. };
  17435. /**
  17436. * Disposes a previously registered javascript function called after the rendering.
  17437. * This function is passed the current mesh and doesn't return anything.
  17438. */
  17439. Mesh.prototype.unregisterAfterRender = function (func) {
  17440. this.onAfterRenderObservable.removeCallback(func);
  17441. };
  17442. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  17443. var scene = this.getScene();
  17444. this._batchCache.mustReturn = false;
  17445. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  17446. this._batchCache.visibleInstances[subMeshId] = null;
  17447. if (this._visibleInstances) {
  17448. var currentRenderId = scene.getRenderId();
  17449. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  17450. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  17451. var selfRenderId = this._renderId;
  17452. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  17453. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  17454. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  17455. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  17456. }
  17457. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  17458. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  17459. this._batchCache.mustReturn = true;
  17460. return this._batchCache;
  17461. }
  17462. if (currentRenderId !== selfRenderId) {
  17463. this._batchCache.renderSelf[subMeshId] = false;
  17464. }
  17465. }
  17466. this._renderIdForInstances[subMeshId] = currentRenderId;
  17467. }
  17468. return this._batchCache;
  17469. };
  17470. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  17471. var visibleInstances = batch.visibleInstances[subMesh._id];
  17472. var matricesCount = visibleInstances.length + 1;
  17473. var bufferSize = matricesCount * 16 * 4;
  17474. while (this._instancesBufferSize < bufferSize) {
  17475. this._instancesBufferSize *= 2;
  17476. }
  17477. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  17478. if (this._worldMatricesInstancesBuffer) {
  17479. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17480. }
  17481. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  17482. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  17483. }
  17484. var offset = 0;
  17485. var instancesCount = 0;
  17486. var world = this.getWorldMatrix();
  17487. if (batch.renderSelf[subMesh._id]) {
  17488. world.copyToArray(this._worldMatricesInstancesArray, offset);
  17489. offset += 16;
  17490. instancesCount++;
  17491. }
  17492. if (visibleInstances) {
  17493. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  17494. var instance = visibleInstances[instanceIndex];
  17495. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  17496. offset += 16;
  17497. instancesCount++;
  17498. }
  17499. }
  17500. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  17501. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  17502. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  17503. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  17504. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  17505. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  17506. this._draw(subMesh, fillMode, instancesCount);
  17507. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  17508. };
  17509. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  17510. var scene = this.getScene();
  17511. var engine = scene.getEngine();
  17512. if (hardwareInstancedRendering) {
  17513. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  17514. }
  17515. else {
  17516. if (batch.renderSelf[subMesh._id]) {
  17517. // Draw
  17518. if (onBeforeDraw) {
  17519. onBeforeDraw(false, this.getWorldMatrix());
  17520. }
  17521. this._draw(subMesh, fillMode);
  17522. }
  17523. if (batch.visibleInstances[subMesh._id]) {
  17524. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  17525. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  17526. // World
  17527. var world = instance.getWorldMatrix();
  17528. if (onBeforeDraw) {
  17529. onBeforeDraw(true, world);
  17530. }
  17531. // Draw
  17532. this._draw(subMesh, fillMode);
  17533. }
  17534. }
  17535. }
  17536. };
  17537. /**
  17538. * Triggers the draw call for the mesh.
  17539. * You don't need to call this method by your own usually because the mesh rendering is handled by the scene rendering manager.
  17540. */
  17541. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  17542. var scene = this.getScene();
  17543. // Managing instances
  17544. var batch = this._getInstancesRenderList(subMesh._id);
  17545. if (batch.mustReturn) {
  17546. return;
  17547. }
  17548. // Checking geometry state
  17549. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17550. return;
  17551. }
  17552. var callbackIndex;
  17553. this.onBeforeRenderObservable.notifyObservers(this);
  17554. var engine = scene.getEngine();
  17555. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  17556. // Material
  17557. var effectiveMaterial = subMesh.getMaterial();
  17558. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  17559. return;
  17560. }
  17561. // Outline - step 1
  17562. var savedDepthWrite = engine.getDepthWrite();
  17563. if (this.renderOutline) {
  17564. engine.setDepthWrite(false);
  17565. scene.getOutlineRenderer().render(subMesh, batch);
  17566. engine.setDepthWrite(savedDepthWrite);
  17567. }
  17568. effectiveMaterial._preBind();
  17569. var effect = effectiveMaterial.getEffect();
  17570. // Bind
  17571. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  17572. this._bind(subMesh, effect, fillMode);
  17573. var world = this.getWorldMatrix();
  17574. effectiveMaterial.bind(world, this);
  17575. // Alpha mode
  17576. if (enableAlphaMode) {
  17577. engine.setAlphaMode(effectiveMaterial.alphaMode);
  17578. }
  17579. // Draw
  17580. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  17581. if (isInstance) {
  17582. effectiveMaterial.bindOnlyWorldMatrix(world);
  17583. }
  17584. });
  17585. // Unbind
  17586. effectiveMaterial.unbind();
  17587. // Outline - step 2
  17588. if (this.renderOutline && savedDepthWrite) {
  17589. engine.setDepthWrite(true);
  17590. engine.setColorWrite(false);
  17591. scene.getOutlineRenderer().render(subMesh, batch);
  17592. engine.setColorWrite(true);
  17593. }
  17594. // Overlay
  17595. if (this.renderOverlay) {
  17596. var currentMode = engine.getAlphaMode();
  17597. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  17598. scene.getOutlineRenderer().render(subMesh, batch, true);
  17599. engine.setAlphaMode(currentMode);
  17600. }
  17601. this.onAfterRenderObservable.notifyObservers(this);
  17602. };
  17603. /**
  17604. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  17605. */
  17606. Mesh.prototype.getEmittedParticleSystems = function () {
  17607. var results = new Array();
  17608. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17609. var particleSystem = this.getScene().particleSystems[index];
  17610. if (particleSystem.emitter === this) {
  17611. results.push(particleSystem);
  17612. }
  17613. }
  17614. return results;
  17615. };
  17616. /**
  17617. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  17618. */
  17619. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  17620. var results = new Array();
  17621. var descendants = this.getDescendants();
  17622. descendants.push(this);
  17623. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17624. var particleSystem = this.getScene().particleSystems[index];
  17625. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  17626. results.push(particleSystem);
  17627. }
  17628. }
  17629. return results;
  17630. };
  17631. Mesh.prototype._checkDelayState = function () {
  17632. var _this = this;
  17633. var that = this;
  17634. var scene = this.getScene();
  17635. if (this._geometry) {
  17636. this._geometry.load(scene);
  17637. }
  17638. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17639. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  17640. scene._addPendingData(that);
  17641. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  17642. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  17643. if (data instanceof ArrayBuffer) {
  17644. _this._delayLoadingFunction(data, _this);
  17645. }
  17646. else {
  17647. _this._delayLoadingFunction(JSON.parse(data), _this);
  17648. }
  17649. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17650. scene._removePendingData(_this);
  17651. }, function () { }, scene.database, getBinaryData);
  17652. }
  17653. };
  17654. /**
  17655. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  17656. */
  17657. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  17658. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17659. return false;
  17660. }
  17661. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  17662. return false;
  17663. }
  17664. this._checkDelayState();
  17665. return true;
  17666. };
  17667. Mesh.prototype.setMaterialByID = function (id) {
  17668. var materials = this.getScene().materials;
  17669. var index;
  17670. for (index = 0; index < materials.length; index++) {
  17671. if (materials[index].id === id) {
  17672. this.material = materials[index];
  17673. return;
  17674. }
  17675. }
  17676. // Multi
  17677. var multiMaterials = this.getScene().multiMaterials;
  17678. for (index = 0; index < multiMaterials.length; index++) {
  17679. if (multiMaterials[index].id === id) {
  17680. this.material = multiMaterials[index];
  17681. return;
  17682. }
  17683. }
  17684. };
  17685. Mesh.prototype.getAnimatables = function () {
  17686. var results = [];
  17687. if (this.material) {
  17688. results.push(this.material);
  17689. }
  17690. if (this.skeleton) {
  17691. results.push(this.skeleton);
  17692. }
  17693. return results;
  17694. };
  17695. // Geometry
  17696. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  17697. // Position
  17698. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17699. return;
  17700. }
  17701. this._resetPointsArrayCache();
  17702. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17703. var temp = [];
  17704. var index;
  17705. for (index = 0; index < data.length; index += 3) {
  17706. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  17707. }
  17708. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  17709. // Normals
  17710. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17711. return;
  17712. }
  17713. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17714. temp = [];
  17715. for (index = 0; index < data.length; index += 3) {
  17716. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  17717. }
  17718. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  17719. // flip faces?
  17720. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  17721. this.flipFaces();
  17722. }
  17723. };
  17724. // Will apply current transform to mesh and reset world matrix
  17725. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  17726. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  17727. this.scaling.copyFromFloats(1, 1, 1);
  17728. this.position.copyFromFloats(0, 0, 0);
  17729. this.rotation.copyFromFloats(0, 0, 0);
  17730. //only if quaternion is already set
  17731. if (this.rotationQuaternion) {
  17732. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  17733. }
  17734. this._worldMatrix = BABYLON.Matrix.Identity();
  17735. };
  17736. // Cache
  17737. Mesh.prototype._resetPointsArrayCache = function () {
  17738. this._positions = null;
  17739. };
  17740. Mesh.prototype._generatePointsArray = function () {
  17741. if (this._positions)
  17742. return true;
  17743. this._positions = [];
  17744. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17745. if (!data) {
  17746. return false;
  17747. }
  17748. for (var index = 0; index < data.length; index += 3) {
  17749. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  17750. }
  17751. return true;
  17752. };
  17753. // Clone
  17754. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  17755. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17756. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  17757. };
  17758. // Dispose
  17759. Mesh.prototype.dispose = function (doNotRecurse) {
  17760. if (this._geometry) {
  17761. this._geometry.releaseForMesh(this, true);
  17762. }
  17763. // Instances
  17764. if (this._worldMatricesInstancesBuffer) {
  17765. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17766. this._worldMatricesInstancesBuffer = null;
  17767. }
  17768. while (this.instances.length) {
  17769. this.instances[0].dispose();
  17770. }
  17771. _super.prototype.dispose.call(this, doNotRecurse);
  17772. };
  17773. // Geometric tools
  17774. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  17775. var _this = this;
  17776. var scene = this.getScene();
  17777. var onload = function (img) {
  17778. // Getting height map data
  17779. var canvas = document.createElement("canvas");
  17780. var context = canvas.getContext("2d");
  17781. var heightMapWidth = img.width;
  17782. var heightMapHeight = img.height;
  17783. canvas.width = heightMapWidth;
  17784. canvas.height = heightMapHeight;
  17785. context.drawImage(img, 0, 0);
  17786. // Create VertexData from map data
  17787. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17788. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  17789. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  17790. //execute success callback, if set
  17791. if (onSuccess) {
  17792. onSuccess(_this);
  17793. }
  17794. };
  17795. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17796. };
  17797. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  17798. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  17799. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  17800. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17801. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  17802. return;
  17803. }
  17804. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17805. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17806. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17807. var position = BABYLON.Vector3.Zero();
  17808. var normal = BABYLON.Vector3.Zero();
  17809. var uv = BABYLON.Vector2.Zero();
  17810. for (var index = 0; index < positions.length; index += 3) {
  17811. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  17812. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  17813. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  17814. // Compute height
  17815. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  17816. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  17817. var pos = (u + v * heightMapWidth) * 4;
  17818. var r = buffer[pos] / 255.0;
  17819. var g = buffer[pos + 1] / 255.0;
  17820. var b = buffer[pos + 2] / 255.0;
  17821. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17822. normal.normalize();
  17823. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  17824. position = position.add(normal);
  17825. position.toArray(positions, index);
  17826. }
  17827. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  17828. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  17829. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  17830. };
  17831. /**
  17832. * Modify the mesh to get a flat shading rendering.
  17833. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  17834. * Warning : the mesh is really modified.
  17835. */
  17836. Mesh.prototype.convertToFlatShadedMesh = function () {
  17837. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  17838. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17839. var kinds = this.getVerticesDataKinds();
  17840. var vbs = [];
  17841. var data = [];
  17842. var newdata = [];
  17843. var updatableNormals = false;
  17844. var kindIndex;
  17845. var kind;
  17846. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17847. kind = kinds[kindIndex];
  17848. var vertexBuffer = this.getVertexBuffer(kind);
  17849. if (kind === BABYLON.VertexBuffer.NormalKind) {
  17850. updatableNormals = vertexBuffer.isUpdatable();
  17851. kinds.splice(kindIndex, 1);
  17852. kindIndex--;
  17853. continue;
  17854. }
  17855. vbs[kind] = vertexBuffer;
  17856. data[kind] = vbs[kind].getData();
  17857. newdata[kind] = [];
  17858. }
  17859. // Save previous submeshes
  17860. var previousSubmeshes = this.subMeshes.slice(0);
  17861. var indices = this.getIndices();
  17862. var totalIndices = this.getTotalIndices();
  17863. // Generating unique vertices per face
  17864. var index;
  17865. for (index = 0; index < totalIndices; index++) {
  17866. var vertexIndex = indices[index];
  17867. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17868. kind = kinds[kindIndex];
  17869. var stride = vbs[kind].getStrideSize();
  17870. for (var offset = 0; offset < stride; offset++) {
  17871. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17872. }
  17873. }
  17874. }
  17875. // Updating faces & normal
  17876. var normals = [];
  17877. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  17878. for (index = 0; index < totalIndices; index += 3) {
  17879. indices[index] = index;
  17880. indices[index + 1] = index + 1;
  17881. indices[index + 2] = index + 2;
  17882. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  17883. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  17884. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  17885. var p1p2 = p1.subtract(p2);
  17886. var p3p2 = p3.subtract(p2);
  17887. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17888. // Store same normals for every vertex
  17889. for (var localIndex = 0; localIndex < 3; localIndex++) {
  17890. normals.push(normal.x);
  17891. normals.push(normal.y);
  17892. normals.push(normal.z);
  17893. }
  17894. }
  17895. this.setIndices(indices);
  17896. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  17897. // Updating vertex buffers
  17898. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17899. kind = kinds[kindIndex];
  17900. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17901. }
  17902. // Updating submeshes
  17903. this.releaseSubMeshes();
  17904. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17905. var previousOne = previousSubmeshes[submeshIndex];
  17906. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17907. }
  17908. this.synchronizeInstances();
  17909. };
  17910. /**
  17911. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  17912. * In other words, more vertices, no more indices and a single bigger VBO.
  17913. */
  17914. Mesh.prototype.convertToUnIndexedMesh = function () {
  17915. /// <summary>Remove indices by unfolding faces into buffers</summary>
  17916. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17917. var kinds = this.getVerticesDataKinds();
  17918. var vbs = [];
  17919. var data = [];
  17920. var newdata = [];
  17921. var updatableNormals = false;
  17922. var kindIndex;
  17923. var kind;
  17924. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17925. kind = kinds[kindIndex];
  17926. var vertexBuffer = this.getVertexBuffer(kind);
  17927. vbs[kind] = vertexBuffer;
  17928. data[kind] = vbs[kind].getData();
  17929. newdata[kind] = [];
  17930. }
  17931. // Save previous submeshes
  17932. var previousSubmeshes = this.subMeshes.slice(0);
  17933. var indices = this.getIndices();
  17934. var totalIndices = this.getTotalIndices();
  17935. // Generating unique vertices per face
  17936. var index;
  17937. for (index = 0; index < totalIndices; index++) {
  17938. var vertexIndex = indices[index];
  17939. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17940. kind = kinds[kindIndex];
  17941. var stride = vbs[kind].getStrideSize();
  17942. for (var offset = 0; offset < stride; offset++) {
  17943. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17944. }
  17945. }
  17946. }
  17947. // Updating indices
  17948. for (index = 0; index < totalIndices; index += 3) {
  17949. indices[index] = index;
  17950. indices[index + 1] = index + 1;
  17951. indices[index + 2] = index + 2;
  17952. }
  17953. this.setIndices(indices);
  17954. // Updating vertex buffers
  17955. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17956. kind = kinds[kindIndex];
  17957. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17958. }
  17959. // Updating submeshes
  17960. this.releaseSubMeshes();
  17961. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17962. var previousOne = previousSubmeshes[submeshIndex];
  17963. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17964. }
  17965. this._unIndexed = true;
  17966. this.synchronizeInstances();
  17967. };
  17968. /**
  17969. * Inverses facet orientations and inverts also the normals with `flipNormals` (default false) if true.
  17970. * Warning : the mesh is really modified.
  17971. */
  17972. Mesh.prototype.flipFaces = function (flipNormals) {
  17973. if (flipNormals === void 0) { flipNormals = false; }
  17974. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  17975. var i;
  17976. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17977. for (i = 0; i < vertex_data.normals.length; i++) {
  17978. vertex_data.normals[i] *= -1;
  17979. }
  17980. }
  17981. var temp;
  17982. for (i = 0; i < vertex_data.indices.length; i += 3) {
  17983. // reassign indices
  17984. temp = vertex_data.indices[i + 1];
  17985. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  17986. vertex_data.indices[i + 2] = temp;
  17987. }
  17988. vertex_data.applyToMesh(this);
  17989. };
  17990. // Instances
  17991. /**
  17992. * Creates a new `InstancedMesh` object from the mesh model.
  17993. */
  17994. Mesh.prototype.createInstance = function (name) {
  17995. return new BABYLON.InstancedMesh(name, this);
  17996. };
  17997. Mesh.prototype.synchronizeInstances = function () {
  17998. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  17999. var instance = this.instances[instanceIndex];
  18000. instance._syncSubMeshes();
  18001. }
  18002. };
  18003. /**
  18004. * Simplify the mesh according to the given array of settings.
  18005. * Function will return immediately and will simplify async.
  18006. * @param settings a collection of simplification settings.
  18007. * @param parallelProcessing should all levels calculate parallel or one after the other.
  18008. * @param type the type of simplification to run.
  18009. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  18010. */
  18011. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  18012. if (parallelProcessing === void 0) { parallelProcessing = true; }
  18013. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  18014. this.getScene().simplificationQueue.addTask({
  18015. settings: settings,
  18016. parallelProcessing: parallelProcessing,
  18017. mesh: this,
  18018. simplificationType: simplificationType,
  18019. successCallback: successCallback
  18020. });
  18021. };
  18022. /**
  18023. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  18024. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  18025. * This should be used together with the simplification to avoid disappearing triangles.
  18026. * @param successCallback an optional success callback to be called after the optimization finished.
  18027. */
  18028. Mesh.prototype.optimizeIndices = function (successCallback) {
  18029. var _this = this;
  18030. var indices = this.getIndices();
  18031. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18032. var vectorPositions = [];
  18033. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  18034. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  18035. }
  18036. var dupes = [];
  18037. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  18038. var realPos = vectorPositions.length - 1 - iteration;
  18039. var testedPosition = vectorPositions[realPos];
  18040. for (var j = 0; j < realPos; ++j) {
  18041. var againstPosition = vectorPositions[j];
  18042. if (testedPosition.equals(againstPosition)) {
  18043. dupes[realPos] = j;
  18044. break;
  18045. }
  18046. }
  18047. }, function () {
  18048. for (var i = 0; i < indices.length; ++i) {
  18049. indices[i] = dupes[indices[i]] || indices[i];
  18050. }
  18051. //indices are now reordered
  18052. var originalSubMeshes = _this.subMeshes.slice(0);
  18053. _this.setIndices(indices);
  18054. _this.subMeshes = originalSubMeshes;
  18055. if (successCallback) {
  18056. successCallback(_this);
  18057. }
  18058. });
  18059. };
  18060. // Statics
  18061. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  18062. var mesh = new Mesh(parsedMesh.name, scene);
  18063. mesh.id = parsedMesh.id;
  18064. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18065. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18066. if (parsedMesh.rotationQuaternion) {
  18067. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18068. }
  18069. else if (parsedMesh.rotation) {
  18070. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18071. }
  18072. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18073. if (parsedMesh.localMatrix) {
  18074. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18075. }
  18076. else if (parsedMesh.pivotMatrix) {
  18077. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18078. }
  18079. mesh.setEnabled(parsedMesh.isEnabled);
  18080. mesh.isVisible = parsedMesh.isVisible;
  18081. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18082. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18083. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18084. if (parsedMesh.applyFog !== undefined) {
  18085. mesh.applyFog = parsedMesh.applyFog;
  18086. }
  18087. if (parsedMesh.pickable !== undefined) {
  18088. mesh.isPickable = parsedMesh.pickable;
  18089. }
  18090. if (parsedMesh.alphaIndex !== undefined) {
  18091. mesh.alphaIndex = parsedMesh.alphaIndex;
  18092. }
  18093. mesh.receiveShadows = parsedMesh.receiveShadows;
  18094. mesh.billboardMode = parsedMesh.billboardMode;
  18095. if (parsedMesh.visibility !== undefined) {
  18096. mesh.visibility = parsedMesh.visibility;
  18097. }
  18098. mesh.checkCollisions = parsedMesh.checkCollisions;
  18099. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18100. // freezeWorldMatrix
  18101. if (parsedMesh.freezeWorldMatrix) {
  18102. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18103. }
  18104. // Parent
  18105. if (parsedMesh.parentId) {
  18106. mesh._waitingParentId = parsedMesh.parentId;
  18107. }
  18108. // Actions
  18109. if (parsedMesh.actions !== undefined) {
  18110. mesh._waitingActions = parsedMesh.actions;
  18111. }
  18112. // Geometry
  18113. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18114. if (parsedMesh.delayLoadingFile) {
  18115. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18116. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18117. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18118. if (parsedMesh._binaryInfo) {
  18119. mesh._binaryInfo = parsedMesh._binaryInfo;
  18120. }
  18121. mesh._delayInfo = [];
  18122. if (parsedMesh.hasUVs) {
  18123. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18124. }
  18125. if (parsedMesh.hasUVs2) {
  18126. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18127. }
  18128. if (parsedMesh.hasUVs3) {
  18129. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18130. }
  18131. if (parsedMesh.hasUVs4) {
  18132. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18133. }
  18134. if (parsedMesh.hasUVs5) {
  18135. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18136. }
  18137. if (parsedMesh.hasUVs6) {
  18138. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18139. }
  18140. if (parsedMesh.hasColors) {
  18141. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18142. }
  18143. if (parsedMesh.hasMatricesIndices) {
  18144. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18145. }
  18146. if (parsedMesh.hasMatricesWeights) {
  18147. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18148. }
  18149. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18150. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18151. mesh._checkDelayState();
  18152. }
  18153. }
  18154. else {
  18155. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18156. }
  18157. // Material
  18158. if (parsedMesh.materialId) {
  18159. mesh.setMaterialByID(parsedMesh.materialId);
  18160. }
  18161. else {
  18162. mesh.material = null;
  18163. }
  18164. // Skeleton
  18165. if (parsedMesh.skeletonId > -1) {
  18166. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18167. if (parsedMesh.numBoneInfluencers) {
  18168. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18169. }
  18170. }
  18171. // Animations
  18172. if (parsedMesh.animations) {
  18173. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18174. var parsedAnimation = parsedMesh.animations[animationIndex];
  18175. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18176. }
  18177. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18178. }
  18179. if (parsedMesh.autoAnimate) {
  18180. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18181. }
  18182. // Layer Mask
  18183. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18184. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18185. }
  18186. else {
  18187. mesh.layerMask = 0x0FFFFFFF;
  18188. }
  18189. //(Deprecated) physics
  18190. if (parsedMesh.physicsImpostor) {
  18191. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18192. mass: parsedMesh.physicsMass,
  18193. friction: parsedMesh.physicsFriction,
  18194. restitution: parsedMesh.physicsRestitution
  18195. }, scene);
  18196. }
  18197. // Instances
  18198. if (parsedMesh.instances) {
  18199. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18200. var parsedInstance = parsedMesh.instances[index];
  18201. var instance = mesh.createInstance(parsedInstance.name);
  18202. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18203. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18204. if (parsedInstance.rotationQuaternion) {
  18205. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18206. }
  18207. else if (parsedInstance.rotation) {
  18208. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18209. }
  18210. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18211. instance.checkCollisions = mesh.checkCollisions;
  18212. if (parsedMesh.animations) {
  18213. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18214. parsedAnimation = parsedMesh.animations[animationIndex];
  18215. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18216. }
  18217. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18218. }
  18219. }
  18220. }
  18221. return mesh;
  18222. };
  18223. /**
  18224. * Creates a ribbon mesh.
  18225. * Please consider using the same method from the `MeshBuilder` class instead.
  18226. * 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.
  18227. *
  18228. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18229. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18230. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18231. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18232. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  18233. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  18234. * 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
  18235. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18236. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18238. */
  18239. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  18240. return BABYLON.MeshBuilder.CreateRibbon(name, {
  18241. pathArray: pathArray,
  18242. closeArray: closeArray,
  18243. closePath: closePath,
  18244. offset: offset,
  18245. updatable: updatable,
  18246. sideOrientation: sideOrientation,
  18247. instance: instance
  18248. }, scene);
  18249. };
  18250. /**
  18251. * Creates a plane polygonal mesh. By default, this is a disc.
  18252. * Please consider using the same method from the `MeshBuilder` class instead.
  18253. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18254. * 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.
  18255. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18256. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18257. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18258. */
  18259. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  18260. var options = {
  18261. radius: radius,
  18262. tessellation: tessellation,
  18263. sideOrientation: sideOrientation,
  18264. updatable: updatable
  18265. };
  18266. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  18267. };
  18268. /**
  18269. * Creates a box mesh.
  18270. * Please consider using the same method from the `MeshBuilder` class instead.
  18271. * The parameter `size` sets the size (float) of each box side (default 1).
  18272. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18273. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18275. */
  18276. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  18277. var options = {
  18278. size: size,
  18279. sideOrientation: sideOrientation,
  18280. updatable: updatable
  18281. };
  18282. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  18283. };
  18284. /**
  18285. * Creates a sphere mesh.
  18286. * Please consider using the same method from the `MeshBuilder` class instead.
  18287. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18288. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18289. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18290. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18291. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18292. */
  18293. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  18294. var options = {
  18295. segments: segments,
  18296. diameterX: diameter,
  18297. diameterY: diameter,
  18298. diameterZ: diameter,
  18299. sideOrientation: sideOrientation,
  18300. updatable: updatable
  18301. };
  18302. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  18303. };
  18304. /**
  18305. * Creates a cylinder or a cone mesh.
  18306. * Please consider using the same method from the `MeshBuilder` class instead.
  18307. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18308. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18309. * 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.
  18310. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18311. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18312. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18313. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18315. */
  18316. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  18317. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  18318. if (scene !== undefined) {
  18319. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  18320. updatable = scene;
  18321. }
  18322. scene = subdivisions;
  18323. subdivisions = 1;
  18324. }
  18325. var options = {
  18326. height: height,
  18327. diameterTop: diameterTop,
  18328. diameterBottom: diameterBottom,
  18329. tessellation: tessellation,
  18330. subdivisions: subdivisions,
  18331. sideOrientation: sideOrientation,
  18332. updatable: updatable
  18333. };
  18334. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  18335. };
  18336. // Torus (Code from SharpDX.org)
  18337. /**
  18338. * Creates a torus mesh.
  18339. * Please consider using the same method from the `MeshBuilder` class instead.
  18340. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18341. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18342. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18343. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18344. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18345. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18346. */
  18347. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  18348. var options = {
  18349. diameter: diameter,
  18350. thickness: thickness,
  18351. tessellation: tessellation,
  18352. sideOrientation: sideOrientation,
  18353. updatable: updatable
  18354. };
  18355. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  18356. };
  18357. /**
  18358. * Creates a torus knot mesh.
  18359. * Please consider using the same method from the `MeshBuilder` class instead.
  18360. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18361. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18362. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18363. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18365. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18366. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18367. */
  18368. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  18369. var options = {
  18370. radius: radius,
  18371. tube: tube,
  18372. radialSegments: radialSegments,
  18373. tubularSegments: tubularSegments,
  18374. p: p,
  18375. q: q,
  18376. sideOrientation: sideOrientation,
  18377. updatable: updatable
  18378. };
  18379. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  18380. };
  18381. /**
  18382. * Creates a line mesh.
  18383. * Please consider using the same method from the `MeshBuilder` class instead.
  18384. * 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.
  18385. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18386. * The parameter `points` is an array successive Vector3.
  18387. * 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
  18388. * When updating an instance, remember that only point positions can change, not the number of points.
  18389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18390. */
  18391. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  18392. var options = {
  18393. points: points,
  18394. updatable: updatable,
  18395. instance: instance
  18396. };
  18397. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  18398. };
  18399. /**
  18400. * Creates a dashed line mesh.
  18401. * Please consider using the same method from the `MeshBuilder` class instead.
  18402. * 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.
  18403. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18404. * The parameter `points` is an array successive Vector3.
  18405. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18406. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18407. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18408. * 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
  18409. * When updating an instance, remember that only point positions can change, not the number of points.
  18410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18411. */
  18412. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  18413. var options = {
  18414. points: points,
  18415. dashSize: dashSize,
  18416. gapSize: gapSize,
  18417. dashNb: dashNb,
  18418. updatable: updatable
  18419. };
  18420. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  18421. };
  18422. /**
  18423. * Creates an extruded shape mesh.
  18424. * 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.
  18425. * Please consider using the same method from the `MeshBuilder` class instead.
  18426. *
  18427. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18428. * 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
  18429. * extruded along the Z axis.
  18430. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18431. * 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.
  18432. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18433. * 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
  18434. * 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
  18435. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18436. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18437. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18439. */
  18440. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  18441. var options = {
  18442. shape: shape,
  18443. path: path,
  18444. scale: scale,
  18445. rotation: rotation,
  18446. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18447. sideOrientation: sideOrientation,
  18448. instance: instance,
  18449. updatable: updatable
  18450. };
  18451. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  18452. };
  18453. /**
  18454. * Creates an custom extruded shape mesh.
  18455. * 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.
  18456. * Please consider using the same method from the `MeshBuilder` class instead.
  18457. *
  18458. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18459. * 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
  18460. * extruded along the Z axis.
  18461. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18462. * 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
  18463. * and the distance of this point from the begining of the path :
  18464. * ```rotationFunction = function(i, distance) {
  18465. * // do things
  18466. * return rotationValue; }```
  18467. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18468. * 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
  18469. * and the distance of this point from the begining of the path :
  18470. * ````scaleFunction = function(i, distance) {
  18471. * // do things
  18472. * return scaleValue;}```
  18473. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18474. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18475. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18476. * 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
  18477. * 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
  18478. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18479. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18480. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18482. */
  18483. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  18484. var options = {
  18485. shape: shape,
  18486. path: path,
  18487. scaleFunction: scaleFunction,
  18488. rotationFunction: rotationFunction,
  18489. ribbonCloseArray: ribbonCloseArray,
  18490. ribbonClosePath: ribbonClosePath,
  18491. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18492. sideOrientation: sideOrientation,
  18493. instance: instance,
  18494. updatable: updatable
  18495. };
  18496. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  18497. };
  18498. /**
  18499. * Creates lathe mesh.
  18500. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18501. * Please consider using the same method from the `MeshBuilder` class instead.
  18502. *
  18503. * 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
  18504. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18505. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  18506. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  18507. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18508. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18509. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18510. */
  18511. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  18512. var options = {
  18513. shape: shape,
  18514. radius: radius,
  18515. tessellation: tessellation,
  18516. sideOrientation: sideOrientation,
  18517. updatable: updatable
  18518. };
  18519. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  18520. };
  18521. /**
  18522. * Creates a plane mesh.
  18523. * Please consider using the same method from the `MeshBuilder` class instead.
  18524. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  18525. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18526. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18527. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18528. */
  18529. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  18530. var options = {
  18531. size: size,
  18532. width: size,
  18533. height: size,
  18534. sideOrientation: sideOrientation,
  18535. updatable: updatable
  18536. };
  18537. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  18538. };
  18539. /**
  18540. * Creates a ground mesh.
  18541. * Please consider using the same method from the `MeshBuilder` class instead.
  18542. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  18543. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  18544. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18545. */
  18546. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  18547. var options = {
  18548. width: width,
  18549. height: height,
  18550. subdivisions: subdivisions,
  18551. updatable: updatable
  18552. };
  18553. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  18554. };
  18555. /**
  18556. * Creates a tiled ground mesh.
  18557. * Please consider using the same method from the `MeshBuilder` class instead.
  18558. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  18559. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  18560. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  18561. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  18562. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  18563. * numbers of subdivisions on the ground width and height of each tile.
  18564. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18565. */
  18566. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  18567. var options = {
  18568. xmin: xmin,
  18569. zmin: zmin,
  18570. xmax: xmax,
  18571. zmax: zmax,
  18572. subdivisions: subdivisions,
  18573. precision: precision,
  18574. updatable: updatable
  18575. };
  18576. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  18577. };
  18578. /**
  18579. * Creates a ground mesh from a height map.
  18580. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  18581. * Please consider using the same method from the `MeshBuilder` class instead.
  18582. * The parameter `url` sets the URL of the height map image resource.
  18583. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  18584. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  18585. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  18586. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  18587. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  18588. * This function is passed the newly built mesh : ```function(mesh) { // do things
  18589. * return; }```
  18590. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18591. */
  18592. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  18593. var options = {
  18594. width: width,
  18595. height: height,
  18596. subdivisions: subdivisions,
  18597. minHeight: minHeight,
  18598. maxHeight: maxHeight,
  18599. updatable: updatable,
  18600. onReady: onReady
  18601. };
  18602. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  18603. };
  18604. /**
  18605. * Creates a tube mesh.
  18606. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18607. *
  18608. * Please consider using the same method from the `MeshBuilder` class instead.
  18609. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  18610. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  18611. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  18612. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  18613. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  18614. * It must return a radius value (positive float) :
  18615. * ```var radiusFunction = function(i, distance) {
  18616. * // do things
  18617. * return radius; }```
  18618. * 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
  18619. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  18620. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18621. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18623. */
  18624. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  18625. var options = {
  18626. path: path,
  18627. radius: radius,
  18628. tessellation: tessellation,
  18629. radiusFunction: radiusFunction,
  18630. arc: 1,
  18631. cap: cap,
  18632. updatable: updatable,
  18633. sideOrientation: sideOrientation,
  18634. instance: instance
  18635. };
  18636. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  18637. };
  18638. /**
  18639. * Creates a polyhedron mesh.
  18640. *
  18641. * Please consider using the same method from the `MeshBuilder` class instead.
  18642. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  18643. * to choose the wanted type.
  18644. * The parameter `size` (positive float, default 1) sets the polygon size.
  18645. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  18646. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  18647. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  18648. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  18649. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  18650. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  18651. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18652. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18653. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18654. */
  18655. Mesh.CreatePolyhedron = function (name, options, scene) {
  18656. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  18657. };
  18658. /**
  18659. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  18660. * Please consider using the same method from the `MeshBuilder` class instead.
  18661. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  18662. * 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`).
  18663. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  18664. * 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.
  18665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18666. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18668. */
  18669. Mesh.CreateIcoSphere = function (name, options, scene) {
  18670. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  18671. };
  18672. /**
  18673. * Creates a decal mesh.
  18674. * Please consider using the same method from the `MeshBuilder` class instead.
  18675. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  18676. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  18677. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  18678. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  18679. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  18680. */
  18681. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  18682. var options = {
  18683. position: position,
  18684. normal: normal,
  18685. size: size,
  18686. angle: angle
  18687. };
  18688. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  18689. };
  18690. // Skeletons
  18691. /**
  18692. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18693. */
  18694. Mesh.prototype.setPositionsForCPUSkinning = function () {
  18695. var source;
  18696. if (!this._sourcePositions) {
  18697. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18698. this._sourcePositions = new Float32Array(source);
  18699. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  18700. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  18701. }
  18702. }
  18703. return this._sourcePositions;
  18704. };
  18705. /**
  18706. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18707. */
  18708. Mesh.prototype.setNormalsForCPUSkinning = function () {
  18709. var source;
  18710. if (!this._sourceNormals) {
  18711. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18712. this._sourceNormals = new Float32Array(source);
  18713. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  18714. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  18715. }
  18716. }
  18717. return this._sourceNormals;
  18718. };
  18719. /**
  18720. * Update the vertex buffers by applying transformation from the bones
  18721. * @param {skeleton} skeleton to apply
  18722. */
  18723. Mesh.prototype.applySkeleton = function (skeleton) {
  18724. if (!this.geometry) {
  18725. return;
  18726. }
  18727. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  18728. return;
  18729. }
  18730. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  18731. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18732. return this;
  18733. }
  18734. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18735. return this;
  18736. }
  18737. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18738. return this;
  18739. }
  18740. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18741. return this;
  18742. }
  18743. if (!this._sourcePositions) {
  18744. this.setPositionsForCPUSkinning();
  18745. }
  18746. if (!this._sourceNormals) {
  18747. this.setNormalsForCPUSkinning();
  18748. }
  18749. // positionsData checks for not being Float32Array will only pass at most once
  18750. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18751. if (!(positionsData instanceof Float32Array)) {
  18752. positionsData = new Float32Array(positionsData);
  18753. }
  18754. // normalsData checks for not being Float32Array will only pass at most once
  18755. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18756. if (!(normalsData instanceof Float32Array)) {
  18757. normalsData = new Float32Array(normalsData);
  18758. }
  18759. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18760. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18761. var needExtras = this.numBoneInfluencers > 4;
  18762. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  18763. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  18764. var skeletonMatrices = skeleton.getTransformMatrices(this);
  18765. var tempVector3 = BABYLON.Vector3.Zero();
  18766. var finalMatrix = new BABYLON.Matrix();
  18767. var tempMatrix = new BABYLON.Matrix();
  18768. var matWeightIdx = 0;
  18769. var inf;
  18770. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  18771. var weight;
  18772. for (inf = 0; inf < 4; inf++) {
  18773. weight = matricesWeightsData[matWeightIdx + inf];
  18774. if (weight > 0) {
  18775. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18776. finalMatrix.addToSelf(tempMatrix);
  18777. }
  18778. else
  18779. break;
  18780. }
  18781. if (needExtras) {
  18782. for (inf = 0; inf < 4; inf++) {
  18783. weight = matricesWeightsExtraData[matWeightIdx + inf];
  18784. if (weight > 0) {
  18785. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18786. finalMatrix.addToSelf(tempMatrix);
  18787. }
  18788. else
  18789. break;
  18790. }
  18791. }
  18792. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  18793. tempVector3.toArray(positionsData, index);
  18794. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  18795. tempVector3.toArray(normalsData, index);
  18796. finalMatrix.reset();
  18797. }
  18798. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  18799. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  18800. return this;
  18801. };
  18802. // Tools
  18803. Mesh.MinMax = function (meshes) {
  18804. var minVector = null;
  18805. var maxVector = null;
  18806. for (var i in meshes) {
  18807. var mesh = meshes[i];
  18808. var boundingBox = mesh.getBoundingInfo().boundingBox;
  18809. if (!minVector) {
  18810. minVector = boundingBox.minimumWorld;
  18811. maxVector = boundingBox.maximumWorld;
  18812. continue;
  18813. }
  18814. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  18815. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  18816. }
  18817. return {
  18818. min: minVector,
  18819. max: maxVector
  18820. };
  18821. };
  18822. Mesh.Center = function (meshesOrMinMaxVector) {
  18823. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  18824. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  18825. };
  18826. /**
  18827. * Merge the array of meshes into a single mesh for performance reasons.
  18828. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  18829. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  18830. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  18831. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  18832. */
  18833. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  18834. if (disposeSource === void 0) { disposeSource = true; }
  18835. var index;
  18836. if (!allow32BitsIndices) {
  18837. var totalVertices = 0;
  18838. // Counting vertices
  18839. for (index = 0; index < meshes.length; index++) {
  18840. if (meshes[index]) {
  18841. totalVertices += meshes[index].getTotalVertices();
  18842. if (totalVertices > 65536) {
  18843. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  18844. return null;
  18845. }
  18846. }
  18847. }
  18848. }
  18849. // Merge
  18850. var vertexData;
  18851. var otherVertexData;
  18852. var source;
  18853. for (index = 0; index < meshes.length; index++) {
  18854. if (meshes[index]) {
  18855. meshes[index].computeWorldMatrix(true);
  18856. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  18857. otherVertexData.transform(meshes[index].getWorldMatrix());
  18858. if (vertexData) {
  18859. vertexData.merge(otherVertexData);
  18860. }
  18861. else {
  18862. vertexData = otherVertexData;
  18863. source = meshes[index];
  18864. }
  18865. }
  18866. }
  18867. if (!meshSubclass) {
  18868. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  18869. }
  18870. vertexData.applyToMesh(meshSubclass);
  18871. // Setting properties
  18872. meshSubclass.material = source.material;
  18873. meshSubclass.checkCollisions = source.checkCollisions;
  18874. // Cleaning
  18875. if (disposeSource) {
  18876. for (index = 0; index < meshes.length; index++) {
  18877. if (meshes[index]) {
  18878. meshes[index].dispose();
  18879. }
  18880. }
  18881. }
  18882. return meshSubclass;
  18883. };
  18884. // Consts
  18885. Mesh._FRONTSIDE = 0;
  18886. Mesh._BACKSIDE = 1;
  18887. Mesh._DOUBLESIDE = 2;
  18888. Mesh._DEFAULTSIDE = 0;
  18889. Mesh._NO_CAP = 0;
  18890. Mesh._CAP_START = 1;
  18891. Mesh._CAP_END = 2;
  18892. Mesh._CAP_ALL = 3;
  18893. return Mesh;
  18894. })(BABYLON.AbstractMesh);
  18895. BABYLON.Mesh = Mesh;
  18896. })(BABYLON || (BABYLON = {}));
  18897. var BABYLON;
  18898. (function (BABYLON) {
  18899. var SubMesh = (function () {
  18900. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  18901. if (createBoundingBox === void 0) { createBoundingBox = true; }
  18902. this.materialIndex = materialIndex;
  18903. this.verticesStart = verticesStart;
  18904. this.verticesCount = verticesCount;
  18905. this.indexStart = indexStart;
  18906. this.indexCount = indexCount;
  18907. this._renderId = 0;
  18908. this._mesh = mesh;
  18909. this._renderingMesh = renderingMesh || mesh;
  18910. mesh.subMeshes.push(this);
  18911. this._trianglePlanes = [];
  18912. this._id = mesh.subMeshes.length - 1;
  18913. if (createBoundingBox) {
  18914. this.refreshBoundingInfo();
  18915. mesh.computeWorldMatrix(true);
  18916. }
  18917. }
  18918. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  18919. get: function () {
  18920. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  18921. },
  18922. enumerable: true,
  18923. configurable: true
  18924. });
  18925. SubMesh.prototype.getBoundingInfo = function () {
  18926. if (this.IsGlobal) {
  18927. return this._mesh.getBoundingInfo();
  18928. }
  18929. return this._boundingInfo;
  18930. };
  18931. SubMesh.prototype.getMesh = function () {
  18932. return this._mesh;
  18933. };
  18934. SubMesh.prototype.getRenderingMesh = function () {
  18935. return this._renderingMesh;
  18936. };
  18937. SubMesh.prototype.getMaterial = function () {
  18938. var rootMaterial = this._renderingMesh.material;
  18939. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  18940. var multiMaterial = rootMaterial;
  18941. return multiMaterial.getSubMaterial(this.materialIndex);
  18942. }
  18943. if (!rootMaterial) {
  18944. return this._mesh.getScene().defaultMaterial;
  18945. }
  18946. return rootMaterial;
  18947. };
  18948. // Methods
  18949. SubMesh.prototype.refreshBoundingInfo = function () {
  18950. this._lastColliderWorldVertices = null;
  18951. if (this.IsGlobal) {
  18952. return;
  18953. }
  18954. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18955. if (!data) {
  18956. this._boundingInfo = this._mesh._boundingInfo;
  18957. return;
  18958. }
  18959. var indices = this._renderingMesh.getIndices();
  18960. var extend;
  18961. //is this the only submesh?
  18962. if (this.indexStart === 0 && this.indexCount === indices.length) {
  18963. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  18964. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  18965. }
  18966. else {
  18967. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  18968. }
  18969. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18970. };
  18971. SubMesh.prototype._checkCollision = function (collider) {
  18972. return this.getBoundingInfo()._checkCollision(collider);
  18973. };
  18974. SubMesh.prototype.updateBoundingInfo = function (world) {
  18975. if (!this.getBoundingInfo()) {
  18976. this.refreshBoundingInfo();
  18977. }
  18978. this.getBoundingInfo().update(world);
  18979. };
  18980. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  18981. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  18982. };
  18983. SubMesh.prototype.render = function (enableAlphaMode) {
  18984. this._renderingMesh.render(this, enableAlphaMode);
  18985. };
  18986. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  18987. if (!this._linesIndexBuffer) {
  18988. var linesIndices = [];
  18989. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  18990. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  18991. }
  18992. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  18993. this.linesIndexCount = linesIndices.length;
  18994. }
  18995. return this._linesIndexBuffer;
  18996. };
  18997. SubMesh.prototype.canIntersects = function (ray) {
  18998. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  18999. };
  19000. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  19001. var intersectInfo = null;
  19002. // LineMesh first as it's also a Mesh...
  19003. if (this._mesh instanceof BABYLON.LinesMesh) {
  19004. var lineMesh = this._mesh;
  19005. // Line test
  19006. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  19007. var p0 = positions[indices[index]];
  19008. var p1 = positions[indices[index + 1]];
  19009. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  19010. if (length < 0) {
  19011. continue;
  19012. }
  19013. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  19014. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  19015. if (fastCheck) {
  19016. break;
  19017. }
  19018. }
  19019. }
  19020. }
  19021. else {
  19022. // Triangles test
  19023. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19024. var p0 = positions[indices[index]];
  19025. var p1 = positions[indices[index + 1]];
  19026. var p2 = positions[indices[index + 2]];
  19027. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  19028. if (currentIntersectInfo) {
  19029. if (currentIntersectInfo.distance < 0) {
  19030. continue;
  19031. }
  19032. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19033. intersectInfo = currentIntersectInfo;
  19034. intersectInfo.faceId = index / 3;
  19035. if (fastCheck) {
  19036. break;
  19037. }
  19038. }
  19039. }
  19040. }
  19041. }
  19042. return intersectInfo;
  19043. };
  19044. // Clone
  19045. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  19046. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  19047. if (!this.IsGlobal) {
  19048. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  19049. }
  19050. return result;
  19051. };
  19052. // Dispose
  19053. SubMesh.prototype.dispose = function () {
  19054. if (this._linesIndexBuffer) {
  19055. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  19056. this._linesIndexBuffer = null;
  19057. }
  19058. // Remove from mesh
  19059. var index = this._mesh.subMeshes.indexOf(this);
  19060. this._mesh.subMeshes.splice(index, 1);
  19061. };
  19062. // Statics
  19063. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  19064. var minVertexIndex = Number.MAX_VALUE;
  19065. var maxVertexIndex = -Number.MAX_VALUE;
  19066. renderingMesh = renderingMesh || mesh;
  19067. var indices = renderingMesh.getIndices();
  19068. for (var index = startIndex; index < startIndex + indexCount; index++) {
  19069. var vertexIndex = indices[index];
  19070. if (vertexIndex < minVertexIndex)
  19071. minVertexIndex = vertexIndex;
  19072. if (vertexIndex > maxVertexIndex)
  19073. maxVertexIndex = vertexIndex;
  19074. }
  19075. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  19076. };
  19077. return SubMesh;
  19078. })();
  19079. BABYLON.SubMesh = SubMesh;
  19080. })(BABYLON || (BABYLON = {}));
  19081. var BABYLON;
  19082. (function (BABYLON) {
  19083. var MeshBuilder = (function () {
  19084. function MeshBuilder() {
  19085. }
  19086. /**
  19087. * Creates a box mesh.
  19088. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19089. * The parameter `size` sets the size (float) of each box side (default 1).
  19090. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19091. * 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).
  19092. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19093. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19094. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19095. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19096. */
  19097. MeshBuilder.CreateBox = function (name, options, scene) {
  19098. var box = new BABYLON.Mesh(name, scene);
  19099. var vertexData = BABYLON.VertexData.CreateBox(options);
  19100. vertexData.applyToMesh(box, options.updatable);
  19101. return box;
  19102. };
  19103. /**
  19104. * Creates a sphere mesh.
  19105. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19106. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19107. * 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`).
  19108. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19109. * 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
  19110. * 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).
  19111. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19112. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19113. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19114. */
  19115. MeshBuilder.CreateSphere = function (name, options, scene) {
  19116. var sphere = new BABYLON.Mesh(name, scene);
  19117. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19118. vertexData.applyToMesh(sphere, options.updatable);
  19119. return sphere;
  19120. };
  19121. /**
  19122. * Creates a plane polygonal mesh. By default, this is a disc.
  19123. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19124. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19125. * 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.
  19126. * 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
  19127. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19128. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19129. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19130. */
  19131. MeshBuilder.CreateDisc = function (name, options, scene) {
  19132. var disc = new BABYLON.Mesh(name, scene);
  19133. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19134. vertexData.applyToMesh(disc, options.updatable);
  19135. return disc;
  19136. };
  19137. /**
  19138. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19139. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19140. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19141. * 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`).
  19142. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19143. * 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.
  19144. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19145. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19146. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19147. */
  19148. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19149. var sphere = new BABYLON.Mesh(name, scene);
  19150. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19151. vertexData.applyToMesh(sphere, options.updatable);
  19152. return sphere;
  19153. };
  19154. ;
  19155. /**
  19156. * Creates a ribbon mesh.
  19157. * 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.
  19158. *
  19159. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19160. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19161. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19162. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19163. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  19164. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  19165. * 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
  19166. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19167. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19168. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19169. */
  19170. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19171. var pathArray = options.pathArray;
  19172. var closeArray = options.closeArray;
  19173. var closePath = options.closePath;
  19174. var offset = options.offset;
  19175. var sideOrientation = options.sideOrientation;
  19176. var instance = options.instance;
  19177. var updatable = options.updatable;
  19178. if (instance) {
  19179. // positionFunction : ribbon case
  19180. // only pathArray and sideOrientation parameters are taken into account for positions update
  19181. var positionFunction = function (positions) {
  19182. var minlg = pathArray[0].length;
  19183. var i = 0;
  19184. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19185. for (var si = 1; si <= ns; si++) {
  19186. for (var p = 0; p < pathArray.length; p++) {
  19187. var path = pathArray[p];
  19188. var l = path.length;
  19189. minlg = (minlg < l) ? minlg : l;
  19190. var j = 0;
  19191. while (j < minlg) {
  19192. positions[i] = path[j].x;
  19193. positions[i + 1] = path[j].y;
  19194. positions[i + 2] = path[j].z;
  19195. j++;
  19196. i += 3;
  19197. }
  19198. if (instance._closePath) {
  19199. positions[i] = path[0].x;
  19200. positions[i + 1] = path[0].y;
  19201. positions[i + 2] = path[0].z;
  19202. i += 3;
  19203. }
  19204. }
  19205. }
  19206. };
  19207. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19208. positionFunction(positions);
  19209. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19210. if (!(instance.areNormalsFrozen)) {
  19211. var indices = instance.getIndices();
  19212. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19213. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19214. if (instance._closePath) {
  19215. var indexFirst = 0;
  19216. var indexLast = 0;
  19217. for (var p = 0; p < pathArray.length; p++) {
  19218. indexFirst = instance._idx[p] * 3;
  19219. if (p + 1 < pathArray.length) {
  19220. indexLast = (instance._idx[p + 1] - 1) * 3;
  19221. }
  19222. else {
  19223. indexLast = normals.length - 3;
  19224. }
  19225. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  19226. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  19227. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  19228. normals[indexLast] = normals[indexFirst];
  19229. normals[indexLast + 1] = normals[indexFirst + 1];
  19230. normals[indexLast + 2] = normals[indexFirst + 2];
  19231. }
  19232. }
  19233. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19234. }
  19235. return instance;
  19236. }
  19237. else {
  19238. var ribbon = new BABYLON.Mesh(name, scene);
  19239. ribbon.sideOrientation = sideOrientation;
  19240. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  19241. if (closePath) {
  19242. ribbon._idx = vertexData._idx;
  19243. }
  19244. ribbon._closePath = closePath;
  19245. ribbon._closeArray = closeArray;
  19246. vertexData.applyToMesh(ribbon, updatable);
  19247. return ribbon;
  19248. }
  19249. };
  19250. /**
  19251. * Creates a cylinder or a cone mesh.
  19252. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  19253. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19254. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19255. * 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.
  19256. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19257. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19258. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  19259. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  19260. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  19261. * 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).
  19262. * 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
  19263. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  19264. * 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
  19265. * 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.
  19266. * If `enclose` is false, a ring surface is one element.
  19267. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  19268. * 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
  19269. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19270. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19271. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19272. */
  19273. MeshBuilder.CreateCylinder = function (name, options, scene) {
  19274. var cylinder = new BABYLON.Mesh(name, scene);
  19275. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  19276. vertexData.applyToMesh(cylinder, options.updatable);
  19277. return cylinder;
  19278. };
  19279. /**
  19280. * Creates a torus mesh.
  19281. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  19282. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19283. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19284. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19285. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19286. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19288. */
  19289. MeshBuilder.CreateTorus = function (name, options, scene) {
  19290. var torus = new BABYLON.Mesh(name, scene);
  19291. var vertexData = BABYLON.VertexData.CreateTorus(options);
  19292. vertexData.applyToMesh(torus, options.updatable);
  19293. return torus;
  19294. };
  19295. /**
  19296. * Creates a torus knot mesh.
  19297. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  19298. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19299. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19300. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19301. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19302. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19303. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19304. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19305. */
  19306. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  19307. var torusKnot = new BABYLON.Mesh(name, scene);
  19308. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  19309. vertexData.applyToMesh(torusKnot, options.updatable);
  19310. return torusKnot;
  19311. };
  19312. /**
  19313. * Creates a line system mesh.
  19314. * A line system is a pool of many lines gathered in a single mesh.
  19315. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  19316. * 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.
  19317. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  19318. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  19319. * 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
  19320. * 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
  19321. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  19322. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19323. */
  19324. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  19325. var instance = options.instance;
  19326. var lines = options.lines;
  19327. if (instance) {
  19328. var positionFunction = function (positions) {
  19329. var i = 0;
  19330. for (var l = 0; l < lines.length; l++) {
  19331. var points = lines[l];
  19332. for (var p = 0; p < points.length; p++) {
  19333. positions[i] = points[p].x;
  19334. positions[i + 1] = points[p].y;
  19335. positions[i + 2] = points[p].z;
  19336. i += 3;
  19337. }
  19338. }
  19339. };
  19340. instance.updateMeshPositions(positionFunction, false);
  19341. return instance;
  19342. }
  19343. // line system creation
  19344. var lineSystem = new BABYLON.LinesMesh(name, scene);
  19345. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  19346. vertexData.applyToMesh(lineSystem, options.updatable);
  19347. return lineSystem;
  19348. };
  19349. /**
  19350. * Creates a line mesh.
  19351. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  19352. * 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.
  19353. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19354. * The parameter `points` is an array successive Vector3.
  19355. * 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
  19356. * When updating an instance, remember that only point positions can change, not the number of points.
  19357. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19358. */
  19359. MeshBuilder.CreateLines = function (name, options, scene) {
  19360. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  19361. return lines;
  19362. };
  19363. /**
  19364. * Creates a dashed line mesh.
  19365. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  19366. * 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.
  19367. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19368. * The parameter `points` is an array successive Vector3.
  19369. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19370. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19371. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19372. * 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
  19373. * When updating an instance, remember that only point positions can change, not the number of points.
  19374. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19375. */
  19376. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  19377. var points = options.points;
  19378. var instance = options.instance;
  19379. var gapSize = options.gapSize;
  19380. var dashNb = options.dashNb;
  19381. var dashSize = options.dashSize;
  19382. if (instance) {
  19383. var positionFunction = function (positions) {
  19384. var curvect = BABYLON.Vector3.Zero();
  19385. var nbSeg = positions.length / 6;
  19386. var lg = 0;
  19387. var nb = 0;
  19388. var shft = 0;
  19389. var dashshft = 0;
  19390. var curshft = 0;
  19391. var p = 0;
  19392. var i = 0;
  19393. var j = 0;
  19394. for (i = 0; i < points.length - 1; i++) {
  19395. points[i + 1].subtractToRef(points[i], curvect);
  19396. lg += curvect.length();
  19397. }
  19398. shft = lg / nbSeg;
  19399. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  19400. for (i = 0; i < points.length - 1; i++) {
  19401. points[i + 1].subtractToRef(points[i], curvect);
  19402. nb = Math.floor(curvect.length() / shft);
  19403. curvect.normalize();
  19404. j = 0;
  19405. while (j < nb && p < positions.length) {
  19406. curshft = shft * j;
  19407. positions[p] = points[i].x + curshft * curvect.x;
  19408. positions[p + 1] = points[i].y + curshft * curvect.y;
  19409. positions[p + 2] = points[i].z + curshft * curvect.z;
  19410. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  19411. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  19412. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  19413. p += 6;
  19414. j++;
  19415. }
  19416. }
  19417. while (p < positions.length) {
  19418. positions[p] = points[i].x;
  19419. positions[p + 1] = points[i].y;
  19420. positions[p + 2] = points[i].z;
  19421. p += 3;
  19422. }
  19423. };
  19424. instance.updateMeshPositions(positionFunction, false);
  19425. return instance;
  19426. }
  19427. // dashed lines creation
  19428. var dashedLines = new BABYLON.LinesMesh(name, scene);
  19429. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  19430. vertexData.applyToMesh(dashedLines, options.updatable);
  19431. dashedLines.dashSize = dashSize;
  19432. dashedLines.gapSize = gapSize;
  19433. return dashedLines;
  19434. };
  19435. /**
  19436. * Creates an extruded shape mesh.
  19437. * 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.
  19438. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  19439. *
  19440. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19441. * 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
  19442. * extruded along the Z axis.
  19443. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19444. * 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.
  19445. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19446. * 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
  19447. * 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
  19448. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19449. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19450. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19452. */
  19453. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  19454. var path = options.path;
  19455. var shape = options.shape;
  19456. var scale = options.scale || 1;
  19457. var rotation = options.rotation || 0;
  19458. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19459. var updatable = options.updatable;
  19460. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19461. var instance = options.instance;
  19462. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  19463. };
  19464. /**
  19465. * Creates an custom extruded shape mesh.
  19466. * 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.
  19467. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  19468. *
  19469. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19470. * 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
  19471. * extruded along the Z axis.
  19472. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19473. * 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
  19474. * and the distance of this point from the begining of the path :
  19475. * ```rotationFunction = function(i, distance) {
  19476. * // do things
  19477. * return rotationValue; }```
  19478. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19479. * 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
  19480. * and the distance of this point from the begining of the path :
  19481. * ````scaleFunction = function(i, distance) {
  19482. * // do things
  19483. * return scaleValue;}```
  19484. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19485. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19486. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19487. * 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
  19488. * 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
  19489. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19490. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19491. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19493. */
  19494. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  19495. var path = options.path;
  19496. var shape = options.shape;
  19497. var scaleFunction = options.scaleFunction || (function () { return 1; });
  19498. var rotationFunction = options.rotationFunction || (function () { return 0; });
  19499. var ribbonCloseArray = options.ribbonCloseArray || false;
  19500. var ribbonClosePath = options.ribbonClosePath || false;
  19501. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19502. var updatable = options.updatable;
  19503. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19504. var instance = options.instance;
  19505. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  19506. };
  19507. /**
  19508. * Creates lathe mesh.
  19509. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19510. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  19511. *
  19512. * 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
  19513. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19514. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19515. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19516. * 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.
  19517. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  19518. * 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
  19519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19520. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19522. */
  19523. MeshBuilder.CreateLathe = function (name, options, scene) {
  19524. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  19525. var closed = (options.closed === undefined) ? true : options.closed;
  19526. var shape = options.shape;
  19527. var radius = options.radius || 1;
  19528. var tessellation = options.tessellation || 64;
  19529. var updatable = options.updatable;
  19530. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19531. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19532. var pi2 = Math.PI * 2;
  19533. var paths = new Array();
  19534. var i = 0;
  19535. var p = 0;
  19536. var step = pi2 / tessellation * arc;
  19537. var rotated;
  19538. var path = new Array();
  19539. ;
  19540. for (i = 0; i <= tessellation; i++) {
  19541. var path = [];
  19542. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  19543. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  19544. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  19545. }
  19546. for (p = 0; p < shape.length; p++) {
  19547. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  19548. path.push(rotated);
  19549. }
  19550. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  19551. 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));
  19552. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  19553. }
  19554. paths.push(path);
  19555. }
  19556. // lathe ribbon
  19557. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  19558. return lathe;
  19559. };
  19560. /**
  19561. * Creates a plane mesh.
  19562. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19563. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19564. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  19565. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  19566. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19567. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19568. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19569. */
  19570. MeshBuilder.CreatePlane = function (name, options, scene) {
  19571. var plane = new BABYLON.Mesh(name, scene);
  19572. var vertexData = BABYLON.VertexData.CreatePlane(options);
  19573. vertexData.applyToMesh(plane, options.updatable);
  19574. if (options.sourcePlane) {
  19575. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  19576. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  19577. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  19578. plane.rotate(vectorProduct, product);
  19579. }
  19580. return plane;
  19581. };
  19582. /**
  19583. * Creates a ground mesh.
  19584. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19585. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19586. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19587. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19588. */
  19589. MeshBuilder.CreateGround = function (name, options, scene) {
  19590. var ground = new BABYLON.GroundMesh(name, scene);
  19591. ground._setReady(false);
  19592. ground._subdivisions = options.subdivisions || 1;
  19593. ground._width = options.width || 1;
  19594. ground._height = options.height || 1;
  19595. ground._maxX = ground._width / 2;
  19596. ground._maxZ = ground._height / 2;
  19597. ground._minX = -ground._maxX;
  19598. ground._minZ = -ground._maxZ;
  19599. var vertexData = BABYLON.VertexData.CreateGround(options);
  19600. vertexData.applyToMesh(ground, options.updatable);
  19601. ground._setReady(true);
  19602. return ground;
  19603. };
  19604. /**
  19605. * Creates a tiled ground mesh.
  19606. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  19607. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19608. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19609. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19610. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19611. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19612. * numbers of subdivisions on the ground width and height of each tile.
  19613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19614. */
  19615. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  19616. var tiledGround = new BABYLON.Mesh(name, scene);
  19617. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  19618. vertexData.applyToMesh(tiledGround, options.updatable);
  19619. return tiledGround;
  19620. };
  19621. /**
  19622. * Creates a ground mesh from a height map.
  19623. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19624. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  19625. * The parameter `url` sets the URL of the height map image resource.
  19626. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19627. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19628. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19629. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19630. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  19631. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19632. * return; }```
  19633. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19634. */
  19635. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  19636. var width = options.width || 10;
  19637. var height = options.height || 10;
  19638. var subdivisions = options.subdivisions || 1;
  19639. var minHeight = options.minHeight;
  19640. var maxHeight = options.maxHeight || 10;
  19641. var updatable = options.updatable;
  19642. var onReady = options.onReady;
  19643. var ground = new BABYLON.GroundMesh(name, scene);
  19644. ground._subdivisions = subdivisions;
  19645. ground._width = width;
  19646. ground._height = height;
  19647. ground._maxX = ground._width / 2;
  19648. ground._maxZ = ground._height / 2;
  19649. ground._minX = -ground._maxX;
  19650. ground._minZ = -ground._maxZ;
  19651. ground._setReady(false);
  19652. var onload = function (img) {
  19653. // Getting height map data
  19654. var canvas = document.createElement("canvas");
  19655. var context = canvas.getContext("2d");
  19656. var bufferWidth = img.width;
  19657. var bufferHeight = img.height;
  19658. canvas.width = bufferWidth;
  19659. canvas.height = bufferHeight;
  19660. context.drawImage(img, 0, 0);
  19661. // Create VertexData from map data
  19662. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19663. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  19664. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  19665. width: width, height: height,
  19666. subdivisions: subdivisions,
  19667. minHeight: minHeight, maxHeight: maxHeight,
  19668. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  19669. });
  19670. vertexData.applyToMesh(ground, updatable);
  19671. ground._setReady(true);
  19672. //execute ready callback, if set
  19673. if (onReady) {
  19674. onReady(ground);
  19675. }
  19676. };
  19677. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19678. return ground;
  19679. };
  19680. /**
  19681. * Creates a tube mesh.
  19682. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19683. *
  19684. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  19685. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  19686. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19687. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19688. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19689. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  19690. * It must return a radius value (positive float) :
  19691. * ```var radiusFunction = function(i, distance) {
  19692. * // do things
  19693. * return radius; }```
  19694. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  19695. * 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
  19696. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  19697. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19698. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19699. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19700. */
  19701. MeshBuilder.CreateTube = function (name, options, scene) {
  19702. var path = options.path;
  19703. var radius = options.radius || 1;
  19704. var tessellation = options.tessellation || 64;
  19705. var radiusFunction = options.radiusFunction;
  19706. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19707. var updatable = options.updatable;
  19708. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19709. var instance = options.instance;
  19710. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  19711. // tube geometry
  19712. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  19713. var tangents = path3D.getTangents();
  19714. var normals = path3D.getNormals();
  19715. var distances = path3D.getDistances();
  19716. var pi2 = Math.PI * 2;
  19717. var step = pi2 / tessellation * arc;
  19718. var returnRadius = function () { return radius; };
  19719. var radiusFunctionFinal = radiusFunction || returnRadius;
  19720. var circlePath;
  19721. var rad;
  19722. var normal;
  19723. var rotated;
  19724. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19725. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19726. for (var i = 0; i < path.length; i++) {
  19727. rad = radiusFunctionFinal(i, distances[i]); // current radius
  19728. circlePath = Array(); // current circle array
  19729. normal = normals[i]; // current normal
  19730. for (var t = 0; t < tessellation; t++) {
  19731. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  19732. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  19733. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  19734. rotated.scaleInPlace(rad).addInPlace(path[i]);
  19735. circlePath[t] = rotated;
  19736. }
  19737. circlePaths[index] = circlePath;
  19738. index++;
  19739. }
  19740. // cap
  19741. var capPath = function (nbPoints, pathIndex) {
  19742. var pointCap = Array();
  19743. for (var i = 0; i < nbPoints; i++) {
  19744. pointCap.push(path[pathIndex]);
  19745. }
  19746. return pointCap;
  19747. };
  19748. switch (cap) {
  19749. case BABYLON.Mesh.NO_CAP:
  19750. break;
  19751. case BABYLON.Mesh.CAP_START:
  19752. circlePaths[0] = capPath(tessellation, 0);
  19753. circlePaths[1] = circlePaths[2].slice(0);
  19754. break;
  19755. case BABYLON.Mesh.CAP_END:
  19756. circlePaths[index] = circlePaths[index - 1].slice(0);
  19757. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19758. break;
  19759. case BABYLON.Mesh.CAP_ALL:
  19760. circlePaths[0] = capPath(tessellation, 0);
  19761. circlePaths[1] = circlePaths[2].slice(0);
  19762. circlePaths[index] = circlePaths[index - 1].slice(0);
  19763. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19764. break;
  19765. default:
  19766. break;
  19767. }
  19768. return circlePaths;
  19769. };
  19770. var path3D;
  19771. var pathArray;
  19772. if (instance) {
  19773. var arc = options.arc || instance.arc;
  19774. path3D = (instance.path3D).update(path);
  19775. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  19776. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  19777. instance.path3D = path3D;
  19778. instance.pathArray = pathArray;
  19779. instance.arc = arc;
  19780. return instance;
  19781. }
  19782. // tube creation
  19783. path3D = new BABYLON.Path3D(path);
  19784. var newPathArray = new Array();
  19785. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19786. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  19787. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  19788. tube.pathArray = pathArray;
  19789. tube.path3D = path3D;
  19790. tube.tessellation = tessellation;
  19791. tube.cap = cap;
  19792. tube.arc = options.arc;
  19793. return tube;
  19794. };
  19795. /**
  19796. * Creates a polyhedron mesh.
  19797. *
  19798. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  19799. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  19800. * to choose the wanted type.
  19801. * The parameter `size` (positive float, default 1) sets the polygon size.
  19802. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19803. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  19804. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  19805. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  19806. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19807. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  19808. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19809. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19811. */
  19812. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  19813. var polyhedron = new BABYLON.Mesh(name, scene);
  19814. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  19815. vertexData.applyToMesh(polyhedron, options.updatable);
  19816. return polyhedron;
  19817. };
  19818. /**
  19819. * Creates a decal mesh.
  19820. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  19821. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  19822. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19823. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19824. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  19825. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19826. */
  19827. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  19828. var indices = sourceMesh.getIndices();
  19829. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19830. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19831. var position = options.position || BABYLON.Vector3.Zero();
  19832. var normal = options.normal || BABYLON.Vector3.Up();
  19833. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  19834. var angle = options.angle || 0;
  19835. // Getting correct rotation
  19836. if (!normal) {
  19837. var target = new BABYLON.Vector3(0, 0, 1);
  19838. var camera = sourceMesh.getScene().activeCamera;
  19839. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  19840. normal = camera.globalPosition.subtract(cameraWorldTarget);
  19841. }
  19842. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  19843. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  19844. var pitch = Math.atan2(normal.y, len);
  19845. // Matrix
  19846. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  19847. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  19848. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  19849. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  19850. var vertexData = new BABYLON.VertexData();
  19851. vertexData.indices = [];
  19852. vertexData.positions = [];
  19853. vertexData.normals = [];
  19854. vertexData.uvs = [];
  19855. var currentVertexDataIndex = 0;
  19856. var extractDecalVector3 = function (indexId) {
  19857. var vertexId = indices[indexId];
  19858. var result = new BABYLON.PositionNormalVertex();
  19859. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  19860. // Send vector to decal local world
  19861. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  19862. // Get normal
  19863. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  19864. return result;
  19865. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  19866. var clip = function (vertices, axis) {
  19867. if (vertices.length === 0) {
  19868. return vertices;
  19869. }
  19870. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  19871. var clipVertices = function (v0, v1) {
  19872. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  19873. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  19874. };
  19875. var result = new Array();
  19876. for (var index = 0; index < vertices.length; index += 3) {
  19877. var v1Out;
  19878. var v2Out;
  19879. var v3Out;
  19880. var total = 0;
  19881. var nV1, nV2, nV3, nV4;
  19882. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  19883. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  19884. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  19885. v1Out = d1 > 0;
  19886. v2Out = d2 > 0;
  19887. v3Out = d3 > 0;
  19888. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  19889. switch (total) {
  19890. case 0:
  19891. result.push(vertices[index]);
  19892. result.push(vertices[index + 1]);
  19893. result.push(vertices[index + 2]);
  19894. break;
  19895. case 1:
  19896. if (v1Out) {
  19897. nV1 = vertices[index + 1];
  19898. nV2 = vertices[index + 2];
  19899. nV3 = clipVertices(vertices[index], nV1);
  19900. nV4 = clipVertices(vertices[index], nV2);
  19901. }
  19902. if (v2Out) {
  19903. nV1 = vertices[index];
  19904. nV2 = vertices[index + 2];
  19905. nV3 = clipVertices(vertices[index + 1], nV1);
  19906. nV4 = clipVertices(vertices[index + 1], nV2);
  19907. result.push(nV3);
  19908. result.push(nV2.clone());
  19909. result.push(nV1.clone());
  19910. result.push(nV2.clone());
  19911. result.push(nV3.clone());
  19912. result.push(nV4);
  19913. break;
  19914. }
  19915. if (v3Out) {
  19916. nV1 = vertices[index];
  19917. nV2 = vertices[index + 1];
  19918. nV3 = clipVertices(vertices[index + 2], nV1);
  19919. nV4 = clipVertices(vertices[index + 2], nV2);
  19920. }
  19921. result.push(nV1.clone());
  19922. result.push(nV2.clone());
  19923. result.push(nV3);
  19924. result.push(nV4);
  19925. result.push(nV3.clone());
  19926. result.push(nV2.clone());
  19927. break;
  19928. case 2:
  19929. if (!v1Out) {
  19930. nV1 = vertices[index].clone();
  19931. nV2 = clipVertices(nV1, vertices[index + 1]);
  19932. nV3 = clipVertices(nV1, vertices[index + 2]);
  19933. result.push(nV1);
  19934. result.push(nV2);
  19935. result.push(nV3);
  19936. }
  19937. if (!v2Out) {
  19938. nV1 = vertices[index + 1].clone();
  19939. nV2 = clipVertices(nV1, vertices[index + 2]);
  19940. nV3 = clipVertices(nV1, vertices[index]);
  19941. result.push(nV1);
  19942. result.push(nV2);
  19943. result.push(nV3);
  19944. }
  19945. if (!v3Out) {
  19946. nV1 = vertices[index + 2].clone();
  19947. nV2 = clipVertices(nV1, vertices[index]);
  19948. nV3 = clipVertices(nV1, vertices[index + 1]);
  19949. result.push(nV1);
  19950. result.push(nV2);
  19951. result.push(nV3);
  19952. }
  19953. break;
  19954. case 3:
  19955. break;
  19956. }
  19957. }
  19958. return result;
  19959. };
  19960. for (var index = 0; index < indices.length; index += 3) {
  19961. var faceVertices = new Array();
  19962. faceVertices.push(extractDecalVector3(index));
  19963. faceVertices.push(extractDecalVector3(index + 1));
  19964. faceVertices.push(extractDecalVector3(index + 2));
  19965. // Clip
  19966. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  19967. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  19968. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  19969. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  19970. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  19971. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  19972. if (faceVertices.length === 0) {
  19973. continue;
  19974. }
  19975. // Add UVs and get back to world
  19976. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  19977. var vertex = faceVertices[vIndex];
  19978. //TODO check for Int32Array
  19979. vertexData.indices.push(currentVertexDataIndex);
  19980. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  19981. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  19982. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  19983. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  19984. currentVertexDataIndex++;
  19985. }
  19986. }
  19987. // Return mesh
  19988. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  19989. vertexData.applyToMesh(decal);
  19990. decal.position = position.clone();
  19991. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  19992. return decal;
  19993. };
  19994. // Privates
  19995. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  19996. // extrusion geometry
  19997. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  19998. var tangents = path3D.getTangents();
  19999. var normals = path3D.getNormals();
  20000. var binormals = path3D.getBinormals();
  20001. var distances = path3D.getDistances();
  20002. var angle = 0;
  20003. var returnScale = function () { return scale; };
  20004. var returnRotation = function () { return rotation; };
  20005. var rotate = custom ? rotateFunction : returnRotation;
  20006. var scl = custom ? scaleFunction : returnScale;
  20007. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20008. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20009. for (var i = 0; i < curve.length; i++) {
  20010. var shapePath = new Array();
  20011. var angleStep = rotate(i, distances[i]);
  20012. var scaleRatio = scl(i, distances[i]);
  20013. for (var p = 0; p < shape.length; p++) {
  20014. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  20015. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  20016. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  20017. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  20018. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  20019. shapePath[p] = rotated;
  20020. }
  20021. shapePaths[index] = shapePath;
  20022. angle += angleStep;
  20023. index++;
  20024. }
  20025. // cap
  20026. var capPath = function (shapePath) {
  20027. var pointCap = Array();
  20028. var barycenter = BABYLON.Vector3.Zero();
  20029. var i;
  20030. for (i = 0; i < shapePath.length; i++) {
  20031. barycenter.addInPlace(shapePath[i]);
  20032. }
  20033. barycenter.scaleInPlace(1 / shapePath.length);
  20034. for (i = 0; i < shapePath.length; i++) {
  20035. pointCap.push(barycenter);
  20036. }
  20037. return pointCap;
  20038. };
  20039. switch (cap) {
  20040. case BABYLON.Mesh.NO_CAP:
  20041. break;
  20042. case BABYLON.Mesh.CAP_START:
  20043. shapePaths[0] = capPath(shapePaths[2]);
  20044. shapePaths[1] = shapePaths[2].slice(0);
  20045. break;
  20046. case BABYLON.Mesh.CAP_END:
  20047. shapePaths[index] = shapePaths[index - 1];
  20048. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20049. break;
  20050. case BABYLON.Mesh.CAP_ALL:
  20051. shapePaths[0] = capPath(shapePaths[2]);
  20052. shapePaths[1] = shapePaths[2].slice(0);
  20053. shapePaths[index] = shapePaths[index - 1];
  20054. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20055. break;
  20056. default:
  20057. break;
  20058. }
  20059. return shapePaths;
  20060. };
  20061. var path3D;
  20062. var pathArray;
  20063. if (instance) {
  20064. path3D = (instance.path3D).update(curve);
  20065. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  20066. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  20067. return instance;
  20068. }
  20069. // extruded shape creation
  20070. path3D = new BABYLON.Path3D(curve);
  20071. var newShapePaths = new Array();
  20072. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20073. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  20074. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  20075. extrudedGeneric.pathArray = pathArray;
  20076. extrudedGeneric.path3D = path3D;
  20077. extrudedGeneric.cap = cap;
  20078. return extrudedGeneric;
  20079. };
  20080. return MeshBuilder;
  20081. })();
  20082. BABYLON.MeshBuilder = MeshBuilder;
  20083. })(BABYLON || (BABYLON = {}));
  20084. var BABYLON;
  20085. (function (BABYLON) {
  20086. var BaseTexture = (function () {
  20087. function BaseTexture(scene) {
  20088. this.hasAlpha = false;
  20089. this.getAlphaFromRGB = false;
  20090. this.level = 1;
  20091. this.coordinatesIndex = 0;
  20092. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20093. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20094. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20095. this.anisotropicFilteringLevel = 4;
  20096. this.isCube = false;
  20097. this.isRenderTarget = false;
  20098. this.animations = new Array();
  20099. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20100. this._scene = scene;
  20101. this._scene.textures.push(this);
  20102. }
  20103. BaseTexture.prototype.getScene = function () {
  20104. return this._scene;
  20105. };
  20106. BaseTexture.prototype.getTextureMatrix = function () {
  20107. return null;
  20108. };
  20109. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20110. return null;
  20111. };
  20112. BaseTexture.prototype.getInternalTexture = function () {
  20113. return this._texture;
  20114. };
  20115. BaseTexture.prototype.isReady = function () {
  20116. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20117. return true;
  20118. }
  20119. if (this._texture) {
  20120. return this._texture.isReady;
  20121. }
  20122. return false;
  20123. };
  20124. BaseTexture.prototype.getSize = function () {
  20125. if (this._texture._width) {
  20126. return { width: this._texture._width, height: this._texture._height };
  20127. }
  20128. if (this._texture._size) {
  20129. return { width: this._texture._size, height: this._texture._size };
  20130. }
  20131. return { width: 0, height: 0 };
  20132. };
  20133. BaseTexture.prototype.getBaseSize = function () {
  20134. if (!this.isReady() || !this._texture)
  20135. return { width: 0, height: 0 };
  20136. if (this._texture._size) {
  20137. return { width: this._texture._size, height: this._texture._size };
  20138. }
  20139. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20140. };
  20141. BaseTexture.prototype.scale = function (ratio) {
  20142. };
  20143. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20144. get: function () {
  20145. return false;
  20146. },
  20147. enumerable: true,
  20148. configurable: true
  20149. });
  20150. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20151. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20152. for (var index = 0; index < texturesCache.length; index++) {
  20153. var texturesCacheEntry = texturesCache[index];
  20154. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20155. texturesCache.splice(index, 1);
  20156. return;
  20157. }
  20158. }
  20159. };
  20160. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20161. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20162. for (var index = 0; index < texturesCache.length; index++) {
  20163. var texturesCacheEntry = texturesCache[index];
  20164. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20165. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20166. texturesCacheEntry.references++;
  20167. return texturesCacheEntry;
  20168. }
  20169. }
  20170. }
  20171. return null;
  20172. };
  20173. BaseTexture.prototype.delayLoad = function () {
  20174. };
  20175. BaseTexture.prototype.clone = function () {
  20176. return null;
  20177. };
  20178. BaseTexture.prototype.releaseInternalTexture = function () {
  20179. if (this._texture) {
  20180. this._scene.getEngine().releaseInternalTexture(this._texture);
  20181. delete this._texture;
  20182. }
  20183. };
  20184. BaseTexture.prototype.dispose = function () {
  20185. // Animations
  20186. this.getScene().stopAnimation(this);
  20187. // Remove from scene
  20188. var index = this._scene.textures.indexOf(this);
  20189. if (index >= 0) {
  20190. this._scene.textures.splice(index, 1);
  20191. }
  20192. if (this._texture === undefined) {
  20193. return;
  20194. }
  20195. // Release
  20196. this.releaseInternalTexture();
  20197. // Callback
  20198. if (this.onDispose) {
  20199. this.onDispose();
  20200. }
  20201. };
  20202. BaseTexture.prototype.serialize = function () {
  20203. if (!this.name) {
  20204. return null;
  20205. }
  20206. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20207. // Animations
  20208. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20209. return serializationObject;
  20210. };
  20211. __decorate([
  20212. BABYLON.serialize()
  20213. ], BaseTexture.prototype, "name", void 0);
  20214. __decorate([
  20215. BABYLON.serialize()
  20216. ], BaseTexture.prototype, "hasAlpha", void 0);
  20217. __decorate([
  20218. BABYLON.serialize()
  20219. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20220. __decorate([
  20221. BABYLON.serialize()
  20222. ], BaseTexture.prototype, "level", void 0);
  20223. __decorate([
  20224. BABYLON.serialize()
  20225. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20226. __decorate([
  20227. BABYLON.serialize()
  20228. ], BaseTexture.prototype, "coordinatesMode", void 0);
  20229. __decorate([
  20230. BABYLON.serialize()
  20231. ], BaseTexture.prototype, "wrapU", void 0);
  20232. __decorate([
  20233. BABYLON.serialize()
  20234. ], BaseTexture.prototype, "wrapV", void 0);
  20235. __decorate([
  20236. BABYLON.serialize()
  20237. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20238. __decorate([
  20239. BABYLON.serialize()
  20240. ], BaseTexture.prototype, "isCube", void 0);
  20241. __decorate([
  20242. BABYLON.serialize()
  20243. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20244. return BaseTexture;
  20245. })();
  20246. BABYLON.BaseTexture = BaseTexture;
  20247. })(BABYLON || (BABYLON = {}));
  20248. var BABYLON;
  20249. (function (BABYLON) {
  20250. var Texture = (function (_super) {
  20251. __extends(Texture, _super);
  20252. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  20253. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20254. if (onLoad === void 0) { onLoad = null; }
  20255. if (onError === void 0) { onError = null; }
  20256. if (buffer === void 0) { buffer = null; }
  20257. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20258. _super.call(this, scene);
  20259. this.uOffset = 0;
  20260. this.vOffset = 0;
  20261. this.uScale = 1.0;
  20262. this.vScale = 1.0;
  20263. this.uAng = 0;
  20264. this.vAng = 0;
  20265. this.wAng = 0;
  20266. this.name = url;
  20267. this.url = url;
  20268. this._noMipmap = noMipmap;
  20269. this._invertY = invertY;
  20270. this._samplingMode = samplingMode;
  20271. this._buffer = buffer;
  20272. this._deleteBuffer = deleteBuffer;
  20273. if (!url) {
  20274. return;
  20275. }
  20276. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  20277. if (!this._texture) {
  20278. if (!scene.useDelayedTextureLoading) {
  20279. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  20280. if (deleteBuffer) {
  20281. delete this._buffer;
  20282. }
  20283. }
  20284. else {
  20285. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20286. this._delayedOnLoad = onLoad;
  20287. this._delayedOnError = onError;
  20288. }
  20289. }
  20290. else {
  20291. BABYLON.Tools.SetImmediate(function () {
  20292. if (onLoad) {
  20293. onLoad();
  20294. }
  20295. });
  20296. }
  20297. }
  20298. Texture.prototype.delayLoad = function () {
  20299. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20300. return;
  20301. }
  20302. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20303. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20304. if (!this._texture) {
  20305. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  20306. if (this._deleteBuffer) {
  20307. delete this._buffer;
  20308. }
  20309. }
  20310. };
  20311. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20312. if (!this._texture) {
  20313. return;
  20314. }
  20315. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20316. };
  20317. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20318. x *= this.uScale;
  20319. y *= this.vScale;
  20320. x -= 0.5 * this.uScale;
  20321. y -= 0.5 * this.vScale;
  20322. z -= 0.5;
  20323. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20324. t.x += 0.5 * this.uScale + this.uOffset;
  20325. t.y += 0.5 * this.vScale + this.vOffset;
  20326. t.z += 0.5;
  20327. };
  20328. Texture.prototype.getTextureMatrix = function () {
  20329. if (this.uOffset === this._cachedUOffset &&
  20330. this.vOffset === this._cachedVOffset &&
  20331. this.uScale === this._cachedUScale &&
  20332. this.vScale === this._cachedVScale &&
  20333. this.uAng === this._cachedUAng &&
  20334. this.vAng === this._cachedVAng &&
  20335. this.wAng === this._cachedWAng) {
  20336. return this._cachedTextureMatrix;
  20337. }
  20338. this._cachedUOffset = this.uOffset;
  20339. this._cachedVOffset = this.vOffset;
  20340. this._cachedUScale = this.uScale;
  20341. this._cachedVScale = this.vScale;
  20342. this._cachedUAng = this.uAng;
  20343. this._cachedVAng = this.vAng;
  20344. this._cachedWAng = this.wAng;
  20345. if (!this._cachedTextureMatrix) {
  20346. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20347. this._rowGenerationMatrix = new BABYLON.Matrix();
  20348. this._t0 = BABYLON.Vector3.Zero();
  20349. this._t1 = BABYLON.Vector3.Zero();
  20350. this._t2 = BABYLON.Vector3.Zero();
  20351. }
  20352. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20353. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20354. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20355. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20356. this._t1.subtractInPlace(this._t0);
  20357. this._t2.subtractInPlace(this._t0);
  20358. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20359. this._cachedTextureMatrix.m[0] = this._t1.x;
  20360. this._cachedTextureMatrix.m[1] = this._t1.y;
  20361. this._cachedTextureMatrix.m[2] = this._t1.z;
  20362. this._cachedTextureMatrix.m[4] = this._t2.x;
  20363. this._cachedTextureMatrix.m[5] = this._t2.y;
  20364. this._cachedTextureMatrix.m[6] = this._t2.z;
  20365. this._cachedTextureMatrix.m[8] = this._t0.x;
  20366. this._cachedTextureMatrix.m[9] = this._t0.y;
  20367. this._cachedTextureMatrix.m[10] = this._t0.z;
  20368. return this._cachedTextureMatrix;
  20369. };
  20370. Texture.prototype.getReflectionTextureMatrix = function () {
  20371. if (this.uOffset === this._cachedUOffset &&
  20372. this.vOffset === this._cachedVOffset &&
  20373. this.uScale === this._cachedUScale &&
  20374. this.vScale === this._cachedVScale &&
  20375. this.coordinatesMode === this._cachedCoordinatesMode) {
  20376. return this._cachedTextureMatrix;
  20377. }
  20378. if (!this._cachedTextureMatrix) {
  20379. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20380. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20381. }
  20382. this._cachedCoordinatesMode = this.coordinatesMode;
  20383. switch (this.coordinatesMode) {
  20384. case Texture.PLANAR_MODE:
  20385. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20386. this._cachedTextureMatrix[0] = this.uScale;
  20387. this._cachedTextureMatrix[5] = this.vScale;
  20388. this._cachedTextureMatrix[12] = this.uOffset;
  20389. this._cachedTextureMatrix[13] = this.vOffset;
  20390. break;
  20391. case Texture.PROJECTION_MODE:
  20392. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20393. this._projectionModeMatrix.m[0] = 0.5;
  20394. this._projectionModeMatrix.m[5] = -0.5;
  20395. this._projectionModeMatrix.m[10] = 0.0;
  20396. this._projectionModeMatrix.m[12] = 0.5;
  20397. this._projectionModeMatrix.m[13] = 0.5;
  20398. this._projectionModeMatrix.m[14] = 1.0;
  20399. this._projectionModeMatrix.m[15] = 1.0;
  20400. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20401. break;
  20402. default:
  20403. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20404. break;
  20405. }
  20406. return this._cachedTextureMatrix;
  20407. };
  20408. Texture.prototype.clone = function () {
  20409. var _this = this;
  20410. return BABYLON.SerializationHelper.Clone(function () {
  20411. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20412. }, this);
  20413. };
  20414. // Statics
  20415. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  20416. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20417. if (onLoad === void 0) { onLoad = null; }
  20418. if (onError === void 0) { onError = null; }
  20419. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  20420. };
  20421. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20422. if (parsedTexture.isCube) {
  20423. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20424. }
  20425. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20426. return null;
  20427. }
  20428. var texture = BABYLON.SerializationHelper.Parse(function () {
  20429. if (parsedTexture.mirrorPlane) {
  20430. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20431. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20432. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20433. return mirrorTexture;
  20434. }
  20435. else if (parsedTexture.isRenderTarget) {
  20436. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20437. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20438. return renderTargetTexture;
  20439. }
  20440. else {
  20441. var texture;
  20442. if (parsedTexture.base64String) {
  20443. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20444. }
  20445. else {
  20446. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20447. }
  20448. return texture;
  20449. }
  20450. }, parsedTexture, scene);
  20451. // Animations
  20452. if (parsedTexture.animations) {
  20453. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20454. var parsedAnimation = parsedTexture.animations[animationIndex];
  20455. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20456. }
  20457. }
  20458. return texture;
  20459. };
  20460. // Constants
  20461. Texture.NEAREST_SAMPLINGMODE = 1;
  20462. Texture.BILINEAR_SAMPLINGMODE = 2;
  20463. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20464. Texture.EXPLICIT_MODE = 0;
  20465. Texture.SPHERICAL_MODE = 1;
  20466. Texture.PLANAR_MODE = 2;
  20467. Texture.CUBIC_MODE = 3;
  20468. Texture.PROJECTION_MODE = 4;
  20469. Texture.SKYBOX_MODE = 5;
  20470. Texture.INVCUBIC_MODE = 6;
  20471. Texture.EQUIRECTANGULAR_MODE = 7;
  20472. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20473. Texture.CLAMP_ADDRESSMODE = 0;
  20474. Texture.WRAP_ADDRESSMODE = 1;
  20475. Texture.MIRROR_ADDRESSMODE = 2;
  20476. __decorate([
  20477. BABYLON.serialize()
  20478. ], Texture.prototype, "url", void 0);
  20479. __decorate([
  20480. BABYLON.serialize()
  20481. ], Texture.prototype, "uOffset", void 0);
  20482. __decorate([
  20483. BABYLON.serialize()
  20484. ], Texture.prototype, "vOffset", void 0);
  20485. __decorate([
  20486. BABYLON.serialize()
  20487. ], Texture.prototype, "uScale", void 0);
  20488. __decorate([
  20489. BABYLON.serialize()
  20490. ], Texture.prototype, "vScale", void 0);
  20491. __decorate([
  20492. BABYLON.serialize()
  20493. ], Texture.prototype, "uAng", void 0);
  20494. __decorate([
  20495. BABYLON.serialize()
  20496. ], Texture.prototype, "vAng", void 0);
  20497. __decorate([
  20498. BABYLON.serialize()
  20499. ], Texture.prototype, "wAng", void 0);
  20500. return Texture;
  20501. })(BABYLON.BaseTexture);
  20502. BABYLON.Texture = Texture;
  20503. })(BABYLON || (BABYLON = {}));
  20504. var BABYLON;
  20505. (function (BABYLON) {
  20506. var CubeTexture = (function (_super) {
  20507. __extends(CubeTexture, _super);
  20508. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  20509. _super.call(this, scene);
  20510. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  20511. this.name = rootUrl;
  20512. this.url = rootUrl;
  20513. this._noMipmap = noMipmap;
  20514. this.hasAlpha = false;
  20515. if (!rootUrl && !files) {
  20516. return;
  20517. }
  20518. this._texture = this._getFromCache(rootUrl, noMipmap);
  20519. if (!files) {
  20520. if (!extensions) {
  20521. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  20522. }
  20523. files = [];
  20524. for (var index = 0; index < extensions.length; index++) {
  20525. files.push(rootUrl + extensions[index]);
  20526. }
  20527. this._extensions = extensions;
  20528. }
  20529. this._files = files;
  20530. if (!this._texture) {
  20531. if (!scene.useDelayedTextureLoading) {
  20532. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  20533. }
  20534. else {
  20535. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20536. }
  20537. }
  20538. this.isCube = true;
  20539. this._textureMatrix = BABYLON.Matrix.Identity();
  20540. }
  20541. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  20542. return new CubeTexture("", scene, null, noMipmap, files);
  20543. };
  20544. // Methods
  20545. CubeTexture.prototype.delayLoad = function () {
  20546. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20547. return;
  20548. }
  20549. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20550. this._texture = this._getFromCache(this.url, this._noMipmap);
  20551. if (!this._texture) {
  20552. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  20553. }
  20554. };
  20555. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  20556. return this._textureMatrix;
  20557. };
  20558. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  20559. var texture = BABYLON.SerializationHelper.Parse(function () {
  20560. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20561. }, parsedTexture, scene);
  20562. // Animations
  20563. if (parsedTexture.animations) {
  20564. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20565. var parsedAnimation = parsedTexture.animations[animationIndex];
  20566. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20567. }
  20568. }
  20569. return texture;
  20570. };
  20571. CubeTexture.prototype.clone = function () {
  20572. var _this = this;
  20573. return BABYLON.SerializationHelper.Clone(function () {
  20574. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  20575. }, this);
  20576. };
  20577. return CubeTexture;
  20578. })(BABYLON.BaseTexture);
  20579. BABYLON.CubeTexture = CubeTexture;
  20580. })(BABYLON || (BABYLON = {}));
  20581. var BABYLON;
  20582. (function (BABYLON) {
  20583. var RenderTargetTexture = (function (_super) {
  20584. __extends(RenderTargetTexture, _super);
  20585. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  20586. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  20587. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  20588. if (isCube === void 0) { isCube = false; }
  20589. _super.call(this, null, scene, !generateMipMaps);
  20590. this.isCube = isCube;
  20591. this.renderList = new Array();
  20592. this.renderParticles = true;
  20593. this.renderSprites = false;
  20594. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  20595. this._currentRefreshId = -1;
  20596. this._refreshRate = 1;
  20597. this.name = name;
  20598. this.isRenderTarget = true;
  20599. this._size = size;
  20600. this._generateMipMaps = generateMipMaps;
  20601. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  20602. if (isCube) {
  20603. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20604. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  20605. this._textureMatrix = BABYLON.Matrix.Identity();
  20606. }
  20607. else {
  20608. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  20609. }
  20610. // Rendering groups
  20611. this._renderingManager = new BABYLON.RenderingManager(scene);
  20612. }
  20613. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  20614. get: function () {
  20615. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  20616. },
  20617. enumerable: true,
  20618. configurable: true
  20619. });
  20620. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  20621. get: function () {
  20622. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  20623. },
  20624. enumerable: true,
  20625. configurable: true
  20626. });
  20627. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  20628. get: function () {
  20629. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  20630. },
  20631. enumerable: true,
  20632. configurable: true
  20633. });
  20634. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  20635. this._currentRefreshId = -1;
  20636. };
  20637. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  20638. get: function () {
  20639. return this._refreshRate;
  20640. },
  20641. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20642. set: function (value) {
  20643. this._refreshRate = value;
  20644. this.resetRefreshCounter();
  20645. },
  20646. enumerable: true,
  20647. configurable: true
  20648. });
  20649. RenderTargetTexture.prototype._shouldRender = function () {
  20650. if (this._currentRefreshId === -1) {
  20651. this._currentRefreshId = 1;
  20652. return true;
  20653. }
  20654. if (this.refreshRate === this._currentRefreshId) {
  20655. this._currentRefreshId = 1;
  20656. return true;
  20657. }
  20658. this._currentRefreshId++;
  20659. return false;
  20660. };
  20661. RenderTargetTexture.prototype.isReady = function () {
  20662. if (!this.getScene().renderTargetsEnabled) {
  20663. return false;
  20664. }
  20665. return _super.prototype.isReady.call(this);
  20666. };
  20667. RenderTargetTexture.prototype.getRenderSize = function () {
  20668. return this._size;
  20669. };
  20670. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  20671. get: function () {
  20672. return true;
  20673. },
  20674. enumerable: true,
  20675. configurable: true
  20676. });
  20677. RenderTargetTexture.prototype.scale = function (ratio) {
  20678. var newSize = this._size * ratio;
  20679. this.resize(newSize, this._generateMipMaps);
  20680. };
  20681. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  20682. if (this.isCube) {
  20683. return this._textureMatrix;
  20684. }
  20685. return _super.prototype.getReflectionTextureMatrix.call(this);
  20686. };
  20687. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  20688. this.releaseInternalTexture();
  20689. if (this.isCube) {
  20690. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  20691. }
  20692. else {
  20693. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20694. }
  20695. };
  20696. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  20697. var scene = this.getScene();
  20698. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20699. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  20700. }
  20701. if (this._waitingRenderList) {
  20702. this.renderList = [];
  20703. for (var index = 0; index < this._waitingRenderList.length; index++) {
  20704. var id = this._waitingRenderList[index];
  20705. this.renderList.push(scene.getMeshByID(id));
  20706. }
  20707. delete this._waitingRenderList;
  20708. }
  20709. if (this.renderList && this.renderList.length === 0) {
  20710. return;
  20711. }
  20712. // Prepare renderingManager
  20713. this._renderingManager.reset();
  20714. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  20715. var sceneRenderId = scene.getRenderId();
  20716. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  20717. var mesh = currentRenderList[meshIndex];
  20718. if (mesh) {
  20719. if (!mesh.isReady()) {
  20720. // Reset _currentRefreshId
  20721. this.resetRefreshCounter();
  20722. continue;
  20723. }
  20724. mesh._preActivateForIntermediateRendering(sceneRenderId);
  20725. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  20726. mesh._activate(sceneRenderId);
  20727. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  20728. var subMesh = mesh.subMeshes[subIndex];
  20729. scene._activeIndices += subMesh.indexCount;
  20730. this._renderingManager.dispatch(subMesh);
  20731. }
  20732. }
  20733. }
  20734. }
  20735. if (this.isCube) {
  20736. for (var face = 0; face < 6; face++) {
  20737. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  20738. scene.incrementRenderId();
  20739. scene.resetCachedMaterial();
  20740. }
  20741. }
  20742. else {
  20743. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  20744. }
  20745. if (this.onAfterUnbind) {
  20746. this.onAfterUnbind();
  20747. }
  20748. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20749. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  20750. }
  20751. scene.resetCachedMaterial();
  20752. };
  20753. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  20754. var scene = this.getScene();
  20755. var engine = scene.getEngine();
  20756. // Bind
  20757. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  20758. if (this.isCube) {
  20759. engine.bindFramebuffer(this._texture, faceIndex);
  20760. }
  20761. else {
  20762. engine.bindFramebuffer(this._texture);
  20763. }
  20764. }
  20765. if (this.onBeforeRender) {
  20766. this.onBeforeRender(faceIndex);
  20767. }
  20768. // Clear
  20769. if (this.onClear) {
  20770. this.onClear(engine);
  20771. }
  20772. else {
  20773. engine.clear(scene.clearColor, true, true);
  20774. }
  20775. if (!this._doNotChangeAspectRatio) {
  20776. scene.updateTransformMatrix(true);
  20777. }
  20778. // Render
  20779. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  20780. if (useCameraPostProcess) {
  20781. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  20782. }
  20783. if (!this._doNotChangeAspectRatio) {
  20784. scene.updateTransformMatrix(true);
  20785. }
  20786. if (this.onAfterRender) {
  20787. this.onAfterRender(faceIndex);
  20788. }
  20789. // Dump ?
  20790. if (dumpForDebug) {
  20791. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  20792. }
  20793. // Unbind
  20794. if (!this.isCube || faceIndex === 5) {
  20795. if (this.isCube) {
  20796. if (faceIndex === 5) {
  20797. engine.generateMipMapsForCubemap(this._texture);
  20798. }
  20799. }
  20800. engine.unBindFramebuffer(this._texture, this.isCube);
  20801. }
  20802. };
  20803. RenderTargetTexture.prototype.clone = function () {
  20804. var textureSize = this.getSize();
  20805. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  20806. // Base texture
  20807. newTexture.hasAlpha = this.hasAlpha;
  20808. newTexture.level = this.level;
  20809. // RenderTarget Texture
  20810. newTexture.coordinatesMode = this.coordinatesMode;
  20811. newTexture.renderList = this.renderList.slice(0);
  20812. return newTexture;
  20813. };
  20814. RenderTargetTexture.prototype.serialize = function () {
  20815. if (!this.name) {
  20816. return null;
  20817. }
  20818. var serializationObject = _super.prototype.serialize.call(this);
  20819. serializationObject.renderTargetSize = this.getRenderSize();
  20820. serializationObject.renderList = [];
  20821. for (var index = 0; index < this.renderList.length; index++) {
  20822. serializationObject.renderList.push(this.renderList[index].id);
  20823. }
  20824. return serializationObject;
  20825. };
  20826. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  20827. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  20828. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  20829. return RenderTargetTexture;
  20830. })(BABYLON.Texture);
  20831. BABYLON.RenderTargetTexture = RenderTargetTexture;
  20832. })(BABYLON || (BABYLON = {}));
  20833. var BABYLON;
  20834. (function (BABYLON) {
  20835. var ProceduralTexture = (function (_super) {
  20836. __extends(ProceduralTexture, _super);
  20837. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  20838. if (generateMipMaps === void 0) { generateMipMaps = true; }
  20839. if (isCube === void 0) { isCube = false; }
  20840. _super.call(this, null, scene, !generateMipMaps);
  20841. this.isCube = isCube;
  20842. this.isEnabled = true;
  20843. this._currentRefreshId = -1;
  20844. this._refreshRate = 1;
  20845. this._vertexDeclaration = [2];
  20846. this._vertexStrideSize = 2 * 4;
  20847. this._uniforms = new Array();
  20848. this._samplers = new Array();
  20849. this._textures = new Array();
  20850. this._floats = new Array();
  20851. this._floatsArrays = {};
  20852. this._colors3 = new Array();
  20853. this._colors4 = new Array();
  20854. this._vectors2 = new Array();
  20855. this._vectors3 = new Array();
  20856. this._matrices = new Array();
  20857. this._fallbackTextureUsed = false;
  20858. scene._proceduralTextures.push(this);
  20859. this.name = name;
  20860. this.isRenderTarget = true;
  20861. this._size = size;
  20862. this._generateMipMaps = generateMipMaps;
  20863. this.setFragment(fragment);
  20864. this._fallbackTexture = fallbackTexture;
  20865. if (isCube) {
  20866. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20867. this.setFloat("face", 0);
  20868. }
  20869. else {
  20870. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  20871. }
  20872. // VBO
  20873. var vertices = [];
  20874. vertices.push(1, 1);
  20875. vertices.push(-1, 1);
  20876. vertices.push(-1, -1);
  20877. vertices.push(1, -1);
  20878. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20879. // Indices
  20880. var indices = [];
  20881. indices.push(0);
  20882. indices.push(1);
  20883. indices.push(2);
  20884. indices.push(0);
  20885. indices.push(2);
  20886. indices.push(3);
  20887. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20888. }
  20889. ProceduralTexture.prototype.reset = function () {
  20890. if (this._effect === undefined) {
  20891. return;
  20892. }
  20893. var engine = this.getScene().getEngine();
  20894. engine._releaseEffect(this._effect);
  20895. };
  20896. ProceduralTexture.prototype.isReady = function () {
  20897. var _this = this;
  20898. var engine = this.getScene().getEngine();
  20899. var shaders;
  20900. if (!this._fragment) {
  20901. return false;
  20902. }
  20903. if (this._fallbackTextureUsed) {
  20904. return true;
  20905. }
  20906. if (this._fragment.fragmentElement !== undefined) {
  20907. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  20908. }
  20909. else {
  20910. shaders = { vertex: "procedural", fragment: this._fragment };
  20911. }
  20912. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  20913. _this.releaseInternalTexture();
  20914. if (_this._fallbackTexture) {
  20915. _this._texture = _this._fallbackTexture._texture;
  20916. _this._texture.references++;
  20917. }
  20918. _this._fallbackTextureUsed = true;
  20919. });
  20920. return this._effect.isReady();
  20921. };
  20922. ProceduralTexture.prototype.resetRefreshCounter = function () {
  20923. this._currentRefreshId = -1;
  20924. };
  20925. ProceduralTexture.prototype.setFragment = function (fragment) {
  20926. this._fragment = fragment;
  20927. };
  20928. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  20929. get: function () {
  20930. return this._refreshRate;
  20931. },
  20932. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20933. set: function (value) {
  20934. this._refreshRate = value;
  20935. this.resetRefreshCounter();
  20936. },
  20937. enumerable: true,
  20938. configurable: true
  20939. });
  20940. ProceduralTexture.prototype._shouldRender = function () {
  20941. if (!this.isEnabled || !this.isReady() || !this._texture) {
  20942. return false;
  20943. }
  20944. if (this._fallbackTextureUsed) {
  20945. return false;
  20946. }
  20947. if (this._currentRefreshId === -1) {
  20948. this._currentRefreshId = 1;
  20949. return true;
  20950. }
  20951. if (this.refreshRate === this._currentRefreshId) {
  20952. this._currentRefreshId = 1;
  20953. return true;
  20954. }
  20955. this._currentRefreshId++;
  20956. return false;
  20957. };
  20958. ProceduralTexture.prototype.getRenderSize = function () {
  20959. return this._size;
  20960. };
  20961. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  20962. if (this._fallbackTextureUsed) {
  20963. return;
  20964. }
  20965. this.releaseInternalTexture();
  20966. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20967. };
  20968. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  20969. if (this._uniforms.indexOf(uniformName) === -1) {
  20970. this._uniforms.push(uniformName);
  20971. }
  20972. };
  20973. ProceduralTexture.prototype.setTexture = function (name, texture) {
  20974. if (this._samplers.indexOf(name) === -1) {
  20975. this._samplers.push(name);
  20976. }
  20977. this._textures[name] = texture;
  20978. return this;
  20979. };
  20980. ProceduralTexture.prototype.setFloat = function (name, value) {
  20981. this._checkUniform(name);
  20982. this._floats[name] = value;
  20983. return this;
  20984. };
  20985. ProceduralTexture.prototype.setFloats = function (name, value) {
  20986. this._checkUniform(name);
  20987. this._floatsArrays[name] = value;
  20988. return this;
  20989. };
  20990. ProceduralTexture.prototype.setColor3 = function (name, value) {
  20991. this._checkUniform(name);
  20992. this._colors3[name] = value;
  20993. return this;
  20994. };
  20995. ProceduralTexture.prototype.setColor4 = function (name, value) {
  20996. this._checkUniform(name);
  20997. this._colors4[name] = value;
  20998. return this;
  20999. };
  21000. ProceduralTexture.prototype.setVector2 = function (name, value) {
  21001. this._checkUniform(name);
  21002. this._vectors2[name] = value;
  21003. return this;
  21004. };
  21005. ProceduralTexture.prototype.setVector3 = function (name, value) {
  21006. this._checkUniform(name);
  21007. this._vectors3[name] = value;
  21008. return this;
  21009. };
  21010. ProceduralTexture.prototype.setMatrix = function (name, value) {
  21011. this._checkUniform(name);
  21012. this._matrices[name] = value;
  21013. return this;
  21014. };
  21015. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21016. var scene = this.getScene();
  21017. var engine = scene.getEngine();
  21018. // Render
  21019. engine.enableEffect(this._effect);
  21020. engine.setState(false);
  21021. // Texture
  21022. for (var name in this._textures) {
  21023. this._effect.setTexture(name, this._textures[name]);
  21024. }
  21025. // Float
  21026. for (name in this._floats) {
  21027. this._effect.setFloat(name, this._floats[name]);
  21028. }
  21029. // Floats
  21030. for (name in this._floatsArrays) {
  21031. this._effect.setArray(name, this._floatsArrays[name]);
  21032. }
  21033. // Color3
  21034. for (name in this._colors3) {
  21035. this._effect.setColor3(name, this._colors3[name]);
  21036. }
  21037. // Color4
  21038. for (name in this._colors4) {
  21039. var color = this._colors4[name];
  21040. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21041. }
  21042. // Vector2
  21043. for (name in this._vectors2) {
  21044. this._effect.setVector2(name, this._vectors2[name]);
  21045. }
  21046. // Vector3
  21047. for (name in this._vectors3) {
  21048. this._effect.setVector3(name, this._vectors3[name]);
  21049. }
  21050. // Matrix
  21051. for (name in this._matrices) {
  21052. this._effect.setMatrix(name, this._matrices[name]);
  21053. }
  21054. // VBOs
  21055. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21056. if (this.isCube) {
  21057. for (var face = 0; face < 6; face++) {
  21058. engine.bindFramebuffer(this._texture, face);
  21059. this._effect.setFloat("face", face);
  21060. // Clear
  21061. engine.clear(scene.clearColor, true, true);
  21062. // Draw order
  21063. engine.draw(true, 0, 6);
  21064. // Mipmaps
  21065. if (face === 5) {
  21066. engine.generateMipMapsForCubemap(this._texture);
  21067. }
  21068. }
  21069. }
  21070. else {
  21071. engine.bindFramebuffer(this._texture);
  21072. // Clear
  21073. engine.clear(scene.clearColor, true, true);
  21074. // Draw order
  21075. engine.draw(true, 0, 6);
  21076. }
  21077. // Unbind
  21078. engine.unBindFramebuffer(this._texture, this.isCube);
  21079. if (this.onGenerated) {
  21080. this.onGenerated();
  21081. }
  21082. };
  21083. ProceduralTexture.prototype.clone = function () {
  21084. var textureSize = this.getSize();
  21085. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  21086. // Base texture
  21087. newTexture.hasAlpha = this.hasAlpha;
  21088. newTexture.level = this.level;
  21089. // RenderTarget Texture
  21090. newTexture.coordinatesMode = this.coordinatesMode;
  21091. return newTexture;
  21092. };
  21093. ProceduralTexture.prototype.dispose = function () {
  21094. var index = this.getScene()._proceduralTextures.indexOf(this);
  21095. if (index >= 0) {
  21096. this.getScene()._proceduralTextures.splice(index, 1);
  21097. }
  21098. _super.prototype.dispose.call(this);
  21099. };
  21100. return ProceduralTexture;
  21101. })(BABYLON.Texture);
  21102. BABYLON.ProceduralTexture = ProceduralTexture;
  21103. })(BABYLON || (BABYLON = {}));
  21104. var BABYLON;
  21105. (function (BABYLON) {
  21106. var MirrorTexture = (function (_super) {
  21107. __extends(MirrorTexture, _super);
  21108. function MirrorTexture(name, size, scene, generateMipMaps) {
  21109. var _this = this;
  21110. _super.call(this, name, size, scene, generateMipMaps, true);
  21111. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  21112. this._transformMatrix = BABYLON.Matrix.Zero();
  21113. this._mirrorMatrix = BABYLON.Matrix.Zero();
  21114. this.onBeforeRender = function () {
  21115. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  21116. _this._savedViewMatrix = scene.getViewMatrix();
  21117. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  21118. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  21119. scene.clipPlane = _this.mirrorPlane;
  21120. scene.getEngine().cullBackFaces = false;
  21121. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  21122. };
  21123. this.onAfterRender = function () {
  21124. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  21125. scene.getEngine().cullBackFaces = true;
  21126. scene._mirroredCameraPosition = null;
  21127. delete scene.clipPlane;
  21128. };
  21129. }
  21130. MirrorTexture.prototype.clone = function () {
  21131. var textureSize = this.getSize();
  21132. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21133. // Base texture
  21134. newTexture.hasAlpha = this.hasAlpha;
  21135. newTexture.level = this.level;
  21136. // Mirror Texture
  21137. newTexture.mirrorPlane = this.mirrorPlane.clone();
  21138. newTexture.renderList = this.renderList.slice(0);
  21139. return newTexture;
  21140. };
  21141. MirrorTexture.prototype.serialize = function () {
  21142. if (!this.name) {
  21143. return null;
  21144. }
  21145. var serializationObject = _super.prototype.serialize.call(this);
  21146. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  21147. return serializationObject;
  21148. };
  21149. return MirrorTexture;
  21150. })(BABYLON.RenderTargetTexture);
  21151. BABYLON.MirrorTexture = MirrorTexture;
  21152. })(BABYLON || (BABYLON = {}));
  21153. var BABYLON;
  21154. (function (BABYLON) {
  21155. /**
  21156. * Creates a refraction texture used by refraction channel of the standard material.
  21157. * @param name the texture name
  21158. * @param size size of the underlying texture
  21159. * @param scene root scene
  21160. */
  21161. var RefractionTexture = (function (_super) {
  21162. __extends(RefractionTexture, _super);
  21163. function RefractionTexture(name, size, scene, generateMipMaps) {
  21164. var _this = this;
  21165. _super.call(this, name, size, scene, generateMipMaps, true);
  21166. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  21167. this.depth = 2.0;
  21168. this.onBeforeRender = function () {
  21169. scene.clipPlane = _this.refractionPlane;
  21170. };
  21171. this.onAfterRender = function () {
  21172. delete scene.clipPlane;
  21173. };
  21174. }
  21175. RefractionTexture.prototype.clone = function () {
  21176. var textureSize = this.getSize();
  21177. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21178. // Base texture
  21179. newTexture.hasAlpha = this.hasAlpha;
  21180. newTexture.level = this.level;
  21181. // Refraction Texture
  21182. newTexture.refractionPlane = this.refractionPlane.clone();
  21183. newTexture.renderList = this.renderList.slice(0);
  21184. newTexture.depth = this.depth;
  21185. return newTexture;
  21186. };
  21187. RefractionTexture.prototype.serialize = function () {
  21188. if (!this.name) {
  21189. return null;
  21190. }
  21191. var serializationObject = _super.prototype.serialize.call(this);
  21192. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  21193. serializationObject.depth = this.depth;
  21194. return serializationObject;
  21195. };
  21196. return RefractionTexture;
  21197. })(BABYLON.RenderTargetTexture);
  21198. BABYLON.RefractionTexture = RefractionTexture;
  21199. })(BABYLON || (BABYLON = {}));
  21200. var BABYLON;
  21201. (function (BABYLON) {
  21202. var DynamicTexture = (function (_super) {
  21203. __extends(DynamicTexture, _super);
  21204. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  21205. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21206. _super.call(this, null, scene, !generateMipMaps);
  21207. this.name = name;
  21208. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21209. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21210. this._generateMipMaps = generateMipMaps;
  21211. if (options.getContext) {
  21212. this._canvas = options;
  21213. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21214. }
  21215. else {
  21216. this._canvas = document.createElement("canvas");
  21217. if (options.width) {
  21218. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21219. }
  21220. else {
  21221. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21222. }
  21223. }
  21224. var textureSize = this.getSize();
  21225. this._canvas.width = textureSize.width;
  21226. this._canvas.height = textureSize.height;
  21227. this._context = this._canvas.getContext("2d");
  21228. }
  21229. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  21230. get: function () {
  21231. return true;
  21232. },
  21233. enumerable: true,
  21234. configurable: true
  21235. });
  21236. DynamicTexture.prototype.scale = function (ratio) {
  21237. var textureSize = this.getSize();
  21238. textureSize.width *= ratio;
  21239. textureSize.height *= ratio;
  21240. this._canvas.width = textureSize.width;
  21241. this._canvas.height = textureSize.height;
  21242. this.releaseInternalTexture();
  21243. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  21244. };
  21245. DynamicTexture.prototype.getContext = function () {
  21246. return this._context;
  21247. };
  21248. DynamicTexture.prototype.clear = function () {
  21249. var size = this.getSize();
  21250. this._context.fillRect(0, 0, size.width, size.height);
  21251. };
  21252. DynamicTexture.prototype.update = function (invertY) {
  21253. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  21254. };
  21255. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  21256. if (update === void 0) { update = true; }
  21257. var size = this.getSize();
  21258. if (clearColor) {
  21259. this._context.fillStyle = clearColor;
  21260. this._context.fillRect(0, 0, size.width, size.height);
  21261. }
  21262. this._context.font = font;
  21263. if (x === null) {
  21264. var textSize = this._context.measureText(text);
  21265. x = (size.width - textSize.width) / 2;
  21266. }
  21267. this._context.fillStyle = color;
  21268. this._context.fillText(text, x, y);
  21269. if (update) {
  21270. this.update(invertY);
  21271. }
  21272. };
  21273. DynamicTexture.prototype.clone = function () {
  21274. var textureSize = this.getSize();
  21275. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21276. // Base texture
  21277. newTexture.hasAlpha = this.hasAlpha;
  21278. newTexture.level = this.level;
  21279. // Dynamic Texture
  21280. newTexture.wrapU = this.wrapU;
  21281. newTexture.wrapV = this.wrapV;
  21282. return newTexture;
  21283. };
  21284. return DynamicTexture;
  21285. })(BABYLON.Texture);
  21286. BABYLON.DynamicTexture = DynamicTexture;
  21287. })(BABYLON || (BABYLON = {}));
  21288. var BABYLON;
  21289. (function (BABYLON) {
  21290. var VideoTexture = (function (_super) {
  21291. __extends(VideoTexture, _super);
  21292. /**
  21293. * Creates a video texture.
  21294. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  21295. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  21296. * @param {BABYLON.Scene} scene is obviously the current scene.
  21297. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  21298. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  21299. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  21300. */
  21301. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  21302. var _this = this;
  21303. if (generateMipMaps === void 0) { generateMipMaps = false; }
  21304. if (invertY === void 0) { invertY = false; }
  21305. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21306. _super.call(this, null, scene, !generateMipMaps, invertY);
  21307. this._autoLaunch = true;
  21308. var urls;
  21309. this.name = name;
  21310. if (urlsOrVideo instanceof HTMLVideoElement) {
  21311. this.video = urlsOrVideo;
  21312. }
  21313. else {
  21314. urls = urlsOrVideo;
  21315. this.video = document.createElement("video");
  21316. this.video.autoplay = false;
  21317. this.video.loop = true;
  21318. }
  21319. this._generateMipMaps = generateMipMaps;
  21320. this._samplingMode = samplingMode;
  21321. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  21322. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21323. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21324. }
  21325. else {
  21326. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21327. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21328. this._generateMipMaps = false;
  21329. }
  21330. if (urls) {
  21331. this.video.addEventListener("canplaythrough", function () {
  21332. _this._createTexture();
  21333. });
  21334. urls.forEach(function (url) {
  21335. var source = document.createElement("source");
  21336. source.src = url;
  21337. _this.video.appendChild(source);
  21338. });
  21339. }
  21340. else {
  21341. this._createTexture();
  21342. }
  21343. this._lastUpdate = BABYLON.Tools.Now;
  21344. }
  21345. VideoTexture.prototype._createTexture = function () {
  21346. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  21347. this._texture.isReady = true;
  21348. };
  21349. VideoTexture.prototype.update = function () {
  21350. if (this._autoLaunch) {
  21351. this._autoLaunch = false;
  21352. this.video.play();
  21353. }
  21354. var now = BABYLON.Tools.Now;
  21355. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  21356. return false;
  21357. }
  21358. this._lastUpdate = now;
  21359. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  21360. return true;
  21361. };
  21362. return VideoTexture;
  21363. })(BABYLON.Texture);
  21364. BABYLON.VideoTexture = VideoTexture;
  21365. })(BABYLON || (BABYLON = {}));
  21366. var BABYLON;
  21367. (function (BABYLON) {
  21368. var CustomProceduralTexture = (function (_super) {
  21369. __extends(CustomProceduralTexture, _super);
  21370. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  21371. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  21372. this._animate = true;
  21373. this._time = 0;
  21374. this._texturePath = texturePath;
  21375. //Try to load json
  21376. this.loadJson(texturePath);
  21377. this.refreshRate = 1;
  21378. }
  21379. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  21380. var _this = this;
  21381. var that = this;
  21382. function noConfigFile() {
  21383. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  21384. try {
  21385. that.setFragment(that._texturePath);
  21386. }
  21387. catch (ex) {
  21388. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  21389. }
  21390. }
  21391. var configFileUrl = jsonUrl + "/config.json";
  21392. var xhr = new XMLHttpRequest();
  21393. xhr.open("GET", configFileUrl, true);
  21394. xhr.addEventListener("load", function () {
  21395. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  21396. try {
  21397. _this._config = JSON.parse(xhr.response);
  21398. _this.updateShaderUniforms();
  21399. _this.updateTextures();
  21400. _this.setFragment(_this._texturePath + "/custom");
  21401. _this._animate = _this._config.animate;
  21402. _this.refreshRate = _this._config.refreshrate;
  21403. }
  21404. catch (ex) {
  21405. noConfigFile();
  21406. }
  21407. }
  21408. else {
  21409. noConfigFile();
  21410. }
  21411. }, false);
  21412. xhr.addEventListener("error", function () {
  21413. noConfigFile();
  21414. }, false);
  21415. try {
  21416. xhr.send();
  21417. }
  21418. catch (ex) {
  21419. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  21420. }
  21421. };
  21422. CustomProceduralTexture.prototype.isReady = function () {
  21423. if (!_super.prototype.isReady.call(this)) {
  21424. return false;
  21425. }
  21426. for (var name in this._textures) {
  21427. var texture = this._textures[name];
  21428. if (!texture.isReady()) {
  21429. return false;
  21430. }
  21431. }
  21432. return true;
  21433. };
  21434. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21435. if (this._animate) {
  21436. this._time += this.getScene().getAnimationRatio() * 0.03;
  21437. this.updateShaderUniforms();
  21438. }
  21439. _super.prototype.render.call(this, useCameraPostProcess);
  21440. };
  21441. CustomProceduralTexture.prototype.updateTextures = function () {
  21442. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  21443. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  21444. }
  21445. };
  21446. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  21447. if (this._config) {
  21448. for (var j = 0; j < this._config.uniforms.length; j++) {
  21449. var uniform = this._config.uniforms[j];
  21450. switch (uniform.type) {
  21451. case "float":
  21452. this.setFloat(uniform.name, uniform.value);
  21453. break;
  21454. case "color3":
  21455. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  21456. break;
  21457. case "color4":
  21458. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  21459. break;
  21460. case "vector2":
  21461. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  21462. break;
  21463. case "vector3":
  21464. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  21465. break;
  21466. }
  21467. }
  21468. }
  21469. this.setFloat("time", this._time);
  21470. };
  21471. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  21472. get: function () {
  21473. return this._animate;
  21474. },
  21475. set: function (value) {
  21476. this._animate = value;
  21477. },
  21478. enumerable: true,
  21479. configurable: true
  21480. });
  21481. return CustomProceduralTexture;
  21482. })(BABYLON.ProceduralTexture);
  21483. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  21484. })(BABYLON || (BABYLON = {}));
  21485. var BABYLON;
  21486. (function (BABYLON) {
  21487. var EffectFallbacks = (function () {
  21488. function EffectFallbacks() {
  21489. this._defines = {};
  21490. this._currentRank = 32;
  21491. this._maxRank = -1;
  21492. }
  21493. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21494. if (!this._defines[rank]) {
  21495. if (rank < this._currentRank) {
  21496. this._currentRank = rank;
  21497. }
  21498. if (rank > this._maxRank) {
  21499. this._maxRank = rank;
  21500. }
  21501. this._defines[rank] = new Array();
  21502. }
  21503. this._defines[rank].push(define);
  21504. };
  21505. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21506. this._meshRank = rank;
  21507. this._mesh = mesh;
  21508. if (rank > this._maxRank) {
  21509. this._maxRank = rank;
  21510. }
  21511. };
  21512. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21513. get: function () {
  21514. return this._currentRank <= this._maxRank;
  21515. },
  21516. enumerable: true,
  21517. configurable: true
  21518. });
  21519. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21520. var currentFallbacks = this._defines[this._currentRank];
  21521. for (var index = 0; index < currentFallbacks.length; index++) {
  21522. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21523. }
  21524. if (this._mesh && this._currentRank === this._meshRank) {
  21525. this._mesh.computeBonesUsingShaders = false;
  21526. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21527. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21528. }
  21529. this._currentRank++;
  21530. return currentDefines;
  21531. };
  21532. return EffectFallbacks;
  21533. })();
  21534. BABYLON.EffectFallbacks = EffectFallbacks;
  21535. var Effect = (function () {
  21536. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  21537. var _this = this;
  21538. this._isReady = false;
  21539. this._compilationError = "";
  21540. this._valueCache = [];
  21541. this._engine = engine;
  21542. this.name = baseName;
  21543. this.defines = defines;
  21544. this._uniformsNames = uniformsNames.concat(samplers);
  21545. this._samplers = samplers;
  21546. this._attributesNames = attributesNames;
  21547. this.onError = onError;
  21548. this.onCompiled = onCompiled;
  21549. var vertexSource;
  21550. var fragmentSource;
  21551. if (baseName.vertexElement) {
  21552. vertexSource = document.getElementById(baseName.vertexElement);
  21553. if (!vertexSource) {
  21554. vertexSource = baseName.vertexElement;
  21555. }
  21556. }
  21557. else {
  21558. vertexSource = baseName.vertex || baseName;
  21559. }
  21560. if (baseName.fragmentElement) {
  21561. fragmentSource = document.getElementById(baseName.fragmentElement);
  21562. if (!fragmentSource) {
  21563. fragmentSource = baseName.fragmentElement;
  21564. }
  21565. }
  21566. else {
  21567. fragmentSource = baseName.fragment || baseName;
  21568. }
  21569. this._loadVertexShader(vertexSource, function (vertexCode) {
  21570. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21571. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21572. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21573. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  21574. });
  21575. });
  21576. });
  21577. });
  21578. }
  21579. // Properties
  21580. Effect.prototype.isReady = function () {
  21581. return this._isReady;
  21582. };
  21583. Effect.prototype.getProgram = function () {
  21584. return this._program;
  21585. };
  21586. Effect.prototype.getAttributesNames = function () {
  21587. return this._attributesNames;
  21588. };
  21589. Effect.prototype.getAttributeLocation = function (index) {
  21590. return this._attributes[index];
  21591. };
  21592. Effect.prototype.getAttributeLocationByName = function (name) {
  21593. var index = this._attributesNames.indexOf(name);
  21594. return this._attributes[index];
  21595. };
  21596. Effect.prototype.getAttributesCount = function () {
  21597. return this._attributes.length;
  21598. };
  21599. Effect.prototype.getUniformIndex = function (uniformName) {
  21600. return this._uniformsNames.indexOf(uniformName);
  21601. };
  21602. Effect.prototype.getUniform = function (uniformName) {
  21603. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21604. };
  21605. Effect.prototype.getSamplers = function () {
  21606. return this._samplers;
  21607. };
  21608. Effect.prototype.getCompilationError = function () {
  21609. return this._compilationError;
  21610. };
  21611. // Methods
  21612. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21613. // DOM element ?
  21614. if (vertex instanceof HTMLElement) {
  21615. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21616. callback(vertexCode);
  21617. return;
  21618. }
  21619. // Is in local store ?
  21620. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21621. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21622. return;
  21623. }
  21624. var vertexShaderUrl;
  21625. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21626. vertexShaderUrl = vertex;
  21627. }
  21628. else {
  21629. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21630. }
  21631. // Vertex shader
  21632. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21633. };
  21634. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21635. // DOM element ?
  21636. if (fragment instanceof HTMLElement) {
  21637. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21638. callback(fragmentCode);
  21639. return;
  21640. }
  21641. // Is in local store ?
  21642. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21643. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21644. return;
  21645. }
  21646. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21647. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21648. return;
  21649. }
  21650. var fragmentShaderUrl;
  21651. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21652. fragmentShaderUrl = fragment;
  21653. }
  21654. else {
  21655. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21656. }
  21657. // Fragment shader
  21658. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21659. };
  21660. Effect.prototype._dumpShadersName = function () {
  21661. if (this.name.vertexElement) {
  21662. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  21663. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  21664. }
  21665. else if (this.name.vertex) {
  21666. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  21667. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  21668. }
  21669. else {
  21670. BABYLON.Tools.Error("Vertex shader:" + this.name);
  21671. BABYLON.Tools.Error("Fragment shader:" + this.name);
  21672. }
  21673. };
  21674. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21675. var _this = this;
  21676. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21677. var match = regex.exec(sourceCode);
  21678. var returnValue = new String(sourceCode);
  21679. while (match != null) {
  21680. var includeFile = match[1];
  21681. if (Effect.IncludesShadersStore[includeFile]) {
  21682. // Substitution
  21683. var includeContent = Effect.IncludesShadersStore[includeFile];
  21684. if (match[2]) {
  21685. var splits = match[3].split(",");
  21686. for (var index = 0; index < splits.length; index += 2) {
  21687. var source = new RegExp(splits[index], "g");
  21688. var dest = splits[index + 1];
  21689. includeContent = includeContent.replace(source, dest);
  21690. }
  21691. }
  21692. if (match[4]) {
  21693. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  21694. }
  21695. // Replace
  21696. returnValue = returnValue.replace(match[0], includeContent);
  21697. }
  21698. else {
  21699. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21700. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21701. Effect.IncludesShadersStore[includeFile] = fileContent;
  21702. _this._processIncludes(returnValue, callback);
  21703. });
  21704. return;
  21705. }
  21706. match = regex.exec(sourceCode);
  21707. }
  21708. callback(returnValue);
  21709. };
  21710. Effect.prototype._processPrecision = function (source) {
  21711. if (source.indexOf("precision highp float") === -1) {
  21712. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21713. source = "precision mediump float;\n" + source;
  21714. }
  21715. else {
  21716. source = "precision highp float;\n" + source;
  21717. }
  21718. }
  21719. else {
  21720. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21721. source = source.replace("precision highp float", "precision mediump float");
  21722. }
  21723. }
  21724. return source;
  21725. };
  21726. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21727. try {
  21728. var engine = this._engine;
  21729. // Precision
  21730. vertexSourceCode = this._processPrecision(vertexSourceCode);
  21731. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  21732. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21733. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21734. this._attributes = engine.getAttributes(this._program, attributesNames);
  21735. for (var index = 0; index < this._samplers.length; index++) {
  21736. var sampler = this.getUniform(this._samplers[index]);
  21737. if (sampler == null) {
  21738. this._samplers.splice(index, 1);
  21739. index--;
  21740. }
  21741. }
  21742. engine.bindSamplers(this);
  21743. this._isReady = true;
  21744. if (this.onCompiled) {
  21745. this.onCompiled(this);
  21746. }
  21747. }
  21748. catch (e) {
  21749. // Is it a problem with precision?
  21750. if (e.message.indexOf("highp") !== -1) {
  21751. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  21752. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  21753. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21754. return;
  21755. }
  21756. // Let's go through fallbacks then
  21757. if (fallbacks && fallbacks.isMoreFallbacks) {
  21758. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  21759. this._dumpShadersName();
  21760. defines = fallbacks.reduce(defines);
  21761. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21762. }
  21763. else {
  21764. BABYLON.Tools.Error("Unable to compile effect: ");
  21765. this._dumpShadersName();
  21766. BABYLON.Tools.Error("Defines: " + defines);
  21767. BABYLON.Tools.Error("Error: " + e.message);
  21768. this._compilationError = e.message;
  21769. if (this.onError) {
  21770. this.onError(this, this._compilationError);
  21771. }
  21772. }
  21773. }
  21774. };
  21775. Object.defineProperty(Effect.prototype, "isSupported", {
  21776. get: function () {
  21777. return this._compilationError === "";
  21778. },
  21779. enumerable: true,
  21780. configurable: true
  21781. });
  21782. Effect.prototype._bindTexture = function (channel, texture) {
  21783. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21784. };
  21785. Effect.prototype.setTexture = function (channel, texture) {
  21786. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  21787. };
  21788. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21789. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21790. };
  21791. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21792. if (!this._valueCache[uniformName]) {
  21793. this._valueCache[uniformName] = new BABYLON.Matrix();
  21794. }
  21795. for (var index = 0; index < 16; index++) {
  21796. this._valueCache[uniformName].m[index] = matrix.m[index];
  21797. }
  21798. };
  21799. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21800. if (!this._valueCache[uniformName]) {
  21801. this._valueCache[uniformName] = [x, y];
  21802. return;
  21803. }
  21804. this._valueCache[uniformName][0] = x;
  21805. this._valueCache[uniformName][1] = y;
  21806. };
  21807. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21808. if (!this._valueCache[uniformName]) {
  21809. this._valueCache[uniformName] = [x, y, z];
  21810. return;
  21811. }
  21812. this._valueCache[uniformName][0] = x;
  21813. this._valueCache[uniformName][1] = y;
  21814. this._valueCache[uniformName][2] = z;
  21815. };
  21816. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21817. if (!this._valueCache[uniformName]) {
  21818. this._valueCache[uniformName] = [x, y, z, w];
  21819. return;
  21820. }
  21821. this._valueCache[uniformName][0] = x;
  21822. this._valueCache[uniformName][1] = y;
  21823. this._valueCache[uniformName][2] = z;
  21824. this._valueCache[uniformName][3] = w;
  21825. };
  21826. Effect.prototype.setArray = function (uniformName, array) {
  21827. this._engine.setArray(this.getUniform(uniformName), array);
  21828. return this;
  21829. };
  21830. Effect.prototype.setArray2 = function (uniformName, array) {
  21831. this._engine.setArray2(this.getUniform(uniformName), array);
  21832. return this;
  21833. };
  21834. Effect.prototype.setArray3 = function (uniformName, array) {
  21835. this._engine.setArray3(this.getUniform(uniformName), array);
  21836. return this;
  21837. };
  21838. Effect.prototype.setArray4 = function (uniformName, array) {
  21839. this._engine.setArray4(this.getUniform(uniformName), array);
  21840. return this;
  21841. };
  21842. Effect.prototype.setMatrices = function (uniformName, matrices) {
  21843. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  21844. return this;
  21845. };
  21846. Effect.prototype.setMatrix = function (uniformName, matrix) {
  21847. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  21848. // return this;
  21849. // this._cacheMatrix(uniformName, matrix);
  21850. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  21851. return this;
  21852. };
  21853. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  21854. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  21855. return this;
  21856. };
  21857. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  21858. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  21859. return this;
  21860. };
  21861. Effect.prototype.setFloat = function (uniformName, value) {
  21862. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  21863. return this;
  21864. this._valueCache[uniformName] = value;
  21865. this._engine.setFloat(this.getUniform(uniformName), value);
  21866. return this;
  21867. };
  21868. Effect.prototype.setBool = function (uniformName, bool) {
  21869. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  21870. return this;
  21871. this._valueCache[uniformName] = bool;
  21872. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  21873. return this;
  21874. };
  21875. Effect.prototype.setVector2 = function (uniformName, vector2) {
  21876. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  21877. return this;
  21878. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  21879. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  21880. return this;
  21881. };
  21882. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  21883. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  21884. return this;
  21885. this._cacheFloat2(uniformName, x, y);
  21886. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  21887. return this;
  21888. };
  21889. Effect.prototype.setVector3 = function (uniformName, vector3) {
  21890. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  21891. return this;
  21892. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  21893. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  21894. return this;
  21895. };
  21896. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  21897. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  21898. return this;
  21899. this._cacheFloat3(uniformName, x, y, z);
  21900. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  21901. return this;
  21902. };
  21903. Effect.prototype.setVector4 = function (uniformName, vector4) {
  21904. 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)
  21905. return this;
  21906. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  21907. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  21908. return this;
  21909. };
  21910. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  21911. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  21912. return this;
  21913. this._cacheFloat4(uniformName, x, y, z, w);
  21914. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  21915. return this;
  21916. };
  21917. Effect.prototype.setColor3 = function (uniformName, color3) {
  21918. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  21919. return this;
  21920. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  21921. this._engine.setColor3(this.getUniform(uniformName), color3);
  21922. return this;
  21923. };
  21924. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  21925. 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)
  21926. return this;
  21927. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  21928. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  21929. return this;
  21930. };
  21931. // Statics
  21932. Effect.ShadersStore = {};
  21933. Effect.IncludesShadersStore = {};
  21934. return Effect;
  21935. })();
  21936. BABYLON.Effect = Effect;
  21937. })(BABYLON || (BABYLON = {}));
  21938. var BABYLON;
  21939. (function (BABYLON) {
  21940. var maxSimultaneousLights = 4;
  21941. var MaterialHelper = (function () {
  21942. function MaterialHelper() {
  21943. }
  21944. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  21945. var lightIndex = 0;
  21946. var needNormals = false;
  21947. for (var index = 0; index < scene.lights.length; index++) {
  21948. var light = scene.lights[index];
  21949. if (!light.isEnabled()) {
  21950. continue;
  21951. }
  21952. // Excluded check
  21953. if (light._excludedMeshesIds.length > 0) {
  21954. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  21955. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  21956. if (excludedMesh) {
  21957. light.excludedMeshes.push(excludedMesh);
  21958. }
  21959. }
  21960. light._excludedMeshesIds = [];
  21961. }
  21962. // Included check
  21963. if (light._includedOnlyMeshesIds.length > 0) {
  21964. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  21965. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  21966. if (includedOnlyMesh) {
  21967. light.includedOnlyMeshes.push(includedOnlyMesh);
  21968. }
  21969. }
  21970. light._includedOnlyMeshesIds = [];
  21971. }
  21972. if (!light.canAffectMesh(mesh)) {
  21973. continue;
  21974. }
  21975. needNormals = true;
  21976. defines["LIGHT" + lightIndex] = true;
  21977. var type;
  21978. if (light instanceof BABYLON.SpotLight) {
  21979. type = "SPOTLIGHT" + lightIndex;
  21980. }
  21981. else if (light instanceof BABYLON.HemisphericLight) {
  21982. type = "HEMILIGHT" + lightIndex;
  21983. }
  21984. else if (light instanceof BABYLON.PointLight) {
  21985. type = "POINTLIGHT" + lightIndex;
  21986. }
  21987. else {
  21988. type = "DIRLIGHT" + lightIndex;
  21989. }
  21990. defines[type] = true;
  21991. // Specular
  21992. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  21993. defines["SPECULARTERM"] = true;
  21994. }
  21995. // Shadows
  21996. if (scene.shadowsEnabled) {
  21997. var shadowGenerator = light.getShadowGenerator();
  21998. if (mesh && mesh.receiveShadows && shadowGenerator) {
  21999. defines["SHADOW" + lightIndex] = true;
  22000. defines["SHADOWS"] = true;
  22001. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  22002. defines["SHADOWVSM" + lightIndex] = true;
  22003. }
  22004. if (shadowGenerator.usePoissonSampling) {
  22005. defines["SHADOWPCF" + lightIndex] = true;
  22006. }
  22007. }
  22008. }
  22009. lightIndex++;
  22010. if (lightIndex === maxSimultaneousLights)
  22011. break;
  22012. }
  22013. return needNormals;
  22014. };
  22015. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  22016. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22017. if (!defines["LIGHT" + lightIndex]) {
  22018. continue;
  22019. }
  22020. if (lightIndex > 0) {
  22021. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22022. }
  22023. if (defines["SHADOW" + lightIndex]) {
  22024. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22025. }
  22026. if (defines["SHADOWPCF" + lightIndex]) {
  22027. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22028. }
  22029. if (defines["SHADOWVSM" + lightIndex]) {
  22030. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  22031. }
  22032. }
  22033. };
  22034. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22035. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22036. fallbacks.addCPUSkinningFallback(0, mesh);
  22037. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22038. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22039. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22040. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22041. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22042. }
  22043. }
  22044. };
  22045. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22046. if (defines["INSTANCES"]) {
  22047. attribs.push("world0");
  22048. attribs.push("world1");
  22049. attribs.push("world2");
  22050. attribs.push("world3");
  22051. }
  22052. };
  22053. // Bindings
  22054. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22055. var shadowGenerator = light.getShadowGenerator();
  22056. if (mesh.receiveShadows && shadowGenerator) {
  22057. if (!light.needCube()) {
  22058. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22059. }
  22060. else {
  22061. if (!depthValuesAlreadySet) {
  22062. depthValuesAlreadySet = true;
  22063. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22064. }
  22065. }
  22066. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22067. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  22068. }
  22069. return depthValuesAlreadySet;
  22070. };
  22071. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22072. if (light instanceof BABYLON.PointLight) {
  22073. // Point Light
  22074. light.transferToEffect(effect, "vLightData" + lightIndex);
  22075. }
  22076. else if (light instanceof BABYLON.DirectionalLight) {
  22077. // Directional Light
  22078. light.transferToEffect(effect, "vLightData" + lightIndex);
  22079. }
  22080. else if (light instanceof BABYLON.SpotLight) {
  22081. // Spot Light
  22082. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  22083. }
  22084. else if (light instanceof BABYLON.HemisphericLight) {
  22085. // Hemispheric Light
  22086. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22087. }
  22088. };
  22089. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  22090. var lightIndex = 0;
  22091. var depthValuesAlreadySet = false;
  22092. for (var index = 0; index < scene.lights.length; index++) {
  22093. var light = scene.lights[index];
  22094. if (!light.isEnabled()) {
  22095. continue;
  22096. }
  22097. if (!light.canAffectMesh(mesh)) {
  22098. continue;
  22099. }
  22100. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22101. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22102. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22103. if (defines["SPECULARTERM"]) {
  22104. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22105. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22106. }
  22107. // Shadows
  22108. if (scene.shadowsEnabled) {
  22109. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22110. }
  22111. lightIndex++;
  22112. if (lightIndex === maxSimultaneousLights)
  22113. break;
  22114. }
  22115. };
  22116. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22117. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22118. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22119. effect.setColor3("vFogColor", scene.fogColor);
  22120. }
  22121. };
  22122. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22123. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22124. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  22125. }
  22126. };
  22127. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22128. if (defines["LOGARITHMICDEPTH"]) {
  22129. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22130. }
  22131. };
  22132. MaterialHelper.BindClipPlane = function (effect, scene) {
  22133. if (scene.clipPlane) {
  22134. var clipPlane = scene.clipPlane;
  22135. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22136. }
  22137. };
  22138. return MaterialHelper;
  22139. })();
  22140. BABYLON.MaterialHelper = MaterialHelper;
  22141. })(BABYLON || (BABYLON = {}));
  22142. var BABYLON;
  22143. (function (BABYLON) {
  22144. var FresnelParameters = (function () {
  22145. function FresnelParameters() {
  22146. this.isEnabled = true;
  22147. this.leftColor = BABYLON.Color3.White();
  22148. this.rightColor = BABYLON.Color3.Black();
  22149. this.bias = 0;
  22150. this.power = 1;
  22151. }
  22152. FresnelParameters.prototype.clone = function () {
  22153. var newFresnelParameters = new FresnelParameters();
  22154. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  22155. return new FresnelParameters;
  22156. };
  22157. FresnelParameters.prototype.serialize = function () {
  22158. var serializationObject = {};
  22159. serializationObject.isEnabled = this.isEnabled;
  22160. serializationObject.leftColor = this.leftColor;
  22161. serializationObject.rightColor = this.rightColor;
  22162. serializationObject.bias = this.bias;
  22163. serializationObject.power = this.power;
  22164. return serializationObject;
  22165. };
  22166. FresnelParameters.Parse = function (parsedFresnelParameters) {
  22167. var fresnelParameters = new FresnelParameters();
  22168. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  22169. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  22170. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  22171. fresnelParameters.bias = parsedFresnelParameters.bias;
  22172. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  22173. return fresnelParameters;
  22174. };
  22175. return FresnelParameters;
  22176. })();
  22177. BABYLON.FresnelParameters = FresnelParameters;
  22178. })(BABYLON || (BABYLON = {}));
  22179. var BABYLON;
  22180. (function (BABYLON) {
  22181. var MaterialDefines = (function () {
  22182. function MaterialDefines() {
  22183. }
  22184. MaterialDefines.prototype.isEqual = function (other) {
  22185. for (var index = 0; index < this._keys.length; index++) {
  22186. var prop = this._keys[index];
  22187. if (this[prop] !== other[prop]) {
  22188. return false;
  22189. }
  22190. }
  22191. return true;
  22192. };
  22193. MaterialDefines.prototype.cloneTo = function (other) {
  22194. for (var index = 0; index < this._keys.length; index++) {
  22195. var prop = this._keys[index];
  22196. other[prop] = this[prop];
  22197. }
  22198. };
  22199. MaterialDefines.prototype.reset = function () {
  22200. for (var index = 0; index < this._keys.length; index++) {
  22201. var prop = this._keys[index];
  22202. if (typeof (this[prop]) === "number") {
  22203. this[prop] = 0;
  22204. }
  22205. else {
  22206. this[prop] = false;
  22207. }
  22208. }
  22209. };
  22210. MaterialDefines.prototype.toString = function () {
  22211. var result = "";
  22212. for (var index = 0; index < this._keys.length; index++) {
  22213. var prop = this._keys[index];
  22214. if (typeof (this[prop]) === "number") {
  22215. result += "#define " + prop + " " + this[prop] + "\n";
  22216. }
  22217. else if (this[prop]) {
  22218. result += "#define " + prop + "\n";
  22219. }
  22220. }
  22221. return result;
  22222. };
  22223. return MaterialDefines;
  22224. })();
  22225. BABYLON.MaterialDefines = MaterialDefines;
  22226. var Material = (function () {
  22227. function Material(name, scene, doNotAdd) {
  22228. this.name = name;
  22229. this.checkReadyOnEveryCall = false;
  22230. this.checkReadyOnlyOnce = false;
  22231. this.state = "";
  22232. this.alpha = 1.0;
  22233. this.backFaceCulling = true;
  22234. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22235. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22236. this.disableDepthWrite = false;
  22237. this.fogEnabled = true;
  22238. this.pointSize = 1.0;
  22239. this.zOffset = 0;
  22240. this._wasPreviouslyReady = false;
  22241. this._fillMode = Material.TriangleFillMode;
  22242. this.id = name;
  22243. this._scene = scene;
  22244. if (!doNotAdd) {
  22245. scene.materials.push(this);
  22246. }
  22247. }
  22248. Object.defineProperty(Material, "TriangleFillMode", {
  22249. get: function () {
  22250. return Material._TriangleFillMode;
  22251. },
  22252. enumerable: true,
  22253. configurable: true
  22254. });
  22255. Object.defineProperty(Material, "WireFrameFillMode", {
  22256. get: function () {
  22257. return Material._WireFrameFillMode;
  22258. },
  22259. enumerable: true,
  22260. configurable: true
  22261. });
  22262. Object.defineProperty(Material, "PointFillMode", {
  22263. get: function () {
  22264. return Material._PointFillMode;
  22265. },
  22266. enumerable: true,
  22267. configurable: true
  22268. });
  22269. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22270. get: function () {
  22271. return Material._ClockWiseSideOrientation;
  22272. },
  22273. enumerable: true,
  22274. configurable: true
  22275. });
  22276. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22277. get: function () {
  22278. return Material._CounterClockWiseSideOrientation;
  22279. },
  22280. enumerable: true,
  22281. configurable: true
  22282. });
  22283. Object.defineProperty(Material.prototype, "wireframe", {
  22284. get: function () {
  22285. return this._fillMode === Material.WireFrameFillMode;
  22286. },
  22287. set: function (value) {
  22288. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22289. },
  22290. enumerable: true,
  22291. configurable: true
  22292. });
  22293. Object.defineProperty(Material.prototype, "pointsCloud", {
  22294. get: function () {
  22295. return this._fillMode === Material.PointFillMode;
  22296. },
  22297. set: function (value) {
  22298. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. Object.defineProperty(Material.prototype, "fillMode", {
  22304. get: function () {
  22305. return this._fillMode;
  22306. },
  22307. set: function (value) {
  22308. this._fillMode = value;
  22309. },
  22310. enumerable: true,
  22311. configurable: true
  22312. });
  22313. /**
  22314. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22315. * subclasses should override adding information pertainent to themselves
  22316. */
  22317. Material.prototype.toString = function (fullDetails) {
  22318. var ret = "Name: " + this.name;
  22319. if (fullDetails) {
  22320. }
  22321. return ret;
  22322. };
  22323. Object.defineProperty(Material.prototype, "isFrozen", {
  22324. get: function () {
  22325. return this.checkReadyOnlyOnce;
  22326. },
  22327. enumerable: true,
  22328. configurable: true
  22329. });
  22330. Material.prototype.freeze = function () {
  22331. this.checkReadyOnlyOnce = true;
  22332. };
  22333. Material.prototype.unfreeze = function () {
  22334. this.checkReadyOnlyOnce = false;
  22335. };
  22336. Material.prototype.isReady = function (mesh, useInstances) {
  22337. return true;
  22338. };
  22339. Material.prototype.getEffect = function () {
  22340. return this._effect;
  22341. };
  22342. Material.prototype.getScene = function () {
  22343. return this._scene;
  22344. };
  22345. Material.prototype.needAlphaBlending = function () {
  22346. return (this.alpha < 1.0);
  22347. };
  22348. Material.prototype.needAlphaTesting = function () {
  22349. return false;
  22350. };
  22351. Material.prototype.getAlphaTestTexture = function () {
  22352. return null;
  22353. };
  22354. Material.prototype.trackCreation = function (onCompiled, onError) {
  22355. };
  22356. Material.prototype.markDirty = function () {
  22357. this._wasPreviouslyReady = false;
  22358. };
  22359. Material.prototype._preBind = function () {
  22360. var engine = this._scene.getEngine();
  22361. engine.enableEffect(this._effect);
  22362. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  22363. };
  22364. Material.prototype.bind = function (world, mesh) {
  22365. this._scene._cachedMaterial = this;
  22366. if (this.onBind) {
  22367. this.onBind(this, mesh);
  22368. }
  22369. if (this.disableDepthWrite) {
  22370. var engine = this._scene.getEngine();
  22371. this._cachedDepthWriteState = engine.getDepthWrite();
  22372. engine.setDepthWrite(false);
  22373. }
  22374. };
  22375. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22376. };
  22377. Material.prototype.unbind = function () {
  22378. if (this.disableDepthWrite) {
  22379. var engine = this._scene.getEngine();
  22380. engine.setDepthWrite(this._cachedDepthWriteState);
  22381. }
  22382. };
  22383. Material.prototype.clone = function (name) {
  22384. return null;
  22385. };
  22386. Material.prototype.getBindedMeshes = function () {
  22387. var result = new Array();
  22388. for (var index = 0; index < this._scene.meshes.length; index++) {
  22389. var mesh = this._scene.meshes[index];
  22390. if (mesh.material === this) {
  22391. result.push(mesh);
  22392. }
  22393. }
  22394. return result;
  22395. };
  22396. Material.prototype.dispose = function (forceDisposeEffect) {
  22397. // Animations
  22398. this.getScene().stopAnimation(this);
  22399. // Remove from scene
  22400. var index = this._scene.materials.indexOf(this);
  22401. if (index >= 0) {
  22402. this._scene.materials.splice(index, 1);
  22403. }
  22404. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22405. if (forceDisposeEffect && this._effect) {
  22406. this._scene.getEngine()._releaseEffect(this._effect);
  22407. this._effect = null;
  22408. }
  22409. // Remove from meshes
  22410. for (index = 0; index < this._scene.meshes.length; index++) {
  22411. var mesh = this._scene.meshes[index];
  22412. if (mesh.material === this) {
  22413. mesh.material = null;
  22414. }
  22415. }
  22416. // Callback
  22417. if (this.onDispose) {
  22418. this.onDispose();
  22419. }
  22420. };
  22421. Material.prototype.serialize = function () {
  22422. return BABYLON.SerializationHelper.Serialize(this);
  22423. };
  22424. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22425. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22426. multiMaterial.id = parsedMultiMaterial.id;
  22427. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22428. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22429. var subMatId = parsedMultiMaterial.materials[matIndex];
  22430. if (subMatId) {
  22431. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22432. }
  22433. else {
  22434. multiMaterial.subMaterials.push(null);
  22435. }
  22436. }
  22437. return multiMaterial;
  22438. };
  22439. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22440. if (!parsedMaterial.customType) {
  22441. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  22442. }
  22443. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  22444. return materialType.Parse(parsedMaterial, scene, rootUrl);
  22445. ;
  22446. };
  22447. Material._TriangleFillMode = 0;
  22448. Material._WireFrameFillMode = 1;
  22449. Material._PointFillMode = 2;
  22450. Material._ClockWiseSideOrientation = 0;
  22451. Material._CounterClockWiseSideOrientation = 1;
  22452. __decorate([
  22453. BABYLON.serialize()
  22454. ], Material.prototype, "id", void 0);
  22455. __decorate([
  22456. BABYLON.serialize()
  22457. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  22458. __decorate([
  22459. BABYLON.serialize()
  22460. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  22461. __decorate([
  22462. BABYLON.serialize()
  22463. ], Material.prototype, "state", void 0);
  22464. __decorate([
  22465. BABYLON.serialize()
  22466. ], Material.prototype, "alpha", void 0);
  22467. __decorate([
  22468. BABYLON.serialize()
  22469. ], Material.prototype, "backFaceCulling", void 0);
  22470. __decorate([
  22471. BABYLON.serialize()
  22472. ], Material.prototype, "sideOrientation", void 0);
  22473. __decorate([
  22474. BABYLON.serialize()
  22475. ], Material.prototype, "alphaMode", void 0);
  22476. __decorate([
  22477. BABYLON.serialize()
  22478. ], Material.prototype, "disableDepthWrite", void 0);
  22479. __decorate([
  22480. BABYLON.serialize()
  22481. ], Material.prototype, "fogEnabled", void 0);
  22482. __decorate([
  22483. BABYLON.serialize()
  22484. ], Material.prototype, "pointSize", void 0);
  22485. __decorate([
  22486. BABYLON.serialize()
  22487. ], Material.prototype, "zOffset", void 0);
  22488. __decorate([
  22489. BABYLON.serialize()
  22490. ], Material.prototype, "wireframe", null);
  22491. __decorate([
  22492. BABYLON.serialize()
  22493. ], Material.prototype, "pointsCloud", null);
  22494. __decorate([
  22495. BABYLON.serialize()
  22496. ], Material.prototype, "fillMode", null);
  22497. return Material;
  22498. })();
  22499. BABYLON.Material = Material;
  22500. })(BABYLON || (BABYLON = {}));
  22501. var BABYLON;
  22502. (function (BABYLON) {
  22503. var StandardMaterialDefines = (function (_super) {
  22504. __extends(StandardMaterialDefines, _super);
  22505. function StandardMaterialDefines() {
  22506. _super.call(this);
  22507. this.DIFFUSE = false;
  22508. this.AMBIENT = false;
  22509. this.OPACITY = false;
  22510. this.OPACITYRGB = false;
  22511. this.REFLECTION = false;
  22512. this.EMISSIVE = false;
  22513. this.SPECULAR = false;
  22514. this.BUMP = false;
  22515. this.PARALLAX = false;
  22516. this.PARALLAXOCCLUSION = false;
  22517. this.SPECULAROVERALPHA = false;
  22518. this.CLIPPLANE = false;
  22519. this.ALPHATEST = false;
  22520. this.ALPHAFROMDIFFUSE = false;
  22521. this.POINTSIZE = false;
  22522. this.FOG = false;
  22523. this.LIGHT0 = false;
  22524. this.LIGHT1 = false;
  22525. this.LIGHT2 = false;
  22526. this.LIGHT3 = false;
  22527. this.SPOTLIGHT0 = false;
  22528. this.SPOTLIGHT1 = false;
  22529. this.SPOTLIGHT2 = false;
  22530. this.SPOTLIGHT3 = false;
  22531. this.HEMILIGHT0 = false;
  22532. this.HEMILIGHT1 = false;
  22533. this.HEMILIGHT2 = false;
  22534. this.HEMILIGHT3 = false;
  22535. this.POINTLIGHT0 = false;
  22536. this.POINTLIGHT1 = false;
  22537. this.POINTLIGHT2 = false;
  22538. this.POINTLIGHT3 = false;
  22539. this.DIRLIGHT0 = false;
  22540. this.DIRLIGHT1 = false;
  22541. this.DIRLIGHT2 = false;
  22542. this.DIRLIGHT3 = false;
  22543. this.SPECULARTERM = false;
  22544. this.SHADOW0 = false;
  22545. this.SHADOW1 = false;
  22546. this.SHADOW2 = false;
  22547. this.SHADOW3 = false;
  22548. this.SHADOWS = false;
  22549. this.SHADOWVSM0 = false;
  22550. this.SHADOWVSM1 = false;
  22551. this.SHADOWVSM2 = false;
  22552. this.SHADOWVSM3 = false;
  22553. this.SHADOWPCF0 = false;
  22554. this.SHADOWPCF1 = false;
  22555. this.SHADOWPCF2 = false;
  22556. this.SHADOWPCF3 = false;
  22557. this.DIFFUSEFRESNEL = false;
  22558. this.OPACITYFRESNEL = false;
  22559. this.REFLECTIONFRESNEL = false;
  22560. this.REFRACTIONFRESNEL = false;
  22561. this.EMISSIVEFRESNEL = false;
  22562. this.FRESNEL = false;
  22563. this.NORMAL = false;
  22564. this.UV1 = false;
  22565. this.UV2 = false;
  22566. this.VERTEXCOLOR = false;
  22567. this.VERTEXALPHA = false;
  22568. this.NUM_BONE_INFLUENCERS = 0;
  22569. this.BonesPerMesh = 0;
  22570. this.INSTANCES = false;
  22571. this.GLOSSINESS = false;
  22572. this.ROUGHNESS = false;
  22573. this.EMISSIVEASILLUMINATION = false;
  22574. this.LINKEMISSIVEWITHDIFFUSE = false;
  22575. this.REFLECTIONFRESNELFROMSPECULAR = false;
  22576. this.LIGHTMAP = false;
  22577. this.USELIGHTMAPASSHADOWMAP = false;
  22578. this.REFLECTIONMAP_3D = false;
  22579. this.REFLECTIONMAP_SPHERICAL = false;
  22580. this.REFLECTIONMAP_PLANAR = false;
  22581. this.REFLECTIONMAP_CUBIC = false;
  22582. this.REFLECTIONMAP_PROJECTION = false;
  22583. this.REFLECTIONMAP_SKYBOX = false;
  22584. this.REFLECTIONMAP_EXPLICIT = false;
  22585. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  22586. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  22587. this.INVERTCUBICMAP = false;
  22588. this.LOGARITHMICDEPTH = false;
  22589. this.REFRACTION = false;
  22590. this.REFRACTIONMAP_3D = false;
  22591. this.REFLECTIONOVERALPHA = false;
  22592. this._keys = Object.keys(this);
  22593. }
  22594. return StandardMaterialDefines;
  22595. })(BABYLON.MaterialDefines);
  22596. var StandardMaterial = (function (_super) {
  22597. __extends(StandardMaterial, _super);
  22598. function StandardMaterial(name, scene) {
  22599. var _this = this;
  22600. _super.call(this, name, scene);
  22601. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22602. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  22603. this.specularColor = new BABYLON.Color3(1, 1, 1);
  22604. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  22605. this.specularPower = 64;
  22606. this.useAlphaFromDiffuseTexture = false;
  22607. this.useEmissiveAsIllumination = false;
  22608. this.linkEmissiveWithDiffuse = false;
  22609. this.useReflectionFresnelFromSpecular = false;
  22610. this.useSpecularOverAlpha = false;
  22611. this.useReflectionOverAlpha = false;
  22612. this.disableLighting = false;
  22613. this.useParallax = false;
  22614. this.useParallaxOcclusion = false;
  22615. this.parallaxScaleBias = 0.05;
  22616. this.roughness = 0;
  22617. this.indexOfRefraction = 0.98;
  22618. this.invertRefractionY = true;
  22619. this.useLightmapAsShadowmap = false;
  22620. this.useGlossinessFromSpecularMapAlpha = false;
  22621. this._renderTargets = new BABYLON.SmartArray(16);
  22622. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  22623. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  22624. this._defines = new StandardMaterialDefines();
  22625. this._cachedDefines = new StandardMaterialDefines();
  22626. this._cachedDefines.BonesPerMesh = -1;
  22627. this.getRenderTargetTextures = function () {
  22628. _this._renderTargets.reset();
  22629. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  22630. _this._renderTargets.push(_this.reflectionTexture);
  22631. }
  22632. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  22633. _this._renderTargets.push(_this.refractionTexture);
  22634. }
  22635. return _this._renderTargets;
  22636. };
  22637. }
  22638. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  22639. get: function () {
  22640. return this._useLogarithmicDepth;
  22641. },
  22642. set: function (value) {
  22643. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  22644. },
  22645. enumerable: true,
  22646. configurable: true
  22647. });
  22648. StandardMaterial.prototype.needAlphaBlending = function () {
  22649. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  22650. };
  22651. StandardMaterial.prototype.needAlphaTesting = function () {
  22652. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  22653. };
  22654. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  22655. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  22656. };
  22657. StandardMaterial.prototype.getAlphaTestTexture = function () {
  22658. return this.diffuseTexture;
  22659. };
  22660. // Methods
  22661. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  22662. if (!mesh) {
  22663. return true;
  22664. }
  22665. if (this._defines.INSTANCES !== useInstances) {
  22666. return false;
  22667. }
  22668. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  22669. return true;
  22670. }
  22671. return false;
  22672. };
  22673. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  22674. if (this.isFrozen) {
  22675. if (this._wasPreviouslyReady) {
  22676. return true;
  22677. }
  22678. }
  22679. var scene = this.getScene();
  22680. if (!this.checkReadyOnEveryCall) {
  22681. if (this._renderId === scene.getRenderId()) {
  22682. if (this._checkCache(scene, mesh, useInstances)) {
  22683. return true;
  22684. }
  22685. }
  22686. }
  22687. var engine = scene.getEngine();
  22688. var needNormals = false;
  22689. var needUVs = false;
  22690. this._defines.reset();
  22691. // Textures
  22692. if (scene.texturesEnabled) {
  22693. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22694. if (!this.diffuseTexture.isReady()) {
  22695. return false;
  22696. }
  22697. else {
  22698. needUVs = true;
  22699. this._defines.DIFFUSE = true;
  22700. }
  22701. }
  22702. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22703. if (!this.ambientTexture.isReady()) {
  22704. return false;
  22705. }
  22706. else {
  22707. needUVs = true;
  22708. this._defines.AMBIENT = true;
  22709. }
  22710. }
  22711. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22712. if (!this.opacityTexture.isReady()) {
  22713. return false;
  22714. }
  22715. else {
  22716. needUVs = true;
  22717. this._defines.OPACITY = true;
  22718. if (this.opacityTexture.getAlphaFromRGB) {
  22719. this._defines.OPACITYRGB = true;
  22720. }
  22721. }
  22722. }
  22723. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22724. if (!this.reflectionTexture.isReady()) {
  22725. return false;
  22726. }
  22727. else {
  22728. needNormals = true;
  22729. this._defines.REFLECTION = true;
  22730. if (this.roughness > 0) {
  22731. this._defines.ROUGHNESS = true;
  22732. }
  22733. if (this.useReflectionOverAlpha) {
  22734. this._defines.REFLECTIONOVERALPHA = true;
  22735. }
  22736. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  22737. this._defines.INVERTCUBICMAP = true;
  22738. }
  22739. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  22740. switch (this.reflectionTexture.coordinatesMode) {
  22741. case BABYLON.Texture.CUBIC_MODE:
  22742. case BABYLON.Texture.INVCUBIC_MODE:
  22743. this._defines.REFLECTIONMAP_CUBIC = true;
  22744. break;
  22745. case BABYLON.Texture.EXPLICIT_MODE:
  22746. this._defines.REFLECTIONMAP_EXPLICIT = true;
  22747. break;
  22748. case BABYLON.Texture.PLANAR_MODE:
  22749. this._defines.REFLECTIONMAP_PLANAR = true;
  22750. break;
  22751. case BABYLON.Texture.PROJECTION_MODE:
  22752. this._defines.REFLECTIONMAP_PROJECTION = true;
  22753. break;
  22754. case BABYLON.Texture.SKYBOX_MODE:
  22755. this._defines.REFLECTIONMAP_SKYBOX = true;
  22756. break;
  22757. case BABYLON.Texture.SPHERICAL_MODE:
  22758. this._defines.REFLECTIONMAP_SPHERICAL = true;
  22759. break;
  22760. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  22761. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  22762. break;
  22763. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  22764. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  22765. break;
  22766. }
  22767. }
  22768. }
  22769. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  22770. if (!this.emissiveTexture.isReady()) {
  22771. return false;
  22772. }
  22773. else {
  22774. needUVs = true;
  22775. this._defines.EMISSIVE = true;
  22776. }
  22777. }
  22778. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  22779. if (!this.lightmapTexture.isReady()) {
  22780. return false;
  22781. }
  22782. else {
  22783. needUVs = true;
  22784. this._defines.LIGHTMAP = true;
  22785. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  22786. }
  22787. }
  22788. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  22789. if (!this.specularTexture.isReady()) {
  22790. return false;
  22791. }
  22792. else {
  22793. needUVs = true;
  22794. this._defines.SPECULAR = true;
  22795. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  22796. }
  22797. }
  22798. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  22799. if (!this.bumpTexture.isReady()) {
  22800. return false;
  22801. }
  22802. else {
  22803. needUVs = true;
  22804. this._defines.BUMP = true;
  22805. if (this.useParallax) {
  22806. this._defines.PARALLAX = true;
  22807. if (this.useParallaxOcclusion) {
  22808. this._defines.PARALLAXOCCLUSION = true;
  22809. }
  22810. }
  22811. }
  22812. }
  22813. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  22814. if (!this.refractionTexture.isReady()) {
  22815. return false;
  22816. }
  22817. else {
  22818. needUVs = true;
  22819. this._defines.REFRACTION = true;
  22820. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  22821. }
  22822. }
  22823. }
  22824. // Effect
  22825. if (scene.clipPlane) {
  22826. this._defines.CLIPPLANE = true;
  22827. }
  22828. if (engine.getAlphaTesting()) {
  22829. this._defines.ALPHATEST = true;
  22830. }
  22831. if (this._shouldUseAlphaFromDiffuseTexture()) {
  22832. this._defines.ALPHAFROMDIFFUSE = true;
  22833. }
  22834. if (this.useEmissiveAsIllumination) {
  22835. this._defines.EMISSIVEASILLUMINATION = true;
  22836. }
  22837. if (this.linkEmissiveWithDiffuse) {
  22838. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  22839. }
  22840. if (this.useLogarithmicDepth) {
  22841. this._defines.LOGARITHMICDEPTH = true;
  22842. }
  22843. // Point size
  22844. if (this.pointsCloud || scene.forcePointsCloud) {
  22845. this._defines.POINTSIZE = true;
  22846. }
  22847. // Fog
  22848. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22849. this._defines.FOG = true;
  22850. }
  22851. if (scene.lightsEnabled && !this.disableLighting) {
  22852. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  22853. }
  22854. if (StandardMaterial.FresnelEnabled) {
  22855. // Fresnel
  22856. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  22857. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  22858. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  22859. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  22860. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22861. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  22862. this._defines.DIFFUSEFRESNEL = true;
  22863. }
  22864. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  22865. this._defines.OPACITYFRESNEL = true;
  22866. }
  22867. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22868. this._defines.REFLECTIONFRESNEL = true;
  22869. if (this.useReflectionFresnelFromSpecular) {
  22870. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  22871. }
  22872. }
  22873. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  22874. this._defines.REFRACTIONFRESNEL = true;
  22875. }
  22876. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  22877. this._defines.EMISSIVEFRESNEL = true;
  22878. }
  22879. needNormals = true;
  22880. this._defines.FRESNEL = true;
  22881. }
  22882. }
  22883. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  22884. this._defines.SPECULAROVERALPHA = true;
  22885. }
  22886. // Attribs
  22887. if (mesh) {
  22888. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22889. this._defines.NORMAL = true;
  22890. }
  22891. if (needUVs) {
  22892. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22893. this._defines.UV1 = true;
  22894. }
  22895. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22896. this._defines.UV2 = true;
  22897. }
  22898. }
  22899. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22900. this._defines.VERTEXCOLOR = true;
  22901. if (mesh.hasVertexAlpha) {
  22902. this._defines.VERTEXALPHA = true;
  22903. }
  22904. }
  22905. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22906. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  22907. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  22908. }
  22909. // Instances
  22910. if (useInstances) {
  22911. this._defines.INSTANCES = true;
  22912. }
  22913. }
  22914. // Get correct effect
  22915. if (!this._defines.isEqual(this._cachedDefines)) {
  22916. this._defines.cloneTo(this._cachedDefines);
  22917. scene.resetCachedMaterial();
  22918. // Fallbacks
  22919. var fallbacks = new BABYLON.EffectFallbacks();
  22920. if (this._defines.REFLECTION) {
  22921. fallbacks.addFallback(0, "REFLECTION");
  22922. }
  22923. if (this._defines.SPECULAR) {
  22924. fallbacks.addFallback(0, "SPECULAR");
  22925. }
  22926. if (this._defines.BUMP) {
  22927. fallbacks.addFallback(0, "BUMP");
  22928. }
  22929. if (this._defines.PARALLAX) {
  22930. fallbacks.addFallback(1, "PARALLAX");
  22931. }
  22932. if (this._defines.PARALLAXOCCLUSION) {
  22933. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  22934. }
  22935. if (this._defines.SPECULAROVERALPHA) {
  22936. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  22937. }
  22938. if (this._defines.FOG) {
  22939. fallbacks.addFallback(1, "FOG");
  22940. }
  22941. if (this._defines.POINTSIZE) {
  22942. fallbacks.addFallback(0, "POINTSIZE");
  22943. }
  22944. if (this._defines.LOGARITHMICDEPTH) {
  22945. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  22946. }
  22947. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  22948. if (this._defines.SPECULARTERM) {
  22949. fallbacks.addFallback(0, "SPECULARTERM");
  22950. }
  22951. if (this._defines.DIFFUSEFRESNEL) {
  22952. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  22953. }
  22954. if (this._defines.OPACITYFRESNEL) {
  22955. fallbacks.addFallback(2, "OPACITYFRESNEL");
  22956. }
  22957. if (this._defines.REFLECTIONFRESNEL) {
  22958. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  22959. }
  22960. if (this._defines.EMISSIVEFRESNEL) {
  22961. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  22962. }
  22963. if (this._defines.FRESNEL) {
  22964. fallbacks.addFallback(4, "FRESNEL");
  22965. }
  22966. //Attributes
  22967. var attribs = [BABYLON.VertexBuffer.PositionKind];
  22968. if (this._defines.NORMAL) {
  22969. attribs.push(BABYLON.VertexBuffer.NormalKind);
  22970. }
  22971. if (this._defines.UV1) {
  22972. attribs.push(BABYLON.VertexBuffer.UVKind);
  22973. }
  22974. if (this._defines.UV2) {
  22975. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  22976. }
  22977. if (this._defines.VERTEXCOLOR) {
  22978. attribs.push(BABYLON.VertexBuffer.ColorKind);
  22979. }
  22980. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  22981. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  22982. // Legacy browser patch
  22983. var shaderName = "default";
  22984. if (!scene.getEngine().getCaps().standardDerivatives) {
  22985. shaderName = "legacydefault";
  22986. }
  22987. var join = this._defines.toString();
  22988. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  22989. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  22990. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  22991. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  22992. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  22993. "vFogInfos", "vFogColor", "pointSize",
  22994. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  22995. "mBones",
  22996. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  22997. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  22998. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  22999. "logarithmicDepthConstant"
  23000. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  23001. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  23002. ], join, fallbacks, this.onCompiled, this.onError);
  23003. }
  23004. if (!this._effect.isReady()) {
  23005. return false;
  23006. }
  23007. this._renderId = scene.getRenderId();
  23008. this._wasPreviouslyReady = true;
  23009. if (mesh) {
  23010. if (!mesh._materialDefines) {
  23011. mesh._materialDefines = new StandardMaterialDefines();
  23012. }
  23013. this._defines.cloneTo(mesh._materialDefines);
  23014. }
  23015. return true;
  23016. };
  23017. StandardMaterial.prototype.unbind = function () {
  23018. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  23019. this._effect.setTexture("reflection2DSampler", null);
  23020. }
  23021. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  23022. this._effect.setTexture("refraction2DSampler", null);
  23023. }
  23024. _super.prototype.unbind.call(this);
  23025. };
  23026. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23027. this._effect.setMatrix("world", world);
  23028. };
  23029. StandardMaterial.prototype.bind = function (world, mesh) {
  23030. var scene = this.getScene();
  23031. // Matrices
  23032. this.bindOnlyWorldMatrix(world);
  23033. // Bones
  23034. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  23035. if (scene.getCachedMaterial() !== this) {
  23036. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23037. if (StandardMaterial.FresnelEnabled) {
  23038. // Fresnel
  23039. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23040. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  23041. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  23042. }
  23043. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23044. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  23045. }
  23046. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23047. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  23048. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  23049. }
  23050. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23051. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  23052. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  23053. }
  23054. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23055. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  23056. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  23057. }
  23058. }
  23059. // Textures
  23060. if (scene.texturesEnabled) {
  23061. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23062. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  23063. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  23064. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  23065. }
  23066. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23067. this._effect.setTexture("ambientSampler", this.ambientTexture);
  23068. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  23069. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  23070. }
  23071. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23072. this._effect.setTexture("opacitySampler", this.opacityTexture);
  23073. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  23074. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  23075. }
  23076. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23077. if (this.reflectionTexture.isCube) {
  23078. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  23079. }
  23080. else {
  23081. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  23082. }
  23083. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  23084. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  23085. }
  23086. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23087. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  23088. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  23089. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  23090. }
  23091. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23092. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  23093. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  23094. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  23095. }
  23096. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23097. this._effect.setTexture("specularSampler", this.specularTexture);
  23098. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  23099. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  23100. }
  23101. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  23102. this._effect.setTexture("bumpSampler", this.bumpTexture);
  23103. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  23104. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  23105. }
  23106. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23107. var depth = 1.0;
  23108. if (this.refractionTexture.isCube) {
  23109. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  23110. }
  23111. else {
  23112. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  23113. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  23114. if (this.refractionTexture.depth) {
  23115. depth = this.refractionTexture.depth;
  23116. }
  23117. }
  23118. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  23119. }
  23120. }
  23121. // Clip plane
  23122. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  23123. // Point size
  23124. if (this.pointsCloud) {
  23125. this._effect.setFloat("pointSize", this.pointSize);
  23126. }
  23127. // Colors
  23128. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  23129. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  23130. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  23131. if (this._defines.SPECULARTERM) {
  23132. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  23133. }
  23134. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  23135. }
  23136. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  23137. // Diffuse
  23138. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  23139. // Lights
  23140. if (scene.lightsEnabled && !this.disableLighting) {
  23141. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  23142. }
  23143. // View
  23144. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  23145. this._effect.setMatrix("view", scene.getViewMatrix());
  23146. }
  23147. // Fog
  23148. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  23149. // Log. depth
  23150. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  23151. }
  23152. _super.prototype.bind.call(this, world, mesh);
  23153. };
  23154. StandardMaterial.prototype.getAnimatables = function () {
  23155. var results = [];
  23156. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  23157. results.push(this.diffuseTexture);
  23158. }
  23159. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  23160. results.push(this.ambientTexture);
  23161. }
  23162. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  23163. results.push(this.opacityTexture);
  23164. }
  23165. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  23166. results.push(this.reflectionTexture);
  23167. }
  23168. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  23169. results.push(this.emissiveTexture);
  23170. }
  23171. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  23172. results.push(this.specularTexture);
  23173. }
  23174. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  23175. results.push(this.bumpTexture);
  23176. }
  23177. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  23178. results.push(this.lightmapTexture);
  23179. }
  23180. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  23181. results.push(this.refractionTexture);
  23182. }
  23183. return results;
  23184. };
  23185. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  23186. if (this.diffuseTexture) {
  23187. this.diffuseTexture.dispose();
  23188. }
  23189. if (this.ambientTexture) {
  23190. this.ambientTexture.dispose();
  23191. }
  23192. if (this.opacityTexture) {
  23193. this.opacityTexture.dispose();
  23194. }
  23195. if (this.reflectionTexture) {
  23196. this.reflectionTexture.dispose();
  23197. }
  23198. if (this.emissiveTexture) {
  23199. this.emissiveTexture.dispose();
  23200. }
  23201. if (this.specularTexture) {
  23202. this.specularTexture.dispose();
  23203. }
  23204. if (this.bumpTexture) {
  23205. this.bumpTexture.dispose();
  23206. }
  23207. if (this.lightmapTexture) {
  23208. this.lightmapTexture.dispose();
  23209. }
  23210. if (this.refractionTexture) {
  23211. this.refractionTexture.dispose();
  23212. }
  23213. _super.prototype.dispose.call(this, forceDisposeEffect);
  23214. };
  23215. StandardMaterial.prototype.clone = function (name) {
  23216. var _this = this;
  23217. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  23218. };
  23219. StandardMaterial.prototype.serialize = function () {
  23220. return BABYLON.SerializationHelper.Serialize(this);
  23221. };
  23222. // Statics
  23223. StandardMaterial.Parse = function (source, scene, rootUrl) {
  23224. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  23225. };
  23226. // Flags used to enable or disable a type of texture for all Standard Materials
  23227. StandardMaterial.DiffuseTextureEnabled = true;
  23228. StandardMaterial.AmbientTextureEnabled = true;
  23229. StandardMaterial.OpacityTextureEnabled = true;
  23230. StandardMaterial.ReflectionTextureEnabled = true;
  23231. StandardMaterial.EmissiveTextureEnabled = true;
  23232. StandardMaterial.SpecularTextureEnabled = true;
  23233. StandardMaterial.BumpTextureEnabled = true;
  23234. StandardMaterial.FresnelEnabled = true;
  23235. StandardMaterial.LightmapTextureEnabled = true;
  23236. StandardMaterial.RefractionTextureEnabled = true;
  23237. __decorate([
  23238. BABYLON.serializeAsTexture()
  23239. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  23240. __decorate([
  23241. BABYLON.serializeAsTexture()
  23242. ], StandardMaterial.prototype, "ambientTexture", void 0);
  23243. __decorate([
  23244. BABYLON.serializeAsTexture()
  23245. ], StandardMaterial.prototype, "opacityTexture", void 0);
  23246. __decorate([
  23247. BABYLON.serializeAsTexture()
  23248. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  23249. __decorate([
  23250. BABYLON.serializeAsTexture()
  23251. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  23252. __decorate([
  23253. BABYLON.serializeAsTexture()
  23254. ], StandardMaterial.prototype, "specularTexture", void 0);
  23255. __decorate([
  23256. BABYLON.serializeAsTexture()
  23257. ], StandardMaterial.prototype, "bumpTexture", void 0);
  23258. __decorate([
  23259. BABYLON.serializeAsTexture()
  23260. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  23261. __decorate([
  23262. BABYLON.serializeAsTexture()
  23263. ], StandardMaterial.prototype, "refractionTexture", void 0);
  23264. __decorate([
  23265. BABYLON.serializeAsColor3("ambient")
  23266. ], StandardMaterial.prototype, "ambientColor", void 0);
  23267. __decorate([
  23268. BABYLON.serializeAsColor3("diffuse")
  23269. ], StandardMaterial.prototype, "diffuseColor", void 0);
  23270. __decorate([
  23271. BABYLON.serializeAsColor3("specular")
  23272. ], StandardMaterial.prototype, "specularColor", void 0);
  23273. __decorate([
  23274. BABYLON.serializeAsColor3("emissive")
  23275. ], StandardMaterial.prototype, "emissiveColor", void 0);
  23276. __decorate([
  23277. BABYLON.serialize()
  23278. ], StandardMaterial.prototype, "specularPower", void 0);
  23279. __decorate([
  23280. BABYLON.serialize()
  23281. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  23282. __decorate([
  23283. BABYLON.serialize()
  23284. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  23285. __decorate([
  23286. BABYLON.serialize()
  23287. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  23288. __decorate([
  23289. BABYLON.serialize()
  23290. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  23291. __decorate([
  23292. BABYLON.serialize()
  23293. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  23294. __decorate([
  23295. BABYLON.serialize()
  23296. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  23297. __decorate([
  23298. BABYLON.serialize()
  23299. ], StandardMaterial.prototype, "disableLighting", void 0);
  23300. __decorate([
  23301. BABYLON.serialize()
  23302. ], StandardMaterial.prototype, "useParallax", void 0);
  23303. __decorate([
  23304. BABYLON.serialize()
  23305. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  23306. __decorate([
  23307. BABYLON.serialize()
  23308. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  23309. __decorate([
  23310. BABYLON.serialize()
  23311. ], StandardMaterial.prototype, "roughness", void 0);
  23312. __decorate([
  23313. BABYLON.serialize()
  23314. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  23315. __decorate([
  23316. BABYLON.serialize()
  23317. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  23318. __decorate([
  23319. BABYLON.serialize()
  23320. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  23321. __decorate([
  23322. BABYLON.serializeAsFresnelParameters()
  23323. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  23324. __decorate([
  23325. BABYLON.serializeAsFresnelParameters()
  23326. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  23327. __decorate([
  23328. BABYLON.serializeAsFresnelParameters()
  23329. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  23330. __decorate([
  23331. BABYLON.serializeAsFresnelParameters()
  23332. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  23333. __decorate([
  23334. BABYLON.serializeAsFresnelParameters()
  23335. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  23336. __decorate([
  23337. BABYLON.serialize()
  23338. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  23339. __decorate([
  23340. BABYLON.serialize()
  23341. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  23342. return StandardMaterial;
  23343. })(BABYLON.Material);
  23344. BABYLON.StandardMaterial = StandardMaterial;
  23345. })(BABYLON || (BABYLON = {}));
  23346. var BABYLON;
  23347. (function (BABYLON) {
  23348. var MultiMaterial = (function (_super) {
  23349. __extends(MultiMaterial, _super);
  23350. function MultiMaterial(name, scene) {
  23351. _super.call(this, name, scene, true);
  23352. this.subMaterials = new Array();
  23353. scene.multiMaterials.push(this);
  23354. }
  23355. // Properties
  23356. MultiMaterial.prototype.getSubMaterial = function (index) {
  23357. if (index < 0 || index >= this.subMaterials.length) {
  23358. return this.getScene().defaultMaterial;
  23359. }
  23360. return this.subMaterials[index];
  23361. };
  23362. // Methods
  23363. MultiMaterial.prototype.isReady = function (mesh) {
  23364. for (var index = 0; index < this.subMaterials.length; index++) {
  23365. var subMaterial = this.subMaterials[index];
  23366. if (subMaterial) {
  23367. if (!this.subMaterials[index].isReady(mesh)) {
  23368. return false;
  23369. }
  23370. }
  23371. }
  23372. return true;
  23373. };
  23374. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  23375. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  23376. for (var index = 0; index < this.subMaterials.length; index++) {
  23377. var subMaterial = null;
  23378. if (cloneChildren) {
  23379. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  23380. }
  23381. else {
  23382. subMaterial = this.subMaterials[index];
  23383. }
  23384. newMultiMaterial.subMaterials.push(subMaterial);
  23385. }
  23386. return newMultiMaterial;
  23387. };
  23388. MultiMaterial.prototype.serialize = function () {
  23389. var serializationObject = {};
  23390. serializationObject.name = this.name;
  23391. serializationObject.id = this.id;
  23392. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23393. serializationObject.materials = [];
  23394. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  23395. var subMat = this.subMaterials[matIndex];
  23396. if (subMat) {
  23397. serializationObject.materials.push(subMat.id);
  23398. }
  23399. else {
  23400. serializationObject.materials.push(null);
  23401. }
  23402. }
  23403. return serializationObject;
  23404. };
  23405. return MultiMaterial;
  23406. })(BABYLON.Material);
  23407. BABYLON.MultiMaterial = MultiMaterial;
  23408. })(BABYLON || (BABYLON = {}));
  23409. var BABYLON;
  23410. (function (BABYLON) {
  23411. var SceneLoader = (function () {
  23412. function SceneLoader() {
  23413. }
  23414. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  23415. get: function () {
  23416. return 0;
  23417. },
  23418. enumerable: true,
  23419. configurable: true
  23420. });
  23421. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  23422. get: function () {
  23423. return 1;
  23424. },
  23425. enumerable: true,
  23426. configurable: true
  23427. });
  23428. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  23429. get: function () {
  23430. return 2;
  23431. },
  23432. enumerable: true,
  23433. configurable: true
  23434. });
  23435. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  23436. get: function () {
  23437. return 3;
  23438. },
  23439. enumerable: true,
  23440. configurable: true
  23441. });
  23442. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  23443. get: function () {
  23444. return SceneLoader._ForceFullSceneLoadingForIncremental;
  23445. },
  23446. set: function (value) {
  23447. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  23448. },
  23449. enumerable: true,
  23450. configurable: true
  23451. });
  23452. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  23453. get: function () {
  23454. return SceneLoader._ShowLoadingScreen;
  23455. },
  23456. set: function (value) {
  23457. SceneLoader._ShowLoadingScreen = value;
  23458. },
  23459. enumerable: true,
  23460. configurable: true
  23461. });
  23462. Object.defineProperty(SceneLoader, "loggingLevel", {
  23463. get: function () {
  23464. return SceneLoader._loggingLevel;
  23465. },
  23466. set: function (value) {
  23467. SceneLoader._loggingLevel = value;
  23468. },
  23469. enumerable: true,
  23470. configurable: true
  23471. });
  23472. SceneLoader._getPluginForFilename = function (sceneFilename) {
  23473. var dotPosition = sceneFilename.lastIndexOf(".");
  23474. var queryStringPosition = sceneFilename.indexOf("?");
  23475. if (queryStringPosition === -1) {
  23476. queryStringPosition = sceneFilename.length;
  23477. }
  23478. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  23479. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23480. var plugin = this._registeredPlugins[index];
  23481. if (plugin.extensions.indexOf(extension) !== -1) {
  23482. return plugin;
  23483. }
  23484. }
  23485. return this._registeredPlugins[this._registeredPlugins.length - 1];
  23486. };
  23487. // Public functions
  23488. SceneLoader.GetPluginForExtension = function (extension) {
  23489. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23490. var plugin = this._registeredPlugins[index];
  23491. if (plugin.extensions.indexOf(extension) !== -1) {
  23492. return plugin;
  23493. }
  23494. }
  23495. return null;
  23496. };
  23497. SceneLoader.RegisterPlugin = function (plugin) {
  23498. plugin.extensions = plugin.extensions.toLowerCase();
  23499. SceneLoader._registeredPlugins.push(plugin);
  23500. };
  23501. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23502. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23503. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23504. return;
  23505. }
  23506. var loadingToken = {};
  23507. scene._addPendingData(loadingToken);
  23508. var manifestChecked = function (success) {
  23509. scene.database = database;
  23510. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  23511. var importMeshFromData = function (data) {
  23512. var meshes = [];
  23513. var particleSystems = [];
  23514. var skeletons = [];
  23515. try {
  23516. if (plugin.importMesh) {
  23517. var syncedPlugin = plugin;
  23518. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  23519. if (onerror) {
  23520. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23521. }
  23522. scene._removePendingData(loadingToken);
  23523. return;
  23524. }
  23525. if (onsuccess) {
  23526. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23527. onsuccess(meshes, particleSystems, skeletons);
  23528. scene._removePendingData(loadingToken);
  23529. }
  23530. }
  23531. else {
  23532. var asyncedPlugin = plugin;
  23533. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  23534. if (onsuccess) {
  23535. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23536. onsuccess(meshes, particleSystems, skeletons);
  23537. scene._removePendingData(loadingToken);
  23538. }
  23539. }, function () {
  23540. if (onerror) {
  23541. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23542. }
  23543. scene._removePendingData(loadingToken);
  23544. });
  23545. }
  23546. }
  23547. catch (e) {
  23548. if (onerror) {
  23549. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  23550. }
  23551. scene._removePendingData(loadingToken);
  23552. }
  23553. };
  23554. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23555. // Direct load
  23556. importMeshFromData(sceneFilename.substr(5));
  23557. return;
  23558. }
  23559. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  23560. importMeshFromData(data);
  23561. }, progressCallBack, database);
  23562. };
  23563. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  23564. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23565. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23566. }
  23567. else {
  23568. // If the scene is a data stream or offline support is not enabled, it's a direct load
  23569. manifestChecked(true);
  23570. }
  23571. };
  23572. /**
  23573. * Load a scene
  23574. * @param rootUrl a string that defines the root url for scene and resources
  23575. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23576. * @param engine is the instance of BABYLON.Engine to use to create the scene
  23577. */
  23578. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  23579. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  23580. };
  23581. /**
  23582. * Append a scene
  23583. * @param rootUrl a string that defines the root url for scene and resources
  23584. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23585. * @param scene is the instance of BABYLON.Scene to append to
  23586. */
  23587. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23588. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23589. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23590. return;
  23591. }
  23592. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  23593. var database;
  23594. var loadingToken = {};
  23595. scene._addPendingData(loadingToken);
  23596. if (SceneLoader.ShowLoadingScreen) {
  23597. scene.getEngine().displayLoadingUI();
  23598. }
  23599. var loadSceneFromData = function (data) {
  23600. scene.database = database;
  23601. if (plugin.load) {
  23602. var syncedPlugin = plugin;
  23603. if (!syncedPlugin.load(scene, data, rootUrl)) {
  23604. if (onerror) {
  23605. onerror(scene);
  23606. }
  23607. scene._removePendingData(loadingToken);
  23608. scene.getEngine().hideLoadingUI();
  23609. return;
  23610. }
  23611. if (onsuccess) {
  23612. onsuccess(scene);
  23613. }
  23614. scene._removePendingData(loadingToken);
  23615. }
  23616. else {
  23617. var asyncedPlugin = plugin;
  23618. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  23619. if (onsuccess) {
  23620. onsuccess(scene);
  23621. }
  23622. }, function () {
  23623. if (onerror) {
  23624. onerror(scene);
  23625. }
  23626. scene._removePendingData(loadingToken);
  23627. scene.getEngine().hideLoadingUI();
  23628. });
  23629. }
  23630. if (SceneLoader.ShowLoadingScreen) {
  23631. scene.executeWhenReady(function () {
  23632. scene.getEngine().hideLoadingUI();
  23633. });
  23634. }
  23635. };
  23636. var manifestChecked = function (success) {
  23637. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  23638. };
  23639. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23640. // Direct load
  23641. loadSceneFromData(sceneFilename.substr(5));
  23642. return;
  23643. }
  23644. if (rootUrl.indexOf("file:") === -1) {
  23645. if (scene.getEngine().enableOfflineSupport) {
  23646. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23647. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23648. }
  23649. else {
  23650. manifestChecked(true);
  23651. }
  23652. }
  23653. else {
  23654. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  23655. }
  23656. };
  23657. // Flags
  23658. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  23659. SceneLoader._ShowLoadingScreen = true;
  23660. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  23661. // Members
  23662. SceneLoader._registeredPlugins = new Array();
  23663. return SceneLoader;
  23664. })();
  23665. BABYLON.SceneLoader = SceneLoader;
  23666. ;
  23667. })(BABYLON || (BABYLON = {}));
  23668. var BABYLON;
  23669. (function (BABYLON) {
  23670. var Internals;
  23671. (function (Internals) {
  23672. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  23673. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23674. var parsedMaterial = parsedData.materials[index];
  23675. if (parsedMaterial.id === id) {
  23676. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23677. }
  23678. }
  23679. return null;
  23680. };
  23681. var isDescendantOf = function (mesh, names, hierarchyIds) {
  23682. names = (names instanceof Array) ? names : [names];
  23683. for (var i in names) {
  23684. if (mesh.name === names[i]) {
  23685. hierarchyIds.push(mesh.id);
  23686. return true;
  23687. }
  23688. }
  23689. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  23690. hierarchyIds.push(mesh.id);
  23691. return true;
  23692. }
  23693. return false;
  23694. };
  23695. var logOperation = function (operation, producer) {
  23696. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  23697. };
  23698. BABYLON.SceneLoader.RegisterPlugin({
  23699. extensions: ".babylon",
  23700. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  23701. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23702. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23703. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23704. // and avoid problems with multiple concurrent .babylon loads.
  23705. var log = "importMesh has failed JSON parse";
  23706. try {
  23707. var parsedData = JSON.parse(data);
  23708. log = "";
  23709. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23710. var loadedSkeletonsIds = [];
  23711. var loadedMaterialsIds = [];
  23712. var hierarchyIds = [];
  23713. var index;
  23714. var cache;
  23715. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23716. var parsedMesh = parsedData.meshes[index];
  23717. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  23718. if (meshesNames instanceof Array) {
  23719. // Remove found mesh name from list.
  23720. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  23721. }
  23722. //Geometry?
  23723. if (parsedMesh.geometryId) {
  23724. //does the file contain geometries?
  23725. if (parsedData.geometries) {
  23726. //find the correct geometry and add it to the scene
  23727. var found = false;
  23728. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  23729. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  23730. return;
  23731. }
  23732. else {
  23733. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  23734. if (parsedGeometryData.id === parsedMesh.geometryId) {
  23735. switch (geometryType) {
  23736. case "boxes":
  23737. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  23738. break;
  23739. case "spheres":
  23740. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  23741. break;
  23742. case "cylinders":
  23743. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  23744. break;
  23745. case "toruses":
  23746. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  23747. break;
  23748. case "grounds":
  23749. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  23750. break;
  23751. case "planes":
  23752. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  23753. break;
  23754. case "torusKnots":
  23755. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  23756. break;
  23757. case "vertexData":
  23758. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  23759. break;
  23760. }
  23761. found = true;
  23762. }
  23763. });
  23764. }
  23765. });
  23766. if (!found) {
  23767. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  23768. }
  23769. }
  23770. }
  23771. // Material ?
  23772. if (parsedMesh.materialId) {
  23773. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  23774. if (!materialFound && parsedData.multiMaterials) {
  23775. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  23776. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  23777. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  23778. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  23779. var subMatId = parsedMultiMaterial.materials[matIndex];
  23780. loadedMaterialsIds.push(subMatId);
  23781. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  23782. log += "\n\tMaterial " + mat.toString(fullDetails);
  23783. }
  23784. loadedMaterialsIds.push(parsedMultiMaterial.id);
  23785. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23786. materialFound = true;
  23787. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  23788. break;
  23789. }
  23790. }
  23791. }
  23792. if (!materialFound) {
  23793. loadedMaterialsIds.push(parsedMesh.materialId);
  23794. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  23795. if (!mat) {
  23796. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  23797. }
  23798. else {
  23799. log += "\n\tMaterial " + mat.toString(fullDetails);
  23800. }
  23801. }
  23802. }
  23803. // Skeleton ?
  23804. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  23805. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  23806. if (!skeletonAlreadyLoaded) {
  23807. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  23808. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  23809. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  23810. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23811. skeletons.push(skeleton);
  23812. loadedSkeletonsIds.push(parsedSkeleton.id);
  23813. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  23814. }
  23815. }
  23816. }
  23817. }
  23818. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  23819. meshes.push(mesh);
  23820. log += "\n\tMesh " + mesh.toString(fullDetails);
  23821. }
  23822. }
  23823. // Connecting parents
  23824. var currentMesh;
  23825. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23826. currentMesh = scene.meshes[index];
  23827. if (currentMesh._waitingParentId) {
  23828. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  23829. currentMesh._waitingParentId = undefined;
  23830. }
  23831. }
  23832. // freeze and compute world matrix application
  23833. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23834. currentMesh = scene.meshes[index];
  23835. if (currentMesh._waitingFreezeWorldMatrix) {
  23836. currentMesh.freezeWorldMatrix();
  23837. currentMesh._waitingFreezeWorldMatrix = undefined;
  23838. }
  23839. else {
  23840. currentMesh.computeWorldMatrix(true);
  23841. }
  23842. }
  23843. // Particles
  23844. if (parsedData.particleSystems) {
  23845. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  23846. var parsedParticleSystem = parsedData.particleSystems[index];
  23847. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  23848. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  23849. }
  23850. }
  23851. }
  23852. return true;
  23853. }
  23854. catch (err) {
  23855. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  23856. log = null;
  23857. throw err;
  23858. }
  23859. finally {
  23860. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  23861. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  23862. }
  23863. }
  23864. },
  23865. load: function (scene, data, rootUrl) {
  23866. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23867. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23868. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23869. // and avoid problems with multiple concurrent .babylon loads.
  23870. var log = "importScene has failed JSON parse";
  23871. try {
  23872. var parsedData = JSON.parse(data);
  23873. log = "";
  23874. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23875. // Scene
  23876. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  23877. scene.autoClear = parsedData.autoClear;
  23878. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  23879. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  23880. if (parsedData.gravity) {
  23881. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  23882. }
  23883. // Fog
  23884. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  23885. scene.fogMode = parsedData.fogMode;
  23886. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  23887. scene.fogStart = parsedData.fogStart;
  23888. scene.fogEnd = parsedData.fogEnd;
  23889. scene.fogDensity = parsedData.fogDensity;
  23890. log += "\tFog mode for scene: ";
  23891. switch (scene.fogMode) {
  23892. // getters not compiling, so using hardcoded
  23893. case 1:
  23894. log += "exp\n";
  23895. break;
  23896. case 2:
  23897. log += "exp2\n";
  23898. break;
  23899. case 3:
  23900. log += "linear\n";
  23901. break;
  23902. }
  23903. }
  23904. //Physics
  23905. if (parsedData.physicsEnabled) {
  23906. var physicsPlugin;
  23907. if (parsedData.physicsEngine === "cannon") {
  23908. physicsPlugin = new BABYLON.CannonJSPlugin();
  23909. }
  23910. else if (parsedData.physicsEngine === "oimo") {
  23911. physicsPlugin = new BABYLON.OimoJSPlugin();
  23912. }
  23913. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  23914. //else - default engine, which is currently oimo
  23915. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  23916. scene.enablePhysics(physicsGravity, physicsPlugin);
  23917. }
  23918. //collisions, if defined. otherwise, default is true
  23919. if (parsedData.collisionsEnabled != undefined) {
  23920. scene.collisionsEnabled = parsedData.collisionsEnabled;
  23921. }
  23922. scene.workerCollisions = !!parsedData.workerCollisions;
  23923. var index;
  23924. var cache;
  23925. // Lights
  23926. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  23927. var parsedLight = parsedData.lights[index];
  23928. var light = BABYLON.Light.Parse(parsedLight, scene);
  23929. log += (index === 0 ? "\n\tLights:" : "");
  23930. log += "\n\t\t" + light.toString(fullDetails);
  23931. }
  23932. // Animations
  23933. if (parsedData.animations) {
  23934. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  23935. var parsedAnimation = parsedData.animations[index];
  23936. var animation = BABYLON.Animation.Parse(parsedAnimation);
  23937. scene.animations.push(animation);
  23938. log += (index === 0 ? "\n\tAnimations:" : "");
  23939. log += "\n\t\t" + animation.toString(fullDetails);
  23940. }
  23941. }
  23942. // Materials
  23943. if (parsedData.materials) {
  23944. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23945. var parsedMaterial = parsedData.materials[index];
  23946. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23947. log += (index === 0 ? "\n\tMaterials:" : "");
  23948. log += "\n\t\t" + mat.toString(fullDetails);
  23949. }
  23950. }
  23951. if (parsedData.multiMaterials) {
  23952. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  23953. var parsedMultiMaterial = parsedData.multiMaterials[index];
  23954. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23955. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  23956. log += "\n\t\t" + mmat.toString(fullDetails);
  23957. }
  23958. }
  23959. // Skeletons
  23960. if (parsedData.skeletons) {
  23961. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  23962. var parsedSkeleton = parsedData.skeletons[index];
  23963. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23964. log += (index === 0 ? "\n\tSkeletons:" : "");
  23965. log += "\n\t\t" + skeleton.toString(fullDetails);
  23966. }
  23967. }
  23968. // Geometries
  23969. var geometries = parsedData.geometries;
  23970. if (geometries) {
  23971. // Boxes
  23972. var boxes = geometries.boxes;
  23973. if (boxes) {
  23974. for (index = 0, cache = boxes.length; index < cache; index++) {
  23975. var parsedBox = boxes[index];
  23976. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  23977. }
  23978. }
  23979. // Spheres
  23980. var spheres = geometries.spheres;
  23981. if (spheres) {
  23982. for (index = 0, cache = spheres.length; index < cache; index++) {
  23983. var parsedSphere = spheres[index];
  23984. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  23985. }
  23986. }
  23987. // Cylinders
  23988. var cylinders = geometries.cylinders;
  23989. if (cylinders) {
  23990. for (index = 0, cache = cylinders.length; index < cache; index++) {
  23991. var parsedCylinder = cylinders[index];
  23992. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  23993. }
  23994. }
  23995. // Toruses
  23996. var toruses = geometries.toruses;
  23997. if (toruses) {
  23998. for (index = 0, cache = toruses.length; index < cache; index++) {
  23999. var parsedTorus = toruses[index];
  24000. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  24001. }
  24002. }
  24003. // Grounds
  24004. var grounds = geometries.grounds;
  24005. if (grounds) {
  24006. for (index = 0, cache = grounds.length; index < cache; index++) {
  24007. var parsedGround = grounds[index];
  24008. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  24009. }
  24010. }
  24011. // Planes
  24012. var planes = geometries.planes;
  24013. if (planes) {
  24014. for (index = 0, cache = planes.length; index < cache; index++) {
  24015. var parsedPlane = planes[index];
  24016. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  24017. }
  24018. }
  24019. // TorusKnots
  24020. var torusKnots = geometries.torusKnots;
  24021. if (torusKnots) {
  24022. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  24023. var parsedTorusKnot = torusKnots[index];
  24024. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  24025. }
  24026. }
  24027. // VertexData
  24028. var vertexData = geometries.vertexData;
  24029. if (vertexData) {
  24030. for (index = 0, cache = vertexData.length; index < cache; index++) {
  24031. var parsedVertexData = vertexData[index];
  24032. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  24033. }
  24034. }
  24035. }
  24036. // Meshes
  24037. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24038. var parsedMesh = parsedData.meshes[index];
  24039. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24040. log += (index === 0 ? "\n\tMeshes:" : "");
  24041. log += "\n\t\t" + mesh.toString(fullDetails);
  24042. }
  24043. // Cameras
  24044. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  24045. var parsedCamera = parsedData.cameras[index];
  24046. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  24047. log += (index === 0 ? "\n\tCameras:" : "");
  24048. log += "\n\t\t" + camera.toString(fullDetails);
  24049. }
  24050. if (parsedData.activeCameraID) {
  24051. scene.setActiveCameraByID(parsedData.activeCameraID);
  24052. }
  24053. // Browsing all the graph to connect the dots
  24054. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  24055. var camera = scene.cameras[index];
  24056. if (camera._waitingParentId) {
  24057. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  24058. camera._waitingParentId = undefined;
  24059. }
  24060. }
  24061. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  24062. var light = scene.lights[index];
  24063. if (light._waitingParentId) {
  24064. light.parent = scene.getLastEntryByID(light._waitingParentId);
  24065. light._waitingParentId = undefined;
  24066. }
  24067. }
  24068. // Sounds
  24069. var loadedSounds = [];
  24070. var loadedSound;
  24071. if (BABYLON.AudioEngine && parsedData.sounds) {
  24072. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  24073. var parsedSound = parsedData.sounds[index];
  24074. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  24075. if (!parsedSound.url)
  24076. parsedSound.url = parsedSound.name;
  24077. if (!loadedSounds[parsedSound.url]) {
  24078. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  24079. loadedSounds[parsedSound.url] = loadedSound;
  24080. }
  24081. else {
  24082. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  24083. }
  24084. }
  24085. else {
  24086. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  24087. }
  24088. }
  24089. }
  24090. loadedSounds = [];
  24091. // Connect parents & children and parse actions
  24092. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24093. var mesh = scene.meshes[index];
  24094. if (mesh._waitingParentId) {
  24095. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  24096. mesh._waitingParentId = undefined;
  24097. }
  24098. if (mesh._waitingActions) {
  24099. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  24100. mesh._waitingActions = undefined;
  24101. }
  24102. }
  24103. // freeze world matrix application
  24104. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24105. var currentMesh = scene.meshes[index];
  24106. if (currentMesh._waitingFreezeWorldMatrix) {
  24107. currentMesh.freezeWorldMatrix();
  24108. currentMesh._waitingFreezeWorldMatrix = undefined;
  24109. }
  24110. else {
  24111. currentMesh.computeWorldMatrix(true);
  24112. }
  24113. }
  24114. // Particles Systems
  24115. if (parsedData.particleSystems) {
  24116. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24117. var parsedParticleSystem = parsedData.particleSystems[index];
  24118. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  24119. }
  24120. }
  24121. // Lens flares
  24122. if (parsedData.lensFlareSystems) {
  24123. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  24124. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  24125. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  24126. }
  24127. }
  24128. // Shadows
  24129. if (parsedData.shadowGenerators) {
  24130. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  24131. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  24132. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  24133. }
  24134. }
  24135. // Actions (scene)
  24136. if (parsedData.actions) {
  24137. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  24138. }
  24139. // Finish
  24140. return true;
  24141. }
  24142. catch (err) {
  24143. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  24144. log = null;
  24145. throw err;
  24146. }
  24147. finally {
  24148. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24149. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24150. }
  24151. }
  24152. }
  24153. });
  24154. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24155. })(BABYLON || (BABYLON = {}));
  24156. var BABYLON;
  24157. (function (BABYLON) {
  24158. var SpriteManager = (function () {
  24159. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  24160. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24161. this.name = name;
  24162. this.cellSize = cellSize;
  24163. this.sprites = new Array();
  24164. this.renderingGroupId = 0;
  24165. this.layerMask = 0x0FFFFFFF;
  24166. this.fogEnabled = true;
  24167. this.isPickable = false;
  24168. this._vertexDeclaration = [4, 4, 4, 4];
  24169. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  24170. this._capacity = capacity;
  24171. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  24172. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24173. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24174. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  24175. this._scene = scene;
  24176. this._scene.spriteManagers.push(this);
  24177. // VBO
  24178. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24179. var indices = [];
  24180. var index = 0;
  24181. for (var count = 0; count < capacity; count++) {
  24182. indices.push(index);
  24183. indices.push(index + 1);
  24184. indices.push(index + 2);
  24185. indices.push(index);
  24186. indices.push(index + 2);
  24187. indices.push(index + 3);
  24188. index += 4;
  24189. }
  24190. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24191. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24192. // Effects
  24193. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  24194. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  24195. }
  24196. Object.defineProperty(SpriteManager.prototype, "texture", {
  24197. get: function () {
  24198. return this._spriteTexture;
  24199. },
  24200. set: function (value) {
  24201. this._spriteTexture = value;
  24202. },
  24203. enumerable: true,
  24204. configurable: true
  24205. });
  24206. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  24207. var arrayOffset = index * 16;
  24208. if (offsetX === 0)
  24209. offsetX = this._epsilon;
  24210. else if (offsetX === 1)
  24211. offsetX = 1 - this._epsilon;
  24212. if (offsetY === 0)
  24213. offsetY = this._epsilon;
  24214. else if (offsetY === 1)
  24215. offsetY = 1 - this._epsilon;
  24216. this._vertices[arrayOffset] = sprite.position.x;
  24217. this._vertices[arrayOffset + 1] = sprite.position.y;
  24218. this._vertices[arrayOffset + 2] = sprite.position.z;
  24219. this._vertices[arrayOffset + 3] = sprite.angle;
  24220. this._vertices[arrayOffset + 4] = sprite.width;
  24221. this._vertices[arrayOffset + 5] = sprite.height;
  24222. this._vertices[arrayOffset + 6] = offsetX;
  24223. this._vertices[arrayOffset + 7] = offsetY;
  24224. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  24225. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  24226. var offset = (sprite.cellIndex / rowSize) >> 0;
  24227. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  24228. this._vertices[arrayOffset + 11] = offset;
  24229. // Color
  24230. this._vertices[arrayOffset + 12] = sprite.color.r;
  24231. this._vertices[arrayOffset + 13] = sprite.color.g;
  24232. this._vertices[arrayOffset + 14] = sprite.color.b;
  24233. this._vertices[arrayOffset + 15] = sprite.color.a;
  24234. };
  24235. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  24236. var count = Math.min(this._capacity, this.sprites.length);
  24237. var min = BABYLON.Vector3.Zero();
  24238. var max = BABYLON.Vector3.Zero();
  24239. var distance = Number.MAX_VALUE;
  24240. var currentSprite;
  24241. var cameraSpacePosition = BABYLON.Vector3.Zero();
  24242. var cameraView = camera.getViewMatrix();
  24243. for (var index = 0; index < count; index++) {
  24244. var sprite = this.sprites[index];
  24245. if (!sprite) {
  24246. continue;
  24247. }
  24248. if (predicate) {
  24249. if (!predicate(sprite)) {
  24250. continue;
  24251. }
  24252. }
  24253. else if (!sprite.isPickable) {
  24254. continue;
  24255. }
  24256. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  24257. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  24258. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  24259. if (ray.intersectsBoxMinMax(min, max)) {
  24260. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  24261. if (distance > currentDistance) {
  24262. distance = currentDistance;
  24263. currentSprite = sprite;
  24264. if (fastCheck) {
  24265. break;
  24266. }
  24267. }
  24268. }
  24269. }
  24270. if (currentSprite) {
  24271. var result = new BABYLON.PickingInfo();
  24272. result.hit = true;
  24273. result.pickedSprite = currentSprite;
  24274. result.distance = distance;
  24275. return result;
  24276. }
  24277. return null;
  24278. };
  24279. SpriteManager.prototype.render = function () {
  24280. // Check
  24281. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  24282. return;
  24283. var engine = this._scene.getEngine();
  24284. var baseSize = this._spriteTexture.getBaseSize();
  24285. // Sprites
  24286. var deltaTime = engine.getDeltaTime();
  24287. var max = Math.min(this._capacity, this.sprites.length);
  24288. var rowSize = baseSize.width / this.cellSize;
  24289. var offset = 0;
  24290. for (var index = 0; index < max; index++) {
  24291. var sprite = this.sprites[index];
  24292. if (!sprite) {
  24293. continue;
  24294. }
  24295. sprite._animate(deltaTime);
  24296. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  24297. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  24298. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  24299. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  24300. }
  24301. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24302. // Render
  24303. var effect = this._effectBase;
  24304. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24305. effect = this._effectFog;
  24306. }
  24307. engine.enableEffect(effect);
  24308. var viewMatrix = this._scene.getViewMatrix();
  24309. effect.setTexture("diffuseSampler", this._spriteTexture);
  24310. effect.setMatrix("view", viewMatrix);
  24311. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24312. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  24313. // Fog
  24314. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24315. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  24316. effect.setColor3("vFogColor", this._scene.fogColor);
  24317. }
  24318. // VBOs
  24319. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24320. // Draw order
  24321. engine.setDepthFunctionToLessOrEqual();
  24322. effect.setBool("alphaTest", true);
  24323. engine.setColorWrite(false);
  24324. engine.draw(true, 0, max * 6);
  24325. engine.setColorWrite(true);
  24326. effect.setBool("alphaTest", false);
  24327. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24328. engine.draw(true, 0, max * 6);
  24329. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24330. };
  24331. SpriteManager.prototype.dispose = function () {
  24332. if (this._vertexBuffer) {
  24333. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24334. this._vertexBuffer = null;
  24335. }
  24336. if (this._indexBuffer) {
  24337. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24338. this._indexBuffer = null;
  24339. }
  24340. if (this._spriteTexture) {
  24341. this._spriteTexture.dispose();
  24342. this._spriteTexture = null;
  24343. }
  24344. // Remove from scene
  24345. var index = this._scene.spriteManagers.indexOf(this);
  24346. this._scene.spriteManagers.splice(index, 1);
  24347. // Callback
  24348. if (this.onDispose) {
  24349. this.onDispose();
  24350. }
  24351. };
  24352. return SpriteManager;
  24353. })();
  24354. BABYLON.SpriteManager = SpriteManager;
  24355. })(BABYLON || (BABYLON = {}));
  24356. var BABYLON;
  24357. (function (BABYLON) {
  24358. var Sprite = (function () {
  24359. function Sprite(name, manager) {
  24360. this.name = name;
  24361. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24362. this.width = 1.0;
  24363. this.height = 1.0;
  24364. this.angle = 0;
  24365. this.cellIndex = 0;
  24366. this.invertU = 0;
  24367. this.invertV = 0;
  24368. this.animations = new Array();
  24369. this.isPickable = false;
  24370. this._animationStarted = false;
  24371. this._loopAnimation = false;
  24372. this._fromIndex = 0;
  24373. this._toIndex = 0;
  24374. this._delay = 0;
  24375. this._direction = 1;
  24376. this._frameCount = 0;
  24377. this._time = 0;
  24378. this._manager = manager;
  24379. this._manager.sprites.push(this);
  24380. this.position = BABYLON.Vector3.Zero();
  24381. }
  24382. Object.defineProperty(Sprite.prototype, "size", {
  24383. get: function () {
  24384. return this.width;
  24385. },
  24386. set: function (value) {
  24387. this.width = value;
  24388. this.height = value;
  24389. },
  24390. enumerable: true,
  24391. configurable: true
  24392. });
  24393. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  24394. this._fromIndex = from;
  24395. this._toIndex = to;
  24396. this._loopAnimation = loop;
  24397. this._delay = delay;
  24398. this._animationStarted = true;
  24399. this._direction = from < to ? 1 : -1;
  24400. this.cellIndex = from;
  24401. this._time = 0;
  24402. };
  24403. Sprite.prototype.stopAnimation = function () {
  24404. this._animationStarted = false;
  24405. };
  24406. Sprite.prototype._animate = function (deltaTime) {
  24407. if (!this._animationStarted)
  24408. return;
  24409. this._time += deltaTime;
  24410. if (this._time > this._delay) {
  24411. this._time = this._time % this._delay;
  24412. this.cellIndex += this._direction;
  24413. if (this.cellIndex == this._toIndex) {
  24414. if (this._loopAnimation) {
  24415. this.cellIndex = this._fromIndex;
  24416. }
  24417. else {
  24418. this._animationStarted = false;
  24419. if (this.disposeWhenFinishedAnimating) {
  24420. this.dispose();
  24421. }
  24422. }
  24423. }
  24424. }
  24425. };
  24426. Sprite.prototype.dispose = function () {
  24427. for (var i = 0; i < this._manager.sprites.length; i++) {
  24428. if (this._manager.sprites[i] == this) {
  24429. this._manager.sprites.splice(i, 1);
  24430. }
  24431. }
  24432. };
  24433. return Sprite;
  24434. })();
  24435. BABYLON.Sprite = Sprite;
  24436. })(BABYLON || (BABYLON = {}));
  24437. var BABYLON;
  24438. (function (BABYLON) {
  24439. var Layer = (function () {
  24440. function Layer(name, imgUrl, scene, isBackground, color) {
  24441. this.name = name;
  24442. this.scale = new BABYLON.Vector2(1, 1);
  24443. this.offset = new BABYLON.Vector2(0, 0);
  24444. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  24445. this._vertexDeclaration = [2];
  24446. this._vertexStrideSize = 2 * 4;
  24447. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  24448. this.isBackground = isBackground === undefined ? true : isBackground;
  24449. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  24450. this._scene = scene;
  24451. this._scene.layers.push(this);
  24452. // VBO
  24453. var vertices = [];
  24454. vertices.push(1, 1);
  24455. vertices.push(-1, 1);
  24456. vertices.push(-1, -1);
  24457. vertices.push(1, -1);
  24458. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  24459. // Indices
  24460. var indices = [];
  24461. indices.push(0);
  24462. indices.push(1);
  24463. indices.push(2);
  24464. indices.push(0);
  24465. indices.push(2);
  24466. indices.push(3);
  24467. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24468. // Effects
  24469. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  24470. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  24471. }
  24472. Layer.prototype.render = function () {
  24473. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  24474. // Check
  24475. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  24476. return;
  24477. var engine = this._scene.getEngine();
  24478. if (this.onBeforeRender) {
  24479. this.onBeforeRender();
  24480. }
  24481. // Render
  24482. engine.enableEffect(currentEffect);
  24483. engine.setState(false);
  24484. // Texture
  24485. currentEffect.setTexture("textureSampler", this.texture);
  24486. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  24487. // Color
  24488. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  24489. // Scale / offset
  24490. currentEffect.setVector2("offset", this.offset);
  24491. currentEffect.setVector2("scale", this.scale);
  24492. // VBOs
  24493. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  24494. // Draw order
  24495. if (!this._alphaTestEffect) {
  24496. engine.setAlphaMode(this.alphaBlendingMode);
  24497. engine.draw(true, 0, 6);
  24498. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24499. }
  24500. else {
  24501. engine.draw(true, 0, 6);
  24502. }
  24503. if (this.onAfterRender) {
  24504. this.onAfterRender();
  24505. }
  24506. };
  24507. Layer.prototype.dispose = function () {
  24508. if (this._vertexBuffer) {
  24509. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24510. this._vertexBuffer = null;
  24511. }
  24512. if (this._indexBuffer) {
  24513. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24514. this._indexBuffer = null;
  24515. }
  24516. if (this.texture) {
  24517. this.texture.dispose();
  24518. this.texture = null;
  24519. }
  24520. // Remove from scene
  24521. var index = this._scene.layers.indexOf(this);
  24522. this._scene.layers.splice(index, 1);
  24523. // Callback
  24524. if (this.onDispose) {
  24525. this.onDispose();
  24526. }
  24527. };
  24528. return Layer;
  24529. })();
  24530. BABYLON.Layer = Layer;
  24531. })(BABYLON || (BABYLON = {}));
  24532. var BABYLON;
  24533. (function (BABYLON) {
  24534. var Particle = (function () {
  24535. function Particle() {
  24536. this.position = BABYLON.Vector3.Zero();
  24537. this.direction = BABYLON.Vector3.Zero();
  24538. this.color = new BABYLON.Color4(0, 0, 0, 0);
  24539. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  24540. this.lifeTime = 1.0;
  24541. this.age = 0;
  24542. this.size = 0;
  24543. this.angle = 0;
  24544. this.angularSpeed = 0;
  24545. }
  24546. Particle.prototype.copyTo = function (other) {
  24547. other.position.copyFrom(this.position);
  24548. other.direction.copyFrom(this.direction);
  24549. other.color.copyFrom(this.color);
  24550. other.colorStep.copyFrom(this.colorStep);
  24551. other.lifeTime = this.lifeTime;
  24552. other.age = this.age;
  24553. other.size = this.size;
  24554. other.angle = this.angle;
  24555. other.angularSpeed = this.angularSpeed;
  24556. };
  24557. return Particle;
  24558. })();
  24559. BABYLON.Particle = Particle;
  24560. })(BABYLON || (BABYLON = {}));
  24561. var BABYLON;
  24562. (function (BABYLON) {
  24563. var randomNumber = function (min, max) {
  24564. if (min === max) {
  24565. return (min);
  24566. }
  24567. var random = Math.random();
  24568. return ((random * (max - min)) + min);
  24569. };
  24570. var ParticleSystem = (function () {
  24571. function ParticleSystem(name, capacity, scene, customEffect) {
  24572. var _this = this;
  24573. this.name = name;
  24574. // Members
  24575. this.animations = [];
  24576. this.renderingGroupId = 0;
  24577. this.emitter = null;
  24578. this.emitRate = 10;
  24579. this.manualEmitCount = -1;
  24580. this.updateSpeed = 0.01;
  24581. this.targetStopDuration = 0;
  24582. this.disposeOnStop = false;
  24583. this.minEmitPower = 1;
  24584. this.maxEmitPower = 1;
  24585. this.minLifeTime = 1;
  24586. this.maxLifeTime = 1;
  24587. this.minSize = 1;
  24588. this.maxSize = 1;
  24589. this.minAngularSpeed = 0;
  24590. this.maxAngularSpeed = 0;
  24591. this.layerMask = 0x0FFFFFFF;
  24592. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  24593. this.forceDepthWrite = false;
  24594. this.gravity = BABYLON.Vector3.Zero();
  24595. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  24596. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  24597. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  24598. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  24599. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24600. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24601. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  24602. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24603. this.particles = new Array();
  24604. this._vertexDeclaration = [3, 4, 4];
  24605. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  24606. this._stockParticles = new Array();
  24607. this._newPartsExcess = 0;
  24608. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  24609. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  24610. this._scaledDirection = BABYLON.Vector3.Zero();
  24611. this._scaledGravity = BABYLON.Vector3.Zero();
  24612. this._currentRenderId = -1;
  24613. this._started = false;
  24614. this._stopped = false;
  24615. this._actualFrame = 0;
  24616. this.id = name;
  24617. this._capacity = capacity;
  24618. this._scene = scene;
  24619. this._customEffect = customEffect;
  24620. scene.particleSystems.push(this);
  24621. // VBO
  24622. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24623. var indices = [];
  24624. var index = 0;
  24625. for (var count = 0; count < capacity; count++) {
  24626. indices.push(index);
  24627. indices.push(index + 1);
  24628. indices.push(index + 2);
  24629. indices.push(index);
  24630. indices.push(index + 2);
  24631. indices.push(index + 3);
  24632. index += 4;
  24633. }
  24634. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24635. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24636. // Default behaviors
  24637. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  24638. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  24639. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  24640. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  24641. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  24642. };
  24643. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  24644. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  24645. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  24646. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  24647. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  24648. };
  24649. this.updateFunction = function (particles) {
  24650. for (var index = 0; index < particles.length; index++) {
  24651. var particle = particles[index];
  24652. particle.age += _this._scaledUpdateSpeed;
  24653. if (particle.age >= particle.lifeTime) {
  24654. _this.recycleParticle(particle);
  24655. index--;
  24656. continue;
  24657. }
  24658. else {
  24659. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  24660. particle.color.addInPlace(_this._scaledColorStep);
  24661. if (particle.color.a < 0)
  24662. particle.color.a = 0;
  24663. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  24664. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  24665. particle.position.addInPlace(_this._scaledDirection);
  24666. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  24667. particle.direction.addInPlace(_this._scaledGravity);
  24668. }
  24669. }
  24670. };
  24671. }
  24672. ParticleSystem.prototype.recycleParticle = function (particle) {
  24673. var lastParticle = this.particles.pop();
  24674. if (lastParticle !== particle) {
  24675. lastParticle.copyTo(particle);
  24676. this._stockParticles.push(lastParticle);
  24677. }
  24678. };
  24679. ParticleSystem.prototype.getCapacity = function () {
  24680. return this._capacity;
  24681. };
  24682. ParticleSystem.prototype.isAlive = function () {
  24683. return this._alive;
  24684. };
  24685. ParticleSystem.prototype.isStarted = function () {
  24686. return this._started;
  24687. };
  24688. ParticleSystem.prototype.start = function () {
  24689. this._started = true;
  24690. this._stopped = false;
  24691. this._actualFrame = 0;
  24692. };
  24693. ParticleSystem.prototype.stop = function () {
  24694. this._stopped = true;
  24695. };
  24696. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  24697. var offset = index * 11;
  24698. this._vertices[offset] = particle.position.x;
  24699. this._vertices[offset + 1] = particle.position.y;
  24700. this._vertices[offset + 2] = particle.position.z;
  24701. this._vertices[offset + 3] = particle.color.r;
  24702. this._vertices[offset + 4] = particle.color.g;
  24703. this._vertices[offset + 5] = particle.color.b;
  24704. this._vertices[offset + 6] = particle.color.a;
  24705. this._vertices[offset + 7] = particle.angle;
  24706. this._vertices[offset + 8] = particle.size;
  24707. this._vertices[offset + 9] = offsetX;
  24708. this._vertices[offset + 10] = offsetY;
  24709. };
  24710. ParticleSystem.prototype._update = function (newParticles) {
  24711. // Update current
  24712. this._alive = this.particles.length > 0;
  24713. this.updateFunction(this.particles);
  24714. // Add new ones
  24715. var worldMatrix;
  24716. if (this.emitter.position) {
  24717. worldMatrix = this.emitter.getWorldMatrix();
  24718. }
  24719. else {
  24720. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  24721. }
  24722. var particle;
  24723. for (var index = 0; index < newParticles; index++) {
  24724. if (this.particles.length === this._capacity) {
  24725. break;
  24726. }
  24727. if (this._stockParticles.length !== 0) {
  24728. particle = this._stockParticles.pop();
  24729. particle.age = 0;
  24730. }
  24731. else {
  24732. particle = new BABYLON.Particle();
  24733. }
  24734. this.particles.push(particle);
  24735. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  24736. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  24737. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  24738. particle.size = randomNumber(this.minSize, this.maxSize);
  24739. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  24740. this.startPositionFunction(worldMatrix, particle.position, particle);
  24741. var step = randomNumber(0, 1.0);
  24742. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  24743. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  24744. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  24745. }
  24746. };
  24747. ParticleSystem.prototype._getEffect = function () {
  24748. if (this._customEffect) {
  24749. return this._customEffect;
  24750. }
  24751. ;
  24752. var defines = [];
  24753. if (this._scene.clipPlane) {
  24754. defines.push("#define CLIPPLANE");
  24755. }
  24756. // Effect
  24757. var join = defines.join("\n");
  24758. if (this._cachedDefines !== join) {
  24759. this._cachedDefines = join;
  24760. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  24761. }
  24762. return this._effect;
  24763. };
  24764. ParticleSystem.prototype.animate = function () {
  24765. if (!this._started)
  24766. return;
  24767. var effect = this._getEffect();
  24768. // Check
  24769. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  24770. return;
  24771. if (this._currentRenderId === this._scene.getRenderId()) {
  24772. return;
  24773. }
  24774. this._currentRenderId = this._scene.getRenderId();
  24775. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  24776. // determine the number of particles we need to create
  24777. var newParticles;
  24778. if (this.manualEmitCount > -1) {
  24779. newParticles = this.manualEmitCount;
  24780. this._newPartsExcess = 0;
  24781. this.manualEmitCount = 0;
  24782. }
  24783. else {
  24784. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  24785. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  24786. }
  24787. if (this._newPartsExcess > 1.0) {
  24788. newParticles += this._newPartsExcess >> 0;
  24789. this._newPartsExcess -= this._newPartsExcess >> 0;
  24790. }
  24791. this._alive = false;
  24792. if (!this._stopped) {
  24793. this._actualFrame += this._scaledUpdateSpeed;
  24794. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  24795. this.stop();
  24796. }
  24797. else {
  24798. newParticles = 0;
  24799. }
  24800. this._update(newParticles);
  24801. // Stopped?
  24802. if (this._stopped) {
  24803. if (!this._alive) {
  24804. this._started = false;
  24805. if (this.disposeOnStop) {
  24806. this._scene._toBeDisposed.push(this);
  24807. }
  24808. }
  24809. }
  24810. // Update VBO
  24811. var offset = 0;
  24812. for (var index = 0; index < this.particles.length; index++) {
  24813. var particle = this.particles[index];
  24814. this._appendParticleVertex(offset++, particle, 0, 0);
  24815. this._appendParticleVertex(offset++, particle, 1, 0);
  24816. this._appendParticleVertex(offset++, particle, 1, 1);
  24817. this._appendParticleVertex(offset++, particle, 0, 1);
  24818. }
  24819. var engine = this._scene.getEngine();
  24820. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24821. };
  24822. ParticleSystem.prototype.render = function () {
  24823. var effect = this._getEffect();
  24824. // Check
  24825. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  24826. return 0;
  24827. var engine = this._scene.getEngine();
  24828. // Render
  24829. engine.enableEffect(effect);
  24830. engine.setState(false);
  24831. var viewMatrix = this._scene.getViewMatrix();
  24832. effect.setTexture("diffuseSampler", this.particleTexture);
  24833. effect.setMatrix("view", viewMatrix);
  24834. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24835. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  24836. if (this._scene.clipPlane) {
  24837. var clipPlane = this._scene.clipPlane;
  24838. var invView = viewMatrix.clone();
  24839. invView.invert();
  24840. effect.setMatrix("invView", invView);
  24841. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24842. }
  24843. // VBOs
  24844. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24845. // Draw order
  24846. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  24847. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  24848. }
  24849. else {
  24850. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24851. }
  24852. if (this.forceDepthWrite) {
  24853. engine.setDepthWrite(true);
  24854. }
  24855. engine.draw(true, 0, this.particles.length * 6);
  24856. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24857. return this.particles.length;
  24858. };
  24859. ParticleSystem.prototype.dispose = function () {
  24860. if (this._vertexBuffer) {
  24861. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24862. this._vertexBuffer = null;
  24863. }
  24864. if (this._indexBuffer) {
  24865. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24866. this._indexBuffer = null;
  24867. }
  24868. if (this.particleTexture) {
  24869. this.particleTexture.dispose();
  24870. this.particleTexture = null;
  24871. }
  24872. // Remove from scene
  24873. var index = this._scene.particleSystems.indexOf(this);
  24874. this._scene.particleSystems.splice(index, 1);
  24875. // Callback
  24876. if (this.onDispose) {
  24877. this.onDispose();
  24878. }
  24879. };
  24880. // Clone
  24881. ParticleSystem.prototype.clone = function (name, newEmitter) {
  24882. var result = new ParticleSystem(name, this._capacity, this._scene);
  24883. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  24884. if (newEmitter === undefined) {
  24885. newEmitter = this.emitter;
  24886. }
  24887. result.emitter = newEmitter;
  24888. if (this.particleTexture) {
  24889. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  24890. }
  24891. result.start();
  24892. return result;
  24893. };
  24894. ParticleSystem.prototype.serialize = function () {
  24895. var serializationObject = {};
  24896. serializationObject.name = this.name;
  24897. serializationObject.id = this.id;
  24898. // Emitter
  24899. if (this.emitter.position) {
  24900. serializationObject.emitterId = this.emitter.id;
  24901. }
  24902. else {
  24903. serializationObject.emitter = this.emitter.asArray();
  24904. }
  24905. serializationObject.capacity = this.getCapacity();
  24906. if (this.particleTexture) {
  24907. serializationObject.textureName = this.particleTexture.name;
  24908. }
  24909. // Animations
  24910. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24911. // Particle system
  24912. serializationObject.minAngularSpeed = this.minAngularSpeed;
  24913. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  24914. serializationObject.minSize = this.minSize;
  24915. serializationObject.maxSize = this.maxSize;
  24916. serializationObject.minEmitPower = this.minEmitPower;
  24917. serializationObject.maxEmitPower = this.maxEmitPower;
  24918. serializationObject.minLifeTime = this.minLifeTime;
  24919. serializationObject.maxLifeTime = this.maxLifeTime;
  24920. serializationObject.emitRate = this.emitRate;
  24921. serializationObject.minEmitBox = this.minEmitBox.asArray();
  24922. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  24923. serializationObject.gravity = this.gravity.asArray();
  24924. serializationObject.direction1 = this.direction1.asArray();
  24925. serializationObject.direction2 = this.direction2.asArray();
  24926. serializationObject.color1 = this.color1.asArray();
  24927. serializationObject.color2 = this.color2.asArray();
  24928. serializationObject.colorDead = this.colorDead.asArray();
  24929. serializationObject.updateSpeed = this.updateSpeed;
  24930. serializationObject.targetStopDuration = this.targetStopDuration;
  24931. serializationObject.textureMask = this.textureMask.asArray();
  24932. serializationObject.blendMode = this.blendMode;
  24933. return serializationObject;
  24934. };
  24935. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  24936. var name = parsedParticleSystem.name;
  24937. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  24938. if (parsedParticleSystem.id) {
  24939. particleSystem.id = parsedParticleSystem.id;
  24940. }
  24941. // Texture
  24942. if (parsedParticleSystem.textureName) {
  24943. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  24944. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  24945. }
  24946. // Emitter
  24947. if (parsedParticleSystem.emitterId) {
  24948. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  24949. }
  24950. else {
  24951. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  24952. }
  24953. // Animations
  24954. if (parsedParticleSystem.animations) {
  24955. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  24956. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  24957. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24958. }
  24959. }
  24960. if (parsedParticleSystem.autoAnimate) {
  24961. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  24962. }
  24963. // Particle system
  24964. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  24965. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  24966. particleSystem.minSize = parsedParticleSystem.minSize;
  24967. particleSystem.maxSize = parsedParticleSystem.maxSize;
  24968. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  24969. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  24970. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  24971. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  24972. particleSystem.emitRate = parsedParticleSystem.emitRate;
  24973. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  24974. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  24975. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  24976. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  24977. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  24978. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  24979. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  24980. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  24981. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  24982. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  24983. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  24984. particleSystem.blendMode = parsedParticleSystem.blendMode;
  24985. particleSystem.start();
  24986. return particleSystem;
  24987. };
  24988. // Statics
  24989. ParticleSystem.BLENDMODE_ONEONE = 0;
  24990. ParticleSystem.BLENDMODE_STANDARD = 1;
  24991. return ParticleSystem;
  24992. })();
  24993. BABYLON.ParticleSystem = ParticleSystem;
  24994. })(BABYLON || (BABYLON = {}));
  24995. var BABYLON;
  24996. (function (BABYLON) {
  24997. var AnimationRange = (function () {
  24998. function AnimationRange(name, from, to) {
  24999. this.name = name;
  25000. this.from = from;
  25001. this.to = to;
  25002. }
  25003. AnimationRange.prototype.clone = function () {
  25004. return new AnimationRange(this.name, this.from, this.to);
  25005. };
  25006. return AnimationRange;
  25007. })();
  25008. BABYLON.AnimationRange = AnimationRange;
  25009. /**
  25010. * Composed of a frame, and an action function
  25011. */
  25012. var AnimationEvent = (function () {
  25013. function AnimationEvent(frame, action, onlyOnce) {
  25014. this.frame = frame;
  25015. this.action = action;
  25016. this.onlyOnce = onlyOnce;
  25017. this.isDone = false;
  25018. }
  25019. return AnimationEvent;
  25020. })();
  25021. BABYLON.AnimationEvent = AnimationEvent;
  25022. var PathCursor = (function () {
  25023. function PathCursor(path) {
  25024. this.path = path;
  25025. this._onchange = new Array();
  25026. this.value = 0;
  25027. this.animations = new Array();
  25028. }
  25029. PathCursor.prototype.getPoint = function () {
  25030. var point = this.path.getPointAtLengthPosition(this.value);
  25031. return new BABYLON.Vector3(point.x, 0, point.y);
  25032. };
  25033. PathCursor.prototype.moveAhead = function (step) {
  25034. if (step === void 0) { step = 0.002; }
  25035. this.move(step);
  25036. return this;
  25037. };
  25038. PathCursor.prototype.moveBack = function (step) {
  25039. if (step === void 0) { step = 0.002; }
  25040. this.move(-step);
  25041. return this;
  25042. };
  25043. PathCursor.prototype.move = function (step) {
  25044. if (Math.abs(step) > 1) {
  25045. throw "step size should be less than 1.";
  25046. }
  25047. this.value += step;
  25048. this.ensureLimits();
  25049. this.raiseOnChange();
  25050. return this;
  25051. };
  25052. PathCursor.prototype.ensureLimits = function () {
  25053. while (this.value > 1) {
  25054. this.value -= 1;
  25055. }
  25056. while (this.value < 0) {
  25057. this.value += 1;
  25058. }
  25059. return this;
  25060. };
  25061. // used by animation engine
  25062. PathCursor.prototype.markAsDirty = function (propertyName) {
  25063. this.ensureLimits();
  25064. this.raiseOnChange();
  25065. return this;
  25066. };
  25067. PathCursor.prototype.raiseOnChange = function () {
  25068. var _this = this;
  25069. this._onchange.forEach(function (f) { return f(_this); });
  25070. return this;
  25071. };
  25072. PathCursor.prototype.onchange = function (f) {
  25073. this._onchange.push(f);
  25074. return this;
  25075. };
  25076. return PathCursor;
  25077. })();
  25078. BABYLON.PathCursor = PathCursor;
  25079. var Animation = (function () {
  25080. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  25081. this.name = name;
  25082. this.targetProperty = targetProperty;
  25083. this.framePerSecond = framePerSecond;
  25084. this.dataType = dataType;
  25085. this.loopMode = loopMode;
  25086. this.enableBlending = enableBlending;
  25087. this._offsetsCache = {};
  25088. this._highLimitsCache = {};
  25089. this._stopped = false;
  25090. this._blendingFactor = 0;
  25091. // The set of event that will be linked to this animation
  25092. this._events = new Array();
  25093. this.allowMatricesInterpolation = false;
  25094. this.blendingSpeed = 0.01;
  25095. this._ranges = {};
  25096. this.targetPropertyPath = targetProperty.split(".");
  25097. this.dataType = dataType;
  25098. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  25099. }
  25100. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  25101. var dataType = undefined;
  25102. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  25103. dataType = Animation.ANIMATIONTYPE_FLOAT;
  25104. }
  25105. else if (from instanceof BABYLON.Quaternion) {
  25106. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  25107. }
  25108. else if (from instanceof BABYLON.Vector3) {
  25109. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  25110. }
  25111. else if (from instanceof BABYLON.Vector2) {
  25112. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  25113. }
  25114. else if (from instanceof BABYLON.Color3) {
  25115. dataType = Animation.ANIMATIONTYPE_COLOR3;
  25116. }
  25117. if (dataType == undefined) {
  25118. return null;
  25119. }
  25120. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  25121. var keys = [];
  25122. keys.push({ frame: 0, value: from });
  25123. keys.push({ frame: totalFrame, value: to });
  25124. animation.setKeys(keys);
  25125. if (easingFunction !== undefined) {
  25126. animation.setEasingFunction(easingFunction);
  25127. }
  25128. return animation;
  25129. };
  25130. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25131. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25132. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25133. };
  25134. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25135. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25136. node.animations.push(animation);
  25137. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25138. };
  25139. // Methods
  25140. /**
  25141. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25142. */
  25143. Animation.prototype.toString = function (fullDetails) {
  25144. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  25145. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  25146. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  25147. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  25148. if (fullDetails) {
  25149. ret += ", Ranges: {";
  25150. var first = true;
  25151. for (var name in this._ranges) {
  25152. if (!first) {
  25153. ret + ", ";
  25154. first = false;
  25155. }
  25156. ret += name;
  25157. }
  25158. ret += "}";
  25159. }
  25160. return ret;
  25161. };
  25162. /**
  25163. * Add an event to this animation.
  25164. */
  25165. Animation.prototype.addEvent = function (event) {
  25166. this._events.push(event);
  25167. };
  25168. /**
  25169. * Remove all events found at the given frame
  25170. * @param frame
  25171. */
  25172. Animation.prototype.removeEvents = function (frame) {
  25173. for (var index = 0; index < this._events.length; index++) {
  25174. if (this._events[index].frame === frame) {
  25175. this._events.splice(index, 1);
  25176. index--;
  25177. }
  25178. }
  25179. };
  25180. Animation.prototype.createRange = function (name, from, to) {
  25181. // check name not already in use; could happen for bones after serialized
  25182. if (!this._ranges[name]) {
  25183. this._ranges[name] = new AnimationRange(name, from, to);
  25184. }
  25185. };
  25186. Animation.prototype.deleteRange = function (name, deleteFrames) {
  25187. if (deleteFrames === void 0) { deleteFrames = true; }
  25188. if (this._ranges[name]) {
  25189. if (deleteFrames) {
  25190. var from = this._ranges[name].from;
  25191. var to = this._ranges[name].to;
  25192. // this loop MUST go high to low for multiple splices to work
  25193. for (var key = this._keys.length - 1; key >= 0; key--) {
  25194. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  25195. this._keys.splice(key, 1);
  25196. }
  25197. }
  25198. }
  25199. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25200. }
  25201. };
  25202. Animation.prototype.getRange = function (name) {
  25203. return this._ranges[name];
  25204. };
  25205. Animation.prototype.reset = function () {
  25206. this._offsetsCache = {};
  25207. this._highLimitsCache = {};
  25208. this.currentFrame = 0;
  25209. this._blendingFactor = 0;
  25210. this._originalBlendValue = null;
  25211. };
  25212. Animation.prototype.isStopped = function () {
  25213. return this._stopped;
  25214. };
  25215. Animation.prototype.getKeys = function () {
  25216. return this._keys;
  25217. };
  25218. Animation.prototype.getHighestFrame = function () {
  25219. var ret = 0;
  25220. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  25221. if (ret < this._keys[key].frame) {
  25222. ret = this._keys[key].frame;
  25223. }
  25224. }
  25225. return ret;
  25226. };
  25227. Animation.prototype.getEasingFunction = function () {
  25228. return this._easingFunction;
  25229. };
  25230. Animation.prototype.setEasingFunction = function (easingFunction) {
  25231. this._easingFunction = easingFunction;
  25232. };
  25233. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  25234. return startValue + (endValue - startValue) * gradient;
  25235. };
  25236. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  25237. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  25238. };
  25239. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  25240. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  25241. };
  25242. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  25243. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  25244. };
  25245. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  25246. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  25247. };
  25248. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  25249. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  25250. };
  25251. Animation.prototype.clone = function () {
  25252. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  25253. if (this._keys) {
  25254. clone.setKeys(this._keys);
  25255. }
  25256. if (this._ranges) {
  25257. clone._ranges = {};
  25258. for (var name in this._ranges) {
  25259. clone._ranges[name] = this._ranges[name].clone();
  25260. }
  25261. }
  25262. return clone;
  25263. };
  25264. Animation.prototype.setKeys = function (values) {
  25265. this._keys = values.slice(0);
  25266. this._offsetsCache = {};
  25267. this._highLimitsCache = {};
  25268. };
  25269. Animation.prototype._getKeyValue = function (value) {
  25270. if (typeof value === "function") {
  25271. return value();
  25272. }
  25273. return value;
  25274. };
  25275. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  25276. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  25277. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  25278. }
  25279. this.currentFrame = currentFrame;
  25280. // Try to get a hash to find the right key
  25281. 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));
  25282. if (this._keys[startKey].frame >= currentFrame) {
  25283. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  25284. startKey--;
  25285. }
  25286. }
  25287. for (var key = startKey; key < this._keys.length; key++) {
  25288. if (this._keys[key + 1].frame >= currentFrame) {
  25289. var startValue = this._getKeyValue(this._keys[key].value);
  25290. var endValue = this._getKeyValue(this._keys[key + 1].value);
  25291. // gradient : percent of currentFrame between the frame inf and the frame sup
  25292. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  25293. // check for easingFunction and correction of gradient
  25294. if (this._easingFunction != null) {
  25295. gradient = this._easingFunction.ease(gradient);
  25296. }
  25297. switch (this.dataType) {
  25298. // Float
  25299. case Animation.ANIMATIONTYPE_FLOAT:
  25300. switch (loopMode) {
  25301. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25302. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25303. return this.floatInterpolateFunction(startValue, endValue, gradient);
  25304. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25305. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  25306. }
  25307. break;
  25308. // Quaternion
  25309. case Animation.ANIMATIONTYPE_QUATERNION:
  25310. var quaternion = null;
  25311. switch (loopMode) {
  25312. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25313. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25314. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  25315. break;
  25316. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25317. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25318. break;
  25319. }
  25320. return quaternion;
  25321. // Vector3
  25322. case Animation.ANIMATIONTYPE_VECTOR3:
  25323. switch (loopMode) {
  25324. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25325. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25326. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  25327. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25328. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25329. }
  25330. // Vector2
  25331. case Animation.ANIMATIONTYPE_VECTOR2:
  25332. switch (loopMode) {
  25333. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25334. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25335. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  25336. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25337. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25338. }
  25339. // Color3
  25340. case Animation.ANIMATIONTYPE_COLOR3:
  25341. switch (loopMode) {
  25342. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25343. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25344. return this.color3InterpolateFunction(startValue, endValue, gradient);
  25345. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25346. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25347. }
  25348. // Matrix
  25349. case Animation.ANIMATIONTYPE_MATRIX:
  25350. switch (loopMode) {
  25351. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25352. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25353. if (this.allowMatricesInterpolation) {
  25354. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  25355. }
  25356. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25357. return startValue;
  25358. }
  25359. default:
  25360. break;
  25361. }
  25362. break;
  25363. }
  25364. }
  25365. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  25366. };
  25367. Animation.prototype.setValue = function (currentValue, blend) {
  25368. if (blend === void 0) { blend = false; }
  25369. // Set value
  25370. var path;
  25371. var destination;
  25372. if (this.targetPropertyPath.length > 1) {
  25373. var property = this._target[this.targetPropertyPath[0]];
  25374. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  25375. property = property[this.targetPropertyPath[index]];
  25376. }
  25377. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  25378. destination = property;
  25379. }
  25380. else {
  25381. path = this.targetPropertyPath[0];
  25382. destination = this._target;
  25383. }
  25384. // Blending
  25385. if (this.enableBlending && this._blendingFactor <= 1.0) {
  25386. if (!this._originalBlendValue) {
  25387. this._originalBlendValue = destination[path];
  25388. }
  25389. if (this._originalBlendValue.prototype) {
  25390. if (this._originalBlendValue.prototype.Lerp) {
  25391. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  25392. }
  25393. else {
  25394. destination[path] = currentValue;
  25395. }
  25396. }
  25397. else {
  25398. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  25399. }
  25400. this._blendingFactor += this.blendingSpeed;
  25401. }
  25402. else {
  25403. destination[path] = currentValue;
  25404. }
  25405. if (this._target.markAsDirty) {
  25406. this._target.markAsDirty(this.targetProperty);
  25407. }
  25408. };
  25409. Animation.prototype.goToFrame = function (frame) {
  25410. if (frame < this._keys[0].frame) {
  25411. frame = this._keys[0].frame;
  25412. }
  25413. else if (frame > this._keys[this._keys.length - 1].frame) {
  25414. frame = this._keys[this._keys.length - 1].frame;
  25415. }
  25416. var currentValue = this._interpolate(frame, 0, this.loopMode);
  25417. this.setValue(currentValue);
  25418. };
  25419. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  25420. if (blend === void 0) { blend = false; }
  25421. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  25422. this._stopped = true;
  25423. return false;
  25424. }
  25425. var returnValue = true;
  25426. // Adding a start key at frame 0 if missing
  25427. if (this._keys[0].frame !== 0) {
  25428. var newKey = { frame: 0, value: this._keys[0].value };
  25429. this._keys.splice(0, 0, newKey);
  25430. }
  25431. // Check limits
  25432. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  25433. from = this._keys[0].frame;
  25434. }
  25435. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  25436. to = this._keys[this._keys.length - 1].frame;
  25437. }
  25438. // Compute ratio
  25439. var range = to - from;
  25440. var offsetValue;
  25441. // ratio represents the frame delta between from and to
  25442. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  25443. var highLimitValue = 0;
  25444. if (ratio > range && !loop) {
  25445. returnValue = false;
  25446. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  25447. }
  25448. else {
  25449. // Get max value if required
  25450. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  25451. var keyOffset = to.toString() + from.toString();
  25452. if (!this._offsetsCache[keyOffset]) {
  25453. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25454. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25455. switch (this.dataType) {
  25456. // Float
  25457. case Animation.ANIMATIONTYPE_FLOAT:
  25458. this._offsetsCache[keyOffset] = toValue - fromValue;
  25459. break;
  25460. // Quaternion
  25461. case Animation.ANIMATIONTYPE_QUATERNION:
  25462. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25463. break;
  25464. // Vector3
  25465. case Animation.ANIMATIONTYPE_VECTOR3:
  25466. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25467. // Vector2
  25468. case Animation.ANIMATIONTYPE_VECTOR2:
  25469. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25470. // Color3
  25471. case Animation.ANIMATIONTYPE_COLOR3:
  25472. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25473. default:
  25474. break;
  25475. }
  25476. this._highLimitsCache[keyOffset] = toValue;
  25477. }
  25478. highLimitValue = this._highLimitsCache[keyOffset];
  25479. offsetValue = this._offsetsCache[keyOffset];
  25480. }
  25481. }
  25482. if (offsetValue === undefined) {
  25483. switch (this.dataType) {
  25484. // Float
  25485. case Animation.ANIMATIONTYPE_FLOAT:
  25486. offsetValue = 0;
  25487. break;
  25488. // Quaternion
  25489. case Animation.ANIMATIONTYPE_QUATERNION:
  25490. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  25491. break;
  25492. // Vector3
  25493. case Animation.ANIMATIONTYPE_VECTOR3:
  25494. offsetValue = BABYLON.Vector3.Zero();
  25495. break;
  25496. // Vector2
  25497. case Animation.ANIMATIONTYPE_VECTOR2:
  25498. offsetValue = BABYLON.Vector2.Zero();
  25499. break;
  25500. // Color3
  25501. case Animation.ANIMATIONTYPE_COLOR3:
  25502. offsetValue = BABYLON.Color3.Black();
  25503. }
  25504. }
  25505. // Compute value
  25506. var repeatCount = (ratio / range) >> 0;
  25507. var currentFrame = returnValue ? from + ratio % range : to;
  25508. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  25509. // Set value
  25510. this.setValue(currentValue);
  25511. // Check events
  25512. for (var index = 0; index < this._events.length; index++) {
  25513. if (currentFrame >= this._events[index].frame) {
  25514. var event = this._events[index];
  25515. if (!event.isDone) {
  25516. // If event should be done only once, remove it.
  25517. if (event.onlyOnce) {
  25518. this._events.splice(index, 1);
  25519. index--;
  25520. }
  25521. event.isDone = true;
  25522. event.action();
  25523. } // Don't do anything if the event has already be done.
  25524. }
  25525. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  25526. // reset event, the animation is looping
  25527. this._events[index].isDone = false;
  25528. }
  25529. }
  25530. if (!returnValue) {
  25531. this._stopped = true;
  25532. }
  25533. return returnValue;
  25534. };
  25535. Animation.prototype.serialize = function () {
  25536. var serializationObject = {};
  25537. serializationObject.name = this.name;
  25538. serializationObject.property = this.targetProperty;
  25539. serializationObject.framePerSecond = this.framePerSecond;
  25540. serializationObject.dataType = this.dataType;
  25541. serializationObject.loopBehavior = this.loopMode;
  25542. var dataType = this.dataType;
  25543. serializationObject.keys = [];
  25544. var keys = this.getKeys();
  25545. for (var index = 0; index < keys.length; index++) {
  25546. var animationKey = keys[index];
  25547. var key = {};
  25548. key.frame = animationKey.frame;
  25549. switch (dataType) {
  25550. case Animation.ANIMATIONTYPE_FLOAT:
  25551. key.values = [animationKey.value];
  25552. break;
  25553. case Animation.ANIMATIONTYPE_QUATERNION:
  25554. case Animation.ANIMATIONTYPE_MATRIX:
  25555. case Animation.ANIMATIONTYPE_VECTOR3:
  25556. case Animation.ANIMATIONTYPE_COLOR3:
  25557. key.values = animationKey.value.asArray();
  25558. break;
  25559. }
  25560. serializationObject.keys.push(key);
  25561. }
  25562. serializationObject.ranges = [];
  25563. for (var name in this._ranges) {
  25564. var range = {};
  25565. range.name = name;
  25566. range.from = this._ranges[name].from;
  25567. range.to = this._ranges[name].to;
  25568. serializationObject.ranges.push(range);
  25569. }
  25570. return serializationObject;
  25571. };
  25572. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  25573. get: function () {
  25574. return Animation._ANIMATIONTYPE_FLOAT;
  25575. },
  25576. enumerable: true,
  25577. configurable: true
  25578. });
  25579. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  25580. get: function () {
  25581. return Animation._ANIMATIONTYPE_VECTOR3;
  25582. },
  25583. enumerable: true,
  25584. configurable: true
  25585. });
  25586. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  25587. get: function () {
  25588. return Animation._ANIMATIONTYPE_VECTOR2;
  25589. },
  25590. enumerable: true,
  25591. configurable: true
  25592. });
  25593. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  25594. get: function () {
  25595. return Animation._ANIMATIONTYPE_QUATERNION;
  25596. },
  25597. enumerable: true,
  25598. configurable: true
  25599. });
  25600. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  25601. get: function () {
  25602. return Animation._ANIMATIONTYPE_MATRIX;
  25603. },
  25604. enumerable: true,
  25605. configurable: true
  25606. });
  25607. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  25608. get: function () {
  25609. return Animation._ANIMATIONTYPE_COLOR3;
  25610. },
  25611. enumerable: true,
  25612. configurable: true
  25613. });
  25614. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  25615. get: function () {
  25616. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  25617. },
  25618. enumerable: true,
  25619. configurable: true
  25620. });
  25621. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  25622. get: function () {
  25623. return Animation._ANIMATIONLOOPMODE_CYCLE;
  25624. },
  25625. enumerable: true,
  25626. configurable: true
  25627. });
  25628. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  25629. get: function () {
  25630. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  25631. },
  25632. enumerable: true,
  25633. configurable: true
  25634. });
  25635. Animation.Parse = function (parsedAnimation) {
  25636. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  25637. var dataType = parsedAnimation.dataType;
  25638. var keys = [];
  25639. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  25640. var key = parsedAnimation.keys[index];
  25641. var data;
  25642. switch (dataType) {
  25643. case Animation.ANIMATIONTYPE_FLOAT:
  25644. data = key.values[0];
  25645. break;
  25646. case Animation.ANIMATIONTYPE_QUATERNION:
  25647. data = BABYLON.Quaternion.FromArray(key.values);
  25648. break;
  25649. case Animation.ANIMATIONTYPE_MATRIX:
  25650. data = BABYLON.Matrix.FromArray(key.values);
  25651. break;
  25652. case Animation.ANIMATIONTYPE_COLOR3:
  25653. data = BABYLON.Color3.FromArray(key.values);
  25654. break;
  25655. case Animation.ANIMATIONTYPE_VECTOR3:
  25656. default:
  25657. data = BABYLON.Vector3.FromArray(key.values);
  25658. break;
  25659. }
  25660. keys.push({
  25661. frame: key.frame,
  25662. value: data
  25663. });
  25664. }
  25665. animation.setKeys(keys);
  25666. if (parsedAnimation.ranges) {
  25667. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  25668. data = parsedAnimation.ranges[index];
  25669. animation.createRange(data.name, data.from, data.to);
  25670. }
  25671. }
  25672. return animation;
  25673. };
  25674. Animation.AppendSerializedAnimations = function (source, destination) {
  25675. if (source.animations) {
  25676. destination.animations = [];
  25677. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  25678. var animation = source.animations[animationIndex];
  25679. destination.animations.push(animation.serialize());
  25680. }
  25681. }
  25682. };
  25683. // Statics
  25684. Animation._ANIMATIONTYPE_FLOAT = 0;
  25685. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  25686. Animation._ANIMATIONTYPE_QUATERNION = 2;
  25687. Animation._ANIMATIONTYPE_MATRIX = 3;
  25688. Animation._ANIMATIONTYPE_COLOR3 = 4;
  25689. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  25690. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  25691. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  25692. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  25693. return Animation;
  25694. })();
  25695. BABYLON.Animation = Animation;
  25696. })(BABYLON || (BABYLON = {}));
  25697. var BABYLON;
  25698. (function (BABYLON) {
  25699. var Animatable = (function () {
  25700. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  25701. if (fromFrame === void 0) { fromFrame = 0; }
  25702. if (toFrame === void 0) { toFrame = 100; }
  25703. if (loopAnimation === void 0) { loopAnimation = false; }
  25704. if (speedRatio === void 0) { speedRatio = 1.0; }
  25705. this.target = target;
  25706. this.fromFrame = fromFrame;
  25707. this.toFrame = toFrame;
  25708. this.loopAnimation = loopAnimation;
  25709. this.speedRatio = speedRatio;
  25710. this.onAnimationEnd = onAnimationEnd;
  25711. this._animations = new Array();
  25712. this._paused = false;
  25713. this.animationStarted = false;
  25714. if (animations) {
  25715. this.appendAnimations(target, animations);
  25716. }
  25717. this._scene = scene;
  25718. scene._activeAnimatables.push(this);
  25719. }
  25720. // Methods
  25721. Animatable.prototype.getAnimations = function () {
  25722. return this._animations;
  25723. };
  25724. Animatable.prototype.appendAnimations = function (target, animations) {
  25725. for (var index = 0; index < animations.length; index++) {
  25726. var animation = animations[index];
  25727. animation._target = target;
  25728. this._animations.push(animation);
  25729. }
  25730. };
  25731. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  25732. var animations = this._animations;
  25733. for (var index = 0; index < animations.length; index++) {
  25734. if (animations[index].targetProperty === property) {
  25735. return animations[index];
  25736. }
  25737. }
  25738. return null;
  25739. };
  25740. Animatable.prototype.reset = function () {
  25741. var animations = this._animations;
  25742. for (var index = 0; index < animations.length; index++) {
  25743. animations[index].reset();
  25744. }
  25745. this._localDelayOffset = null;
  25746. this._pausedDelay = null;
  25747. };
  25748. Animatable.prototype.enableBlending = function (blendingSpeed) {
  25749. var animations = this._animations;
  25750. for (var index = 0; index < animations.length; index++) {
  25751. animations[index].enableBlending = true;
  25752. animations[index].blendingSpeed = blendingSpeed;
  25753. }
  25754. };
  25755. Animatable.prototype.disableBlending = function () {
  25756. var animations = this._animations;
  25757. for (var index = 0; index < animations.length; index++) {
  25758. animations[index].enableBlending = false;
  25759. }
  25760. };
  25761. Animatable.prototype.goToFrame = function (frame) {
  25762. var animations = this._animations;
  25763. for (var index = 0; index < animations.length; index++) {
  25764. animations[index].goToFrame(frame);
  25765. }
  25766. };
  25767. Animatable.prototype.pause = function () {
  25768. if (this._paused) {
  25769. return;
  25770. }
  25771. this._paused = true;
  25772. };
  25773. Animatable.prototype.restart = function () {
  25774. this._paused = false;
  25775. };
  25776. Animatable.prototype.stop = function () {
  25777. var index = this._scene._activeAnimatables.indexOf(this);
  25778. if (index > -1) {
  25779. this._scene._activeAnimatables.splice(index, 1);
  25780. var animations = this._animations;
  25781. for (var index = 0; index < animations.length; index++) {
  25782. animations[index].reset();
  25783. }
  25784. if (this.onAnimationEnd) {
  25785. this.onAnimationEnd();
  25786. }
  25787. }
  25788. };
  25789. Animatable.prototype._animate = function (delay) {
  25790. if (this._paused) {
  25791. this.animationStarted = false;
  25792. if (!this._pausedDelay) {
  25793. this._pausedDelay = delay;
  25794. }
  25795. return true;
  25796. }
  25797. if (!this._localDelayOffset) {
  25798. this._localDelayOffset = delay;
  25799. }
  25800. else if (this._pausedDelay) {
  25801. this._localDelayOffset += delay - this._pausedDelay;
  25802. this._pausedDelay = null;
  25803. }
  25804. // Animating
  25805. var running = false;
  25806. var animations = this._animations;
  25807. var index;
  25808. for (index = 0; index < animations.length; index++) {
  25809. var animation = animations[index];
  25810. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  25811. running = running || isRunning;
  25812. }
  25813. this.animationStarted = running;
  25814. if (!running) {
  25815. // Remove from active animatables
  25816. index = this._scene._activeAnimatables.indexOf(this);
  25817. this._scene._activeAnimatables.splice(index, 1);
  25818. }
  25819. if (!running && this.onAnimationEnd) {
  25820. this.onAnimationEnd();
  25821. this.onAnimationEnd = null;
  25822. }
  25823. return running;
  25824. };
  25825. return Animatable;
  25826. })();
  25827. BABYLON.Animatable = Animatable;
  25828. })(BABYLON || (BABYLON = {}));
  25829. var BABYLON;
  25830. (function (BABYLON) {
  25831. var EasingFunction = (function () {
  25832. function EasingFunction() {
  25833. // Properties
  25834. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  25835. }
  25836. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  25837. get: function () {
  25838. return EasingFunction._EASINGMODE_EASEIN;
  25839. },
  25840. enumerable: true,
  25841. configurable: true
  25842. });
  25843. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  25844. get: function () {
  25845. return EasingFunction._EASINGMODE_EASEOUT;
  25846. },
  25847. enumerable: true,
  25848. configurable: true
  25849. });
  25850. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  25851. get: function () {
  25852. return EasingFunction._EASINGMODE_EASEINOUT;
  25853. },
  25854. enumerable: true,
  25855. configurable: true
  25856. });
  25857. EasingFunction.prototype.setEasingMode = function (easingMode) {
  25858. var n = Math.min(Math.max(easingMode, 0), 2);
  25859. this._easingMode = n;
  25860. };
  25861. EasingFunction.prototype.getEasingMode = function () {
  25862. return this._easingMode;
  25863. };
  25864. EasingFunction.prototype.easeInCore = function (gradient) {
  25865. throw new Error('You must implement this method');
  25866. };
  25867. EasingFunction.prototype.ease = function (gradient) {
  25868. switch (this._easingMode) {
  25869. case EasingFunction.EASINGMODE_EASEIN:
  25870. return this.easeInCore(gradient);
  25871. case EasingFunction.EASINGMODE_EASEOUT:
  25872. return (1 - this.easeInCore(1 - gradient));
  25873. }
  25874. if (gradient >= 0.5) {
  25875. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  25876. }
  25877. return (this.easeInCore(gradient * 2) * 0.5);
  25878. };
  25879. //Statics
  25880. EasingFunction._EASINGMODE_EASEIN = 0;
  25881. EasingFunction._EASINGMODE_EASEOUT = 1;
  25882. EasingFunction._EASINGMODE_EASEINOUT = 2;
  25883. return EasingFunction;
  25884. })();
  25885. BABYLON.EasingFunction = EasingFunction;
  25886. var CircleEase = (function (_super) {
  25887. __extends(CircleEase, _super);
  25888. function CircleEase() {
  25889. _super.apply(this, arguments);
  25890. }
  25891. CircleEase.prototype.easeInCore = function (gradient) {
  25892. gradient = Math.max(0, Math.min(1, gradient));
  25893. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  25894. };
  25895. return CircleEase;
  25896. })(EasingFunction);
  25897. BABYLON.CircleEase = CircleEase;
  25898. var BackEase = (function (_super) {
  25899. __extends(BackEase, _super);
  25900. function BackEase(amplitude) {
  25901. if (amplitude === void 0) { amplitude = 1; }
  25902. _super.call(this);
  25903. this.amplitude = amplitude;
  25904. }
  25905. BackEase.prototype.easeInCore = function (gradient) {
  25906. var num = Math.max(0, this.amplitude);
  25907. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  25908. };
  25909. return BackEase;
  25910. })(EasingFunction);
  25911. BABYLON.BackEase = BackEase;
  25912. var BounceEase = (function (_super) {
  25913. __extends(BounceEase, _super);
  25914. function BounceEase(bounces, bounciness) {
  25915. if (bounces === void 0) { bounces = 3; }
  25916. if (bounciness === void 0) { bounciness = 2; }
  25917. _super.call(this);
  25918. this.bounces = bounces;
  25919. this.bounciness = bounciness;
  25920. }
  25921. BounceEase.prototype.easeInCore = function (gradient) {
  25922. var y = Math.max(0.0, this.bounces);
  25923. var bounciness = this.bounciness;
  25924. if (bounciness <= 1.0) {
  25925. bounciness = 1.001;
  25926. }
  25927. var num9 = Math.pow(bounciness, y);
  25928. var num5 = 1.0 - bounciness;
  25929. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  25930. var num15 = gradient * num4;
  25931. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  25932. var num3 = Math.floor(num65);
  25933. var num13 = num3 + 1.0;
  25934. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  25935. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  25936. var num7 = (num8 + num12) * 0.5;
  25937. var num6 = gradient - num7;
  25938. var num2 = num7 - num8;
  25939. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  25940. };
  25941. return BounceEase;
  25942. })(EasingFunction);
  25943. BABYLON.BounceEase = BounceEase;
  25944. var CubicEase = (function (_super) {
  25945. __extends(CubicEase, _super);
  25946. function CubicEase() {
  25947. _super.apply(this, arguments);
  25948. }
  25949. CubicEase.prototype.easeInCore = function (gradient) {
  25950. return (gradient * gradient * gradient);
  25951. };
  25952. return CubicEase;
  25953. })(EasingFunction);
  25954. BABYLON.CubicEase = CubicEase;
  25955. var ElasticEase = (function (_super) {
  25956. __extends(ElasticEase, _super);
  25957. function ElasticEase(oscillations, springiness) {
  25958. if (oscillations === void 0) { oscillations = 3; }
  25959. if (springiness === void 0) { springiness = 3; }
  25960. _super.call(this);
  25961. this.oscillations = oscillations;
  25962. this.springiness = springiness;
  25963. }
  25964. ElasticEase.prototype.easeInCore = function (gradient) {
  25965. var num2;
  25966. var num3 = Math.max(0.0, this.oscillations);
  25967. var num = Math.max(0.0, this.springiness);
  25968. if (num == 0) {
  25969. num2 = gradient;
  25970. }
  25971. else {
  25972. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  25973. }
  25974. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  25975. };
  25976. return ElasticEase;
  25977. })(EasingFunction);
  25978. BABYLON.ElasticEase = ElasticEase;
  25979. var ExponentialEase = (function (_super) {
  25980. __extends(ExponentialEase, _super);
  25981. function ExponentialEase(exponent) {
  25982. if (exponent === void 0) { exponent = 2; }
  25983. _super.call(this);
  25984. this.exponent = exponent;
  25985. }
  25986. ExponentialEase.prototype.easeInCore = function (gradient) {
  25987. if (this.exponent <= 0) {
  25988. return gradient;
  25989. }
  25990. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  25991. };
  25992. return ExponentialEase;
  25993. })(EasingFunction);
  25994. BABYLON.ExponentialEase = ExponentialEase;
  25995. var PowerEase = (function (_super) {
  25996. __extends(PowerEase, _super);
  25997. function PowerEase(power) {
  25998. if (power === void 0) { power = 2; }
  25999. _super.call(this);
  26000. this.power = power;
  26001. }
  26002. PowerEase.prototype.easeInCore = function (gradient) {
  26003. var y = Math.max(0.0, this.power);
  26004. return Math.pow(gradient, y);
  26005. };
  26006. return PowerEase;
  26007. })(EasingFunction);
  26008. BABYLON.PowerEase = PowerEase;
  26009. var QuadraticEase = (function (_super) {
  26010. __extends(QuadraticEase, _super);
  26011. function QuadraticEase() {
  26012. _super.apply(this, arguments);
  26013. }
  26014. QuadraticEase.prototype.easeInCore = function (gradient) {
  26015. return (gradient * gradient);
  26016. };
  26017. return QuadraticEase;
  26018. })(EasingFunction);
  26019. BABYLON.QuadraticEase = QuadraticEase;
  26020. var QuarticEase = (function (_super) {
  26021. __extends(QuarticEase, _super);
  26022. function QuarticEase() {
  26023. _super.apply(this, arguments);
  26024. }
  26025. QuarticEase.prototype.easeInCore = function (gradient) {
  26026. return (gradient * gradient * gradient * gradient);
  26027. };
  26028. return QuarticEase;
  26029. })(EasingFunction);
  26030. BABYLON.QuarticEase = QuarticEase;
  26031. var QuinticEase = (function (_super) {
  26032. __extends(QuinticEase, _super);
  26033. function QuinticEase() {
  26034. _super.apply(this, arguments);
  26035. }
  26036. QuinticEase.prototype.easeInCore = function (gradient) {
  26037. return (gradient * gradient * gradient * gradient * gradient);
  26038. };
  26039. return QuinticEase;
  26040. })(EasingFunction);
  26041. BABYLON.QuinticEase = QuinticEase;
  26042. var SineEase = (function (_super) {
  26043. __extends(SineEase, _super);
  26044. function SineEase() {
  26045. _super.apply(this, arguments);
  26046. }
  26047. SineEase.prototype.easeInCore = function (gradient) {
  26048. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  26049. };
  26050. return SineEase;
  26051. })(EasingFunction);
  26052. BABYLON.SineEase = SineEase;
  26053. var BezierCurveEase = (function (_super) {
  26054. __extends(BezierCurveEase, _super);
  26055. function BezierCurveEase(x1, y1, x2, y2) {
  26056. if (x1 === void 0) { x1 = 0; }
  26057. if (y1 === void 0) { y1 = 0; }
  26058. if (x2 === void 0) { x2 = 1; }
  26059. if (y2 === void 0) { y2 = 1; }
  26060. _super.call(this);
  26061. this.x1 = x1;
  26062. this.y1 = y1;
  26063. this.x2 = x2;
  26064. this.y2 = y2;
  26065. }
  26066. BezierCurveEase.prototype.easeInCore = function (gradient) {
  26067. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  26068. };
  26069. return BezierCurveEase;
  26070. })(EasingFunction);
  26071. BABYLON.BezierCurveEase = BezierCurveEase;
  26072. })(BABYLON || (BABYLON = {}));
  26073. var BABYLON;
  26074. (function (BABYLON) {
  26075. var Bone = (function (_super) {
  26076. __extends(Bone, _super);
  26077. function Bone(name, skeleton, parentBone, matrix, restPose) {
  26078. _super.call(this, name, skeleton.getScene());
  26079. this.name = name;
  26080. this.children = new Array();
  26081. this.animations = new Array();
  26082. this._worldTransform = new BABYLON.Matrix();
  26083. this._absoluteTransform = new BABYLON.Matrix();
  26084. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  26085. this._skeleton = skeleton;
  26086. this._matrix = matrix;
  26087. this._baseMatrix = matrix;
  26088. this._restPose = restPose ? restPose : matrix.clone();
  26089. skeleton.bones.push(this);
  26090. if (parentBone) {
  26091. this._parent = parentBone;
  26092. parentBone.children.push(this);
  26093. }
  26094. else {
  26095. this._parent = null;
  26096. }
  26097. this._updateDifferenceMatrix();
  26098. }
  26099. // Members
  26100. Bone.prototype.getParent = function () {
  26101. return this._parent;
  26102. };
  26103. Bone.prototype.getLocalMatrix = function () {
  26104. return this._matrix;
  26105. };
  26106. Bone.prototype.getBaseMatrix = function () {
  26107. return this._baseMatrix;
  26108. };
  26109. Bone.prototype.getRestPose = function () {
  26110. return this._restPose;
  26111. };
  26112. Bone.prototype.returnToRest = function () {
  26113. this.updateMatrix(this._restPose.clone());
  26114. };
  26115. Bone.prototype.getWorldMatrix = function () {
  26116. return this._worldTransform;
  26117. };
  26118. Bone.prototype.getInvertedAbsoluteTransform = function () {
  26119. return this._invertedAbsoluteTransform;
  26120. };
  26121. Bone.prototype.getAbsoluteTransform = function () {
  26122. return this._absoluteTransform;
  26123. };
  26124. // Methods
  26125. Bone.prototype.updateMatrix = function (matrix) {
  26126. this._baseMatrix = matrix.clone();
  26127. this._matrix = matrix.clone();
  26128. this._skeleton._markAsDirty();
  26129. this._updateDifferenceMatrix();
  26130. };
  26131. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  26132. if (!rootMatrix) {
  26133. rootMatrix = this._baseMatrix;
  26134. }
  26135. if (this._parent) {
  26136. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  26137. }
  26138. else {
  26139. this._absoluteTransform.copyFrom(rootMatrix);
  26140. }
  26141. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  26142. for (var index = 0; index < this.children.length; index++) {
  26143. this.children[index]._updateDifferenceMatrix();
  26144. }
  26145. };
  26146. Bone.prototype.markAsDirty = function () {
  26147. this._currentRenderId++;
  26148. this._skeleton._markAsDirty();
  26149. };
  26150. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  26151. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26152. // all animation may be coming from a library skeleton, so may need to create animation
  26153. if (this.animations.length === 0) {
  26154. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  26155. this.animations[0].setKeys([]);
  26156. }
  26157. // get animation info / verify there is such a range from the source bone
  26158. var sourceRange = source.animations[0].getRange(rangeName);
  26159. if (!sourceRange) {
  26160. return false;
  26161. }
  26162. var from = sourceRange.from;
  26163. var to = sourceRange.to;
  26164. var sourceKeys = source.animations[0].getKeys();
  26165. // rescaling prep
  26166. var sourceBoneLength = source.length;
  26167. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  26168. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  26169. var destKeys = this.animations[0].getKeys();
  26170. // loop vars declaration / initialization
  26171. var orig;
  26172. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26173. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  26174. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26175. var mat;
  26176. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  26177. orig = sourceKeys[key];
  26178. if (orig.frame >= from && orig.frame <= to) {
  26179. if (scalingReqd) {
  26180. orig.value.decompose(origScale, origRotation, origTranslation);
  26181. origTranslation.scaleInPlace(ratio);
  26182. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  26183. }
  26184. else {
  26185. mat = orig.value;
  26186. }
  26187. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  26188. }
  26189. }
  26190. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  26191. return true;
  26192. };
  26193. return Bone;
  26194. })(BABYLON.Node);
  26195. BABYLON.Bone = Bone;
  26196. })(BABYLON || (BABYLON = {}));
  26197. var BABYLON;
  26198. (function (BABYLON) {
  26199. var Skeleton = (function () {
  26200. function Skeleton(name, id, scene) {
  26201. this.name = name;
  26202. this.id = id;
  26203. this.bones = new Array();
  26204. this.needInitialSkinMatrix = false;
  26205. this._isDirty = true;
  26206. this._meshesWithPoseMatrix = new Array();
  26207. this._identity = BABYLON.Matrix.Identity();
  26208. this._ranges = {};
  26209. this.bones = [];
  26210. this._scene = scene;
  26211. scene.skeletons.push(this);
  26212. //make sure it will recalculate the matrix next time prepare is called.
  26213. this._isDirty = true;
  26214. }
  26215. // Members
  26216. Skeleton.prototype.getTransformMatrices = function (mesh) {
  26217. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  26218. return mesh._bonesTransformMatrices;
  26219. }
  26220. return this._transformMatrices;
  26221. };
  26222. Skeleton.prototype.getScene = function () {
  26223. return this._scene;
  26224. };
  26225. // Methods
  26226. /**
  26227. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26228. */
  26229. Skeleton.prototype.toString = function (fullDetails) {
  26230. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  26231. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26232. if (fullDetails) {
  26233. ret += ", Ranges: {";
  26234. var first = true;
  26235. for (var name in this._ranges) {
  26236. if (!first) {
  26237. ret + ", ";
  26238. first = false;
  26239. }
  26240. ret += name;
  26241. }
  26242. ret += "}";
  26243. }
  26244. return ret;
  26245. };
  26246. /**
  26247. * Get bone's index searching by name
  26248. * @param {string} name is bone's name to search for
  26249. * @return {number} Indice of the bone. Returns -1 if not found
  26250. */
  26251. Skeleton.prototype.getBoneIndexByName = function (name) {
  26252. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  26253. if (this.bones[boneIndex].name === name) {
  26254. return boneIndex;
  26255. }
  26256. }
  26257. return -1;
  26258. };
  26259. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  26260. // check name not already in use
  26261. if (!this._ranges[name]) {
  26262. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  26263. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26264. if (this.bones[i].animations[0]) {
  26265. this.bones[i].animations[0].createRange(name, from, to);
  26266. }
  26267. }
  26268. }
  26269. };
  26270. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  26271. if (deleteFrames === void 0) { deleteFrames = true; }
  26272. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26273. if (this.bones[i].animations[0]) {
  26274. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  26275. }
  26276. }
  26277. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26278. };
  26279. Skeleton.prototype.getAnimationRange = function (name) {
  26280. return this._ranges[name];
  26281. };
  26282. /**
  26283. * Returns as an Array, all AnimationRanges defined on this skeleton
  26284. */
  26285. Skeleton.prototype.getAnimationRanges = function () {
  26286. var animationRanges = [];
  26287. var name;
  26288. var i = 0;
  26289. for (name in this._ranges) {
  26290. animationRanges[i] = this._ranges[name];
  26291. i++;
  26292. }
  26293. return animationRanges;
  26294. };
  26295. /**
  26296. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  26297. */
  26298. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  26299. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26300. if (this._ranges[name] || !source.getAnimationRange(name)) {
  26301. return false;
  26302. }
  26303. var ret = true;
  26304. var frameOffset = this._getHighestAnimationFrame() + 1;
  26305. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  26306. var boneDict = {};
  26307. var sourceBones = source.bones;
  26308. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  26309. boneDict[sourceBones[i].name] = sourceBones[i];
  26310. }
  26311. if (this.bones.length !== sourceBones.length) {
  26312. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  26313. ret = false;
  26314. }
  26315. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26316. var boneName = this.bones[i].name;
  26317. var sourceBone = boneDict[boneName];
  26318. if (sourceBone) {
  26319. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  26320. }
  26321. else {
  26322. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  26323. ret = false;
  26324. }
  26325. }
  26326. // do not call createAnimationRange(), since it also is done to bones, which was already done
  26327. var range = source.getAnimationRange(name);
  26328. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  26329. return ret;
  26330. };
  26331. Skeleton.prototype.returnToRest = function () {
  26332. for (var index = 0; index < this.bones.length; index++) {
  26333. this.bones[index].returnToRest();
  26334. }
  26335. };
  26336. Skeleton.prototype._getHighestAnimationFrame = function () {
  26337. var ret = 0;
  26338. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26339. if (this.bones[i].animations[0]) {
  26340. var highest = this.bones[i].animations[0].getHighestFrame();
  26341. if (ret < highest) {
  26342. ret = highest;
  26343. }
  26344. }
  26345. }
  26346. return ret;
  26347. };
  26348. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  26349. var range = this.getAnimationRange(name);
  26350. if (!range) {
  26351. return null;
  26352. }
  26353. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  26354. };
  26355. Skeleton.prototype._markAsDirty = function () {
  26356. this._isDirty = true;
  26357. };
  26358. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  26359. this._meshesWithPoseMatrix.push(mesh);
  26360. };
  26361. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  26362. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  26363. if (index > -1) {
  26364. this._meshesWithPoseMatrix.splice(index, 1);
  26365. }
  26366. };
  26367. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  26368. for (var index = 0; index < this.bones.length; index++) {
  26369. var bone = this.bones[index];
  26370. var parentBone = bone.getParent();
  26371. if (parentBone) {
  26372. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  26373. }
  26374. else {
  26375. if (initialSkinMatrix) {
  26376. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  26377. }
  26378. else {
  26379. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  26380. }
  26381. }
  26382. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  26383. }
  26384. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  26385. };
  26386. Skeleton.prototype.prepare = function () {
  26387. if (!this._isDirty) {
  26388. return;
  26389. }
  26390. if (this.needInitialSkinMatrix) {
  26391. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  26392. var mesh = this._meshesWithPoseMatrix[index];
  26393. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  26394. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26395. }
  26396. var poseMatrix = mesh.getPoseMatrix();
  26397. // Prepare bones
  26398. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  26399. var bone = this.bones[boneIndex];
  26400. if (!bone.getParent()) {
  26401. var matrix = bone.getBaseMatrix();
  26402. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  26403. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  26404. }
  26405. }
  26406. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  26407. }
  26408. }
  26409. else {
  26410. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  26411. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26412. }
  26413. this._computeTransformMatrices(this._transformMatrices, null);
  26414. }
  26415. this._isDirty = false;
  26416. this._scene._activeBones += this.bones.length;
  26417. };
  26418. Skeleton.prototype.getAnimatables = function () {
  26419. if (!this._animatables || this._animatables.length !== this.bones.length) {
  26420. this._animatables = [];
  26421. for (var index = 0; index < this.bones.length; index++) {
  26422. this._animatables.push(this.bones[index]);
  26423. }
  26424. }
  26425. return this._animatables;
  26426. };
  26427. Skeleton.prototype.clone = function (name, id) {
  26428. var result = new Skeleton(name, id || name, this._scene);
  26429. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26430. for (var index = 0; index < this.bones.length; index++) {
  26431. var source = this.bones[index];
  26432. var parentBone = null;
  26433. if (source.getParent()) {
  26434. var parentIndex = this.bones.indexOf(source.getParent());
  26435. parentBone = result.bones[parentIndex];
  26436. }
  26437. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  26438. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  26439. }
  26440. if (this._ranges) {
  26441. result._ranges = {};
  26442. for (var rangeName in this._ranges) {
  26443. result._ranges[rangeName] = this._ranges[rangeName].clone();
  26444. }
  26445. }
  26446. this._isDirty = true;
  26447. return result;
  26448. };
  26449. Skeleton.prototype.dispose = function () {
  26450. this._meshesWithPoseMatrix = [];
  26451. // Animations
  26452. this.getScene().stopAnimation(this);
  26453. // Remove from scene
  26454. this.getScene().removeSkeleton(this);
  26455. };
  26456. Skeleton.prototype.serialize = function () {
  26457. var serializationObject = {};
  26458. serializationObject.name = this.name;
  26459. serializationObject.id = this.id;
  26460. serializationObject.bones = [];
  26461. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26462. for (var index = 0; index < this.bones.length; index++) {
  26463. var bone = this.bones[index];
  26464. var serializedBone = {
  26465. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  26466. name: bone.name,
  26467. matrix: bone.getLocalMatrix().toArray(),
  26468. rest: bone.getRestPose().toArray()
  26469. };
  26470. serializationObject.bones.push(serializedBone);
  26471. if (bone.length) {
  26472. serializedBone.length = bone.length;
  26473. }
  26474. if (bone.animations && bone.animations.length > 0) {
  26475. serializedBone.animation = bone.animations[0].serialize();
  26476. }
  26477. serializationObject.ranges = [];
  26478. for (var name in this._ranges) {
  26479. var range = {};
  26480. range.name = name;
  26481. range.from = this._ranges[name].from;
  26482. range.to = this._ranges[name].to;
  26483. serializationObject.ranges.push(range);
  26484. }
  26485. }
  26486. return serializationObject;
  26487. };
  26488. Skeleton.Parse = function (parsedSkeleton, scene) {
  26489. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  26490. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  26491. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  26492. var parsedBone = parsedSkeleton.bones[index];
  26493. var parentBone = null;
  26494. if (parsedBone.parentBoneIndex > -1) {
  26495. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  26496. }
  26497. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  26498. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  26499. if (parsedBone.length) {
  26500. bone.length = parsedBone.length;
  26501. }
  26502. if (parsedBone.animation) {
  26503. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  26504. }
  26505. }
  26506. // placed after bones, so createAnimationRange can cascade down
  26507. if (parsedSkeleton.ranges) {
  26508. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  26509. var data = parsedSkeleton.ranges[index];
  26510. skeleton.createAnimationRange(data.name, data.from, data.to);
  26511. }
  26512. }
  26513. return skeleton;
  26514. };
  26515. return Skeleton;
  26516. })();
  26517. BABYLON.Skeleton = Skeleton;
  26518. })(BABYLON || (BABYLON = {}));
  26519. var BABYLON;
  26520. (function (BABYLON) {
  26521. var PostProcess = (function () {
  26522. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  26523. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  26524. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26525. this.name = name;
  26526. this.width = -1;
  26527. this.height = -1;
  26528. this._reusable = false;
  26529. this._textures = new BABYLON.SmartArray(2);
  26530. this._currentRenderTextureInd = 0;
  26531. if (camera != null) {
  26532. this._camera = camera;
  26533. this._scene = camera.getScene();
  26534. camera.attachPostProcess(this);
  26535. this._engine = this._scene.getEngine();
  26536. }
  26537. else {
  26538. this._engine = engine;
  26539. }
  26540. this._renderRatio = ratio;
  26541. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  26542. this._reusable = reusable || false;
  26543. this._textureType = textureType;
  26544. this._samplers = samplers || [];
  26545. this._samplers.push("textureSampler");
  26546. this._fragmentUrl = fragmentUrl;
  26547. this._parameters = parameters || [];
  26548. this.updateEffect(defines);
  26549. }
  26550. PostProcess.prototype.updateEffect = function (defines) {
  26551. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  26552. };
  26553. PostProcess.prototype.isReusable = function () {
  26554. return this._reusable;
  26555. };
  26556. PostProcess.prototype.activate = function (camera, sourceTexture) {
  26557. camera = camera || this._camera;
  26558. var scene = camera.getScene();
  26559. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  26560. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  26561. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  26562. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  26563. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  26564. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  26565. if (this._textures.length > 0) {
  26566. for (var i = 0; i < this._textures.length; i++) {
  26567. this._engine._releaseTexture(this._textures.data[i]);
  26568. }
  26569. this._textures.reset();
  26570. }
  26571. this.width = desiredWidth;
  26572. this.height = desiredHeight;
  26573. 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 }));
  26574. if (this._reusable) {
  26575. 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 }));
  26576. }
  26577. if (this.onSizeChanged) {
  26578. this.onSizeChanged();
  26579. }
  26580. }
  26581. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  26582. if (this.onActivate) {
  26583. this.onActivate(camera);
  26584. }
  26585. // Clear
  26586. if (this.clearColor) {
  26587. this._engine.clear(this.clearColor, true, true);
  26588. }
  26589. else {
  26590. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  26591. }
  26592. if (this._reusable) {
  26593. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  26594. }
  26595. };
  26596. Object.defineProperty(PostProcess.prototype, "isSupported", {
  26597. get: function () {
  26598. return this._effect.isSupported;
  26599. },
  26600. enumerable: true,
  26601. configurable: true
  26602. });
  26603. PostProcess.prototype.apply = function () {
  26604. // Check
  26605. if (!this._effect.isReady())
  26606. return null;
  26607. // States
  26608. this._engine.enableEffect(this._effect);
  26609. this._engine.setState(false);
  26610. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26611. this._engine.setDepthBuffer(false);
  26612. this._engine.setDepthWrite(false);
  26613. // Texture
  26614. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  26615. // Parameters
  26616. if (this.onApply) {
  26617. this.onApply(this._effect);
  26618. }
  26619. return this._effect;
  26620. };
  26621. PostProcess.prototype.dispose = function (camera) {
  26622. camera = camera || this._camera;
  26623. if (this._textures.length > 0) {
  26624. for (var i = 0; i < this._textures.length; i++) {
  26625. this._engine._releaseTexture(this._textures.data[i]);
  26626. }
  26627. this._textures.reset();
  26628. }
  26629. if (!camera) {
  26630. return;
  26631. }
  26632. camera.detachPostProcess(this);
  26633. var index = camera._postProcesses.indexOf(this);
  26634. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  26635. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  26636. }
  26637. };
  26638. return PostProcess;
  26639. })();
  26640. BABYLON.PostProcess = PostProcess;
  26641. })(BABYLON || (BABYLON = {}));
  26642. var BABYLON;
  26643. (function (BABYLON) {
  26644. var PostProcessManager = (function () {
  26645. function PostProcessManager(scene) {
  26646. this._vertexDeclaration = [2];
  26647. this._vertexStrideSize = 2 * 4;
  26648. this._scene = scene;
  26649. }
  26650. PostProcessManager.prototype._prepareBuffers = function () {
  26651. if (this._vertexBuffer) {
  26652. return;
  26653. }
  26654. // VBO
  26655. var vertices = [];
  26656. vertices.push(1, 1);
  26657. vertices.push(-1, 1);
  26658. vertices.push(-1, -1);
  26659. vertices.push(1, -1);
  26660. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  26661. // Indices
  26662. var indices = [];
  26663. indices.push(0);
  26664. indices.push(1);
  26665. indices.push(2);
  26666. indices.push(0);
  26667. indices.push(2);
  26668. indices.push(3);
  26669. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26670. };
  26671. // Methods
  26672. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26673. var postProcesses = this._scene.activeCamera._postProcesses;
  26674. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26675. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26676. return false;
  26677. }
  26678. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  26679. return true;
  26680. };
  26681. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26682. var engine = this._scene.getEngine();
  26683. for (var index = 0; index < postProcesses.length; index++) {
  26684. if (index < postProcesses.length - 1) {
  26685. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26686. }
  26687. else {
  26688. if (targetTexture) {
  26689. engine.bindFramebuffer(targetTexture);
  26690. }
  26691. else {
  26692. engine.restoreDefaultFramebuffer();
  26693. }
  26694. }
  26695. var pp = postProcesses[index];
  26696. var effect = pp.apply();
  26697. if (effect) {
  26698. if (pp.onBeforeRender) {
  26699. pp.onBeforeRender(effect);
  26700. }
  26701. // VBOs
  26702. this._prepareBuffers();
  26703. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26704. // Draw order
  26705. engine.draw(true, 0, 6);
  26706. if (pp.onAfterRender) {
  26707. pp.onAfterRender(effect);
  26708. }
  26709. }
  26710. }
  26711. // Restore depth buffer
  26712. engine.setDepthBuffer(true);
  26713. engine.setDepthWrite(true);
  26714. };
  26715. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26716. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26717. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26718. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26719. return;
  26720. }
  26721. var engine = this._scene.getEngine();
  26722. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  26723. if (index < postProcessesTakenIndices.length - 1) {
  26724. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  26725. }
  26726. else {
  26727. if (targetTexture) {
  26728. engine.bindFramebuffer(targetTexture, faceIndex);
  26729. }
  26730. else {
  26731. engine.restoreDefaultFramebuffer();
  26732. }
  26733. }
  26734. if (doNotPresent) {
  26735. break;
  26736. }
  26737. var pp = postProcesses[postProcessesTakenIndices[index]];
  26738. var effect = pp.apply();
  26739. if (effect) {
  26740. if (pp.onBeforeRender) {
  26741. pp.onBeforeRender(effect);
  26742. }
  26743. // VBOs
  26744. this._prepareBuffers();
  26745. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26746. // Draw order
  26747. engine.draw(true, 0, 6);
  26748. if (pp.onAfterRender) {
  26749. pp.onAfterRender(effect);
  26750. }
  26751. }
  26752. }
  26753. // Restore depth buffer
  26754. engine.setDepthBuffer(true);
  26755. engine.setDepthWrite(true);
  26756. };
  26757. PostProcessManager.prototype.dispose = function () {
  26758. if (this._vertexBuffer) {
  26759. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  26760. this._vertexBuffer = null;
  26761. }
  26762. if (this._indexBuffer) {
  26763. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26764. this._indexBuffer = null;
  26765. }
  26766. };
  26767. return PostProcessManager;
  26768. })();
  26769. BABYLON.PostProcessManager = PostProcessManager;
  26770. })(BABYLON || (BABYLON = {}));
  26771. var BABYLON;
  26772. (function (BABYLON) {
  26773. var PassPostProcess = (function (_super) {
  26774. __extends(PassPostProcess, _super);
  26775. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26776. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  26777. }
  26778. return PassPostProcess;
  26779. })(BABYLON.PostProcess);
  26780. BABYLON.PassPostProcess = PassPostProcess;
  26781. })(BABYLON || (BABYLON = {}));
  26782. var BABYLON;
  26783. (function (BABYLON) {
  26784. /**
  26785. * This is a holder class for the physics joint created by the physics plugin.
  26786. * It holds a set of functions to control the underlying joint.
  26787. */
  26788. var PhysicsJoint = (function () {
  26789. function PhysicsJoint(type, jointData) {
  26790. this.type = type;
  26791. this.jointData = jointData;
  26792. jointData.nativeParams = jointData.nativeParams || {};
  26793. }
  26794. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  26795. get: function () {
  26796. return this._physicsJoint;
  26797. },
  26798. set: function (newJoint) {
  26799. if (this._physicsJoint) {
  26800. }
  26801. this._physicsJoint = newJoint;
  26802. },
  26803. enumerable: true,
  26804. configurable: true
  26805. });
  26806. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  26807. set: function (physicsPlugin) {
  26808. this._physicsPlugin = physicsPlugin;
  26809. },
  26810. enumerable: true,
  26811. configurable: true
  26812. });
  26813. /**
  26814. * Execute a function that is physics-plugin specific.
  26815. * @param {Function} func the function that will be executed.
  26816. * It accepts two parameters: the physics world and the physics joint.
  26817. */
  26818. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  26819. func(this._physicsPlugin.world, this._physicsJoint);
  26820. };
  26821. //TODO check if the native joints are the same
  26822. //Joint Types
  26823. PhysicsJoint.DistanceJoint = 0;
  26824. PhysicsJoint.HingeJoint = 1;
  26825. PhysicsJoint.BallAndSocketJoint = 2;
  26826. PhysicsJoint.WheelJoint = 3;
  26827. PhysicsJoint.SliderJoint = 4;
  26828. //OIMO
  26829. PhysicsJoint.PrismaticJoint = 5;
  26830. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  26831. PhysicsJoint.UniversalJoint = 6;
  26832. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  26833. //Cannon
  26834. //Similar to a Ball-Joint. Different in params
  26835. PhysicsJoint.PointToPointJoint = 8;
  26836. //Cannon only at the moment
  26837. PhysicsJoint.SpringJoint = 9;
  26838. return PhysicsJoint;
  26839. })();
  26840. BABYLON.PhysicsJoint = PhysicsJoint;
  26841. /**
  26842. * A class representing a physics distance joint.
  26843. */
  26844. var DistanceJoint = (function (_super) {
  26845. __extends(DistanceJoint, _super);
  26846. function DistanceJoint(jointData) {
  26847. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  26848. }
  26849. /**
  26850. * Update the predefined distance.
  26851. */
  26852. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  26853. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  26854. };
  26855. return DistanceJoint;
  26856. })(PhysicsJoint);
  26857. BABYLON.DistanceJoint = DistanceJoint;
  26858. /**
  26859. * This class represents a single hinge physics joint
  26860. */
  26861. var HingeJoint = (function (_super) {
  26862. __extends(HingeJoint, _super);
  26863. function HingeJoint(jointData) {
  26864. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  26865. }
  26866. /**
  26867. * Set the motor values.
  26868. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26869. * @param {number} force the force to apply
  26870. * @param {number} maxForce max force for this motor.
  26871. */
  26872. HingeJoint.prototype.setMotor = function (force, maxForce) {
  26873. this._physicsPlugin.setMotor(this, force, maxForce);
  26874. };
  26875. /**
  26876. * Set the motor's limits.
  26877. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26878. */
  26879. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  26880. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  26881. };
  26882. return HingeJoint;
  26883. })(PhysicsJoint);
  26884. BABYLON.HingeJoint = HingeJoint;
  26885. /**
  26886. * This class represents a dual hinge physics joint (same as wheel joint)
  26887. */
  26888. var Hinge2Joint = (function (_super) {
  26889. __extends(Hinge2Joint, _super);
  26890. function Hinge2Joint(jointData) {
  26891. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  26892. }
  26893. /**
  26894. * Set the motor values.
  26895. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26896. * @param {number} force the force to apply
  26897. * @param {number} maxForce max force for this motor.
  26898. * @param {motorIndex} the motor's index, 0 or 1.
  26899. */
  26900. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  26901. if (motorIndex === void 0) { motorIndex = 0; }
  26902. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  26903. };
  26904. /**
  26905. * Set the motor limits.
  26906. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26907. * @param {number} upperLimit the upper limit
  26908. * @param {number} lowerLimit lower limit
  26909. * @param {motorIndex} the motor's index, 0 or 1.
  26910. */
  26911. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  26912. if (motorIndex === void 0) { motorIndex = 0; }
  26913. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  26914. };
  26915. return Hinge2Joint;
  26916. })(PhysicsJoint);
  26917. BABYLON.Hinge2Joint = Hinge2Joint;
  26918. })(BABYLON || (BABYLON = {}));
  26919. var BABYLON;
  26920. (function (BABYLON) {
  26921. var PhysicsImpostor = (function () {
  26922. function PhysicsImpostor(object, type, _options, _scene) {
  26923. var _this = this;
  26924. if (_options === void 0) { _options = { mass: 0 }; }
  26925. this.object = object;
  26926. this.type = type;
  26927. this._options = _options;
  26928. this._scene = _scene;
  26929. this._bodyUpdateRequired = false;
  26930. this._onBeforePhysicsStepCallbacks = new Array();
  26931. this._onAfterPhysicsStepCallbacks = new Array();
  26932. this._onPhysicsCollideCallbacks = [];
  26933. this._deltaPosition = BABYLON.Vector3.Zero();
  26934. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  26935. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  26936. /**
  26937. * this function is executed by the physics engine.
  26938. */
  26939. this.beforeStep = function () {
  26940. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  26941. //conjugate deltaRotation
  26942. if (_this._deltaRotationConjugated) {
  26943. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  26944. }
  26945. else {
  26946. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  26947. }
  26948. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  26949. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  26950. func(_this);
  26951. });
  26952. };
  26953. /**
  26954. * this function is executed by the physics engine.
  26955. */
  26956. this.afterStep = function () {
  26957. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  26958. func(_this);
  26959. });
  26960. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  26961. _this.object.position.addInPlace(_this._deltaPosition);
  26962. if (_this._deltaRotation) {
  26963. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  26964. }
  26965. };
  26966. //event and body object due to cannon's event-based architecture.
  26967. this.onCollide = function (e) {
  26968. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  26969. if (otherImpostor) {
  26970. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  26971. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  26972. }).forEach(function (obj) {
  26973. obj.callback(_this, otherImpostor);
  26974. });
  26975. }
  26976. };
  26977. //sanity check!
  26978. if (!this.object) {
  26979. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  26980. return;
  26981. }
  26982. //legacy support for old syntax.
  26983. if (!this._scene && object.getScene) {
  26984. this._scene = object.getScene();
  26985. }
  26986. this._physicsEngine = this._scene.getPhysicsEngine();
  26987. if (!this._physicsEngine) {
  26988. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  26989. }
  26990. else {
  26991. //set the object's quaternion, if not set
  26992. if (!this.object.rotationQuaternion) {
  26993. if (this.object.rotation) {
  26994. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  26995. }
  26996. else {
  26997. this.object.rotationQuaternion = new BABYLON.Quaternion();
  26998. }
  26999. }
  27000. //default options params
  27001. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  27002. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  27003. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  27004. this._joints = [];
  27005. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  27006. if (!this.object.parent) {
  27007. this._init();
  27008. }
  27009. }
  27010. }
  27011. /**
  27012. * This function will completly initialize this impostor.
  27013. * It will create a new body - but only if this mesh has no parent.
  27014. * If it has, this impostor will not be used other than to define the impostor
  27015. * of the child mesh.
  27016. */
  27017. PhysicsImpostor.prototype._init = function () {
  27018. this._physicsEngine.removeImpostor(this);
  27019. this.physicsBody = null;
  27020. this._parent = this._parent || this._getPhysicsParent();
  27021. if (!this.parent) {
  27022. this._physicsEngine.addImpostor(this);
  27023. }
  27024. };
  27025. PhysicsImpostor.prototype._getPhysicsParent = function () {
  27026. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  27027. var parentMesh = this.object.parent;
  27028. return parentMesh.physicsImpostor;
  27029. }
  27030. return;
  27031. };
  27032. /**
  27033. * Should a new body be generated.
  27034. */
  27035. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  27036. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  27037. };
  27038. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  27039. this.forceUpdate();
  27040. };
  27041. /**
  27042. * Force a regeneration of this or the parent's impostor's body.
  27043. * Use under cautious - This will remove all joints already implemented.
  27044. */
  27045. PhysicsImpostor.prototype.forceUpdate = function () {
  27046. this._init();
  27047. if (this.parent) {
  27048. this.parent.forceUpdate();
  27049. }
  27050. };
  27051. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  27052. /*public get mesh(): AbstractMesh {
  27053. return this._mesh;
  27054. }*/
  27055. /**
  27056. * Gets the body that holds this impostor. Either its own, or its parent.
  27057. */
  27058. get: function () {
  27059. return this._parent ? this._parent.physicsBody : this._physicsBody;
  27060. },
  27061. /**
  27062. * Set the physics body. Used mainly by the physics engine/plugin
  27063. */
  27064. set: function (physicsBody) {
  27065. if (this._physicsBody) {
  27066. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  27067. }
  27068. this._physicsBody = physicsBody;
  27069. this.resetUpdateFlags();
  27070. },
  27071. enumerable: true,
  27072. configurable: true
  27073. });
  27074. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  27075. get: function () {
  27076. return this._parent;
  27077. },
  27078. enumerable: true,
  27079. configurable: true
  27080. });
  27081. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  27082. this._bodyUpdateRequired = false;
  27083. };
  27084. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  27085. if (this.object.getBoundingInfo) {
  27086. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  27087. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  27088. }
  27089. else {
  27090. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  27091. }
  27092. };
  27093. PhysicsImpostor.prototype.getObjectCenter = function () {
  27094. if (this.object.getBoundingInfo) {
  27095. return this.object.getBoundingInfo().boundingBox.center;
  27096. }
  27097. else {
  27098. return this.object.position;
  27099. }
  27100. };
  27101. /**
  27102. * Get a specific parametes from the options parameter.
  27103. */
  27104. PhysicsImpostor.prototype.getParam = function (paramName) {
  27105. return this._options[paramName];
  27106. };
  27107. /**
  27108. * Sets a specific parameter in the options given to the physics plugin
  27109. */
  27110. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  27111. this._options[paramName] = value;
  27112. this._bodyUpdateRequired = true;
  27113. };
  27114. /**
  27115. * Specifically change the body's mass option. Won't recreate the physics body object
  27116. */
  27117. PhysicsImpostor.prototype.setMass = function (mass) {
  27118. if (this.getParam("mass") !== mass) {
  27119. this.setParam("mass", mass);
  27120. }
  27121. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  27122. };
  27123. PhysicsImpostor.prototype.getLinearVelocity = function () {
  27124. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  27125. };
  27126. /**
  27127. * Set the body's linear velocity.
  27128. */
  27129. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  27130. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  27131. };
  27132. PhysicsImpostor.prototype.getAngularVelocity = function () {
  27133. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  27134. };
  27135. /**
  27136. * Set the body's linear velocity.
  27137. */
  27138. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  27139. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  27140. };
  27141. /**
  27142. * Execute a function with the physics plugin native code.
  27143. * Provide a function the will have two variables - the world object and the physics body object.
  27144. */
  27145. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  27146. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  27147. };
  27148. /**
  27149. * Register a function that will be executed before the physics world is stepping forward.
  27150. */
  27151. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  27152. this._onBeforePhysicsStepCallbacks.push(func);
  27153. };
  27154. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  27155. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  27156. if (index > -1) {
  27157. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  27158. }
  27159. else {
  27160. BABYLON.Tools.Warn("Function to remove was not found");
  27161. }
  27162. };
  27163. /**
  27164. * Register a function that will be executed after the physics step
  27165. */
  27166. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  27167. this._onAfterPhysicsStepCallbacks.push(func);
  27168. };
  27169. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  27170. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  27171. if (index > -1) {
  27172. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  27173. }
  27174. else {
  27175. BABYLON.Tools.Warn("Function to remove was not found");
  27176. }
  27177. };
  27178. /**
  27179. * register a function that will be executed when this impostor collides against a different body.
  27180. */
  27181. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  27182. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27183. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  27184. };
  27185. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  27186. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27187. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  27188. if (index > -1) {
  27189. this._onPhysicsCollideCallbacks.splice(index, 1);
  27190. }
  27191. else {
  27192. BABYLON.Tools.Warn("Function to remove was not found");
  27193. }
  27194. };
  27195. /**
  27196. * Apply a force
  27197. */
  27198. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  27199. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  27200. };
  27201. /**
  27202. * Apply an impulse
  27203. */
  27204. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  27205. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  27206. };
  27207. /**
  27208. * A help function to create a joint.
  27209. */
  27210. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  27211. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  27212. this.addJoint(otherImpostor, joint);
  27213. };
  27214. /**
  27215. * Add a joint to this impostor with a different impostor.
  27216. */
  27217. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  27218. this._joints.push({
  27219. otherImpostor: otherImpostor,
  27220. joint: joint
  27221. });
  27222. this._physicsEngine.addJoint(this, otherImpostor, joint);
  27223. };
  27224. /**
  27225. * Will keep this body still, in a sleep mode.
  27226. */
  27227. PhysicsImpostor.prototype.sleep = function () {
  27228. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  27229. };
  27230. /**
  27231. * Wake the body up.
  27232. */
  27233. PhysicsImpostor.prototype.wakeUp = function () {
  27234. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  27235. };
  27236. PhysicsImpostor.prototype.clone = function (newObject) {
  27237. if (!newObject)
  27238. return null;
  27239. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  27240. };
  27241. PhysicsImpostor.prototype.dispose = function () {
  27242. this.physicsBody = null;
  27243. if (this.parent) {
  27244. this.parent.forceUpdate();
  27245. }
  27246. else {
  27247. }
  27248. };
  27249. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  27250. this._deltaPosition.copyFrom(position);
  27251. };
  27252. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  27253. if (!this._deltaRotation) {
  27254. this._deltaRotation = new BABYLON.Quaternion();
  27255. }
  27256. this._deltaRotation.copyFrom(rotation);
  27257. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  27258. };
  27259. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  27260. //Impostor types
  27261. PhysicsImpostor.NoImpostor = 0;
  27262. PhysicsImpostor.SphereImpostor = 1;
  27263. PhysicsImpostor.BoxImpostor = 2;
  27264. PhysicsImpostor.PlaneImpostor = 3;
  27265. PhysicsImpostor.MeshImpostor = 4;
  27266. PhysicsImpostor.CylinderImpostor = 7;
  27267. PhysicsImpostor.ParticleImpostor = 8;
  27268. PhysicsImpostor.HeightmapImpostor = 9;
  27269. return PhysicsImpostor;
  27270. })();
  27271. BABYLON.PhysicsImpostor = PhysicsImpostor;
  27272. })(BABYLON || (BABYLON = {}));
  27273. var BABYLON;
  27274. (function (BABYLON) {
  27275. var PhysicsEngine = (function () {
  27276. function PhysicsEngine(gravity, _physicsPlugin) {
  27277. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  27278. this._physicsPlugin = _physicsPlugin;
  27279. //new methods and parameters
  27280. this._impostors = [];
  27281. this._joints = [];
  27282. if (!this._physicsPlugin.isSupported()) {
  27283. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  27284. + "Please make sure it is included.");
  27285. }
  27286. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  27287. this.setGravity(gravity);
  27288. this.setTimeStep();
  27289. }
  27290. PhysicsEngine.prototype.setGravity = function (gravity) {
  27291. this.gravity = gravity;
  27292. this._physicsPlugin.setGravity(this.gravity);
  27293. };
  27294. /**
  27295. * Set the time step of the physics engine.
  27296. * default is 1/60.
  27297. * To slow it down, enter 1/600 for example.
  27298. * To speed it up, 1/30
  27299. * @param {number} newTimeStep the new timestep to apply to this world.
  27300. */
  27301. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  27302. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  27303. this._physicsPlugin.setTimeStep(newTimeStep);
  27304. };
  27305. PhysicsEngine.prototype.dispose = function () {
  27306. this._impostors.forEach(function (impostor) {
  27307. impostor.dispose();
  27308. });
  27309. this._physicsPlugin.dispose();
  27310. };
  27311. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  27312. return this._physicsPlugin.name;
  27313. };
  27314. /**
  27315. * Adding a new impostor for the impostor tracking.
  27316. * This will be done by the impostor itself.
  27317. * @param {PhysicsImpostor} impostor the impostor to add
  27318. */
  27319. PhysicsEngine.prototype.addImpostor = function (impostor) {
  27320. impostor.uniqueId = this._impostors.push(impostor);
  27321. //if no parent, generate the body
  27322. if (!impostor.parent) {
  27323. this._physicsPlugin.generatePhysicsBody(impostor);
  27324. }
  27325. };
  27326. /**
  27327. * Remove an impostor from the engine.
  27328. * This impostor and its mesh will not longer be updated by the physics engine.
  27329. * @param {PhysicsImpostor} impostor the impostor to remove
  27330. */
  27331. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  27332. var index = this._impostors.indexOf(impostor);
  27333. if (index > -1) {
  27334. var removed = this._impostors.splice(index, 1);
  27335. //Is it needed?
  27336. if (removed.length) {
  27337. //this will also remove it from the world.
  27338. removed[0].physicsBody = null;
  27339. }
  27340. }
  27341. };
  27342. /**
  27343. * Add a joint to the physics engine
  27344. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  27345. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  27346. * @param {PhysicsJoint} the joint that will connect both impostors.
  27347. */
  27348. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  27349. var impostorJoint = {
  27350. mainImpostor: mainImpostor,
  27351. connectedImpostor: connectedImpostor,
  27352. joint: joint
  27353. };
  27354. joint.physicsPlugin = this._physicsPlugin;
  27355. this._joints.push(impostorJoint);
  27356. this._physicsPlugin.generateJoint(impostorJoint);
  27357. };
  27358. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  27359. var matchingJoints = this._joints.filter(function (impostorJoint) {
  27360. return (impostorJoint.connectedImpostor === connectedImpostor
  27361. && impostorJoint.joint === joint
  27362. && impostorJoint.mainImpostor === mainImpostor);
  27363. });
  27364. if (matchingJoints.length) {
  27365. this._physicsPlugin.removeJoint(matchingJoints[0]);
  27366. }
  27367. };
  27368. /**
  27369. * Called by the scene. no need to call it.
  27370. */
  27371. PhysicsEngine.prototype._step = function (delta) {
  27372. var _this = this;
  27373. //check if any mesh has no body / requires an update
  27374. this._impostors.forEach(function (impostor) {
  27375. if (impostor.isBodyInitRequired()) {
  27376. _this._physicsPlugin.generatePhysicsBody(impostor);
  27377. }
  27378. });
  27379. if (delta > 0.1) {
  27380. delta = 0.1;
  27381. }
  27382. else if (delta <= 0) {
  27383. delta = 1.0 / 60.0;
  27384. }
  27385. this._physicsPlugin.executeStep(delta, this._impostors);
  27386. };
  27387. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  27388. return this._physicsPlugin;
  27389. };
  27390. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  27391. for (var i = 0; i < this._impostors.length; ++i) {
  27392. if (this._impostors[i].object === object) {
  27393. return this._impostors[i];
  27394. }
  27395. }
  27396. };
  27397. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  27398. for (var i = 0; i < this._impostors.length; ++i) {
  27399. if (this._impostors[i].physicsBody === body) {
  27400. return this._impostors[i];
  27401. }
  27402. }
  27403. };
  27404. // Statics, Legacy support.
  27405. /**
  27406. * @Deprecated
  27407. *
  27408. */
  27409. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  27410. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  27411. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  27412. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  27413. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  27414. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  27415. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  27416. PhysicsEngine.CapsuleImpostor = -1;
  27417. PhysicsEngine.ConeImpostor = -1;
  27418. PhysicsEngine.ConvexHullImpostor = -1;
  27419. PhysicsEngine.Epsilon = 0.001;
  27420. return PhysicsEngine;
  27421. })();
  27422. BABYLON.PhysicsEngine = PhysicsEngine;
  27423. })(BABYLON || (BABYLON = {}));
  27424. var BABYLON;
  27425. (function (BABYLON) {
  27426. var VertexData = (function () {
  27427. function VertexData() {
  27428. }
  27429. VertexData.prototype.set = function (data, kind) {
  27430. switch (kind) {
  27431. case BABYLON.VertexBuffer.PositionKind:
  27432. this.positions = data;
  27433. break;
  27434. case BABYLON.VertexBuffer.NormalKind:
  27435. this.normals = data;
  27436. break;
  27437. case BABYLON.VertexBuffer.UVKind:
  27438. this.uvs = data;
  27439. break;
  27440. case BABYLON.VertexBuffer.UV2Kind:
  27441. this.uvs2 = data;
  27442. break;
  27443. case BABYLON.VertexBuffer.UV3Kind:
  27444. this.uvs3 = data;
  27445. break;
  27446. case BABYLON.VertexBuffer.UV4Kind:
  27447. this.uvs4 = data;
  27448. break;
  27449. case BABYLON.VertexBuffer.UV5Kind:
  27450. this.uvs5 = data;
  27451. break;
  27452. case BABYLON.VertexBuffer.UV6Kind:
  27453. this.uvs6 = data;
  27454. break;
  27455. case BABYLON.VertexBuffer.ColorKind:
  27456. this.colors = data;
  27457. break;
  27458. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27459. this.matricesIndices = data;
  27460. break;
  27461. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27462. this.matricesWeights = data;
  27463. break;
  27464. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27465. this.matricesIndicesExtra = data;
  27466. break;
  27467. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27468. this.matricesWeightsExtra = data;
  27469. break;
  27470. }
  27471. };
  27472. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27473. this._applyTo(mesh, updatable);
  27474. };
  27475. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27476. this._applyTo(geometry, updatable);
  27477. };
  27478. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27479. this._update(mesh);
  27480. };
  27481. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27482. this._update(geometry);
  27483. };
  27484. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27485. if (this.positions) {
  27486. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27487. }
  27488. if (this.normals) {
  27489. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27490. }
  27491. if (this.uvs) {
  27492. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27493. }
  27494. if (this.uvs2) {
  27495. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27496. }
  27497. if (this.uvs3) {
  27498. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27499. }
  27500. if (this.uvs4) {
  27501. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27502. }
  27503. if (this.uvs5) {
  27504. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27505. }
  27506. if (this.uvs6) {
  27507. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27508. }
  27509. if (this.colors) {
  27510. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27511. }
  27512. if (this.matricesIndices) {
  27513. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27514. }
  27515. if (this.matricesWeights) {
  27516. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27517. }
  27518. if (this.matricesIndicesExtra) {
  27519. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27520. }
  27521. if (this.matricesWeightsExtra) {
  27522. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27523. }
  27524. if (this.indices) {
  27525. meshOrGeometry.setIndices(this.indices);
  27526. }
  27527. };
  27528. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27529. if (this.positions) {
  27530. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27531. }
  27532. if (this.normals) {
  27533. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27534. }
  27535. if (this.uvs) {
  27536. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27537. }
  27538. if (this.uvs2) {
  27539. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27540. }
  27541. if (this.uvs3) {
  27542. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27543. }
  27544. if (this.uvs4) {
  27545. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27546. }
  27547. if (this.uvs5) {
  27548. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27549. }
  27550. if (this.uvs6) {
  27551. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27552. }
  27553. if (this.colors) {
  27554. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27555. }
  27556. if (this.matricesIndices) {
  27557. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27558. }
  27559. if (this.matricesWeights) {
  27560. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27561. }
  27562. if (this.matricesIndicesExtra) {
  27563. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27564. }
  27565. if (this.matricesWeightsExtra) {
  27566. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27567. }
  27568. if (this.indices) {
  27569. meshOrGeometry.setIndices(this.indices);
  27570. }
  27571. };
  27572. VertexData.prototype.transform = function (matrix) {
  27573. var transformed = BABYLON.Vector3.Zero();
  27574. var index;
  27575. if (this.positions) {
  27576. var position = BABYLON.Vector3.Zero();
  27577. for (index = 0; index < this.positions.length; index += 3) {
  27578. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27579. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27580. this.positions[index] = transformed.x;
  27581. this.positions[index + 1] = transformed.y;
  27582. this.positions[index + 2] = transformed.z;
  27583. }
  27584. }
  27585. if (this.normals) {
  27586. var normal = BABYLON.Vector3.Zero();
  27587. for (index = 0; index < this.normals.length; index += 3) {
  27588. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27589. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27590. this.normals[index] = transformed.x;
  27591. this.normals[index + 1] = transformed.y;
  27592. this.normals[index + 2] = transformed.z;
  27593. }
  27594. }
  27595. };
  27596. VertexData.prototype.merge = function (other) {
  27597. if (other.indices) {
  27598. if (!this.indices) {
  27599. this.indices = [];
  27600. }
  27601. var offset = this.positions ? this.positions.length / 3 : 0;
  27602. for (var index = 0; index < other.indices.length; index++) {
  27603. //TODO check type - if Int32Array!
  27604. this.indices.push(other.indices[index] + offset);
  27605. }
  27606. }
  27607. this.positions = this._mergeElement(this.positions, other.positions);
  27608. this.normals = this._mergeElement(this.normals, other.normals);
  27609. this.uvs = this._mergeElement(this.uvs, other.uvs);
  27610. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  27611. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  27612. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  27613. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  27614. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  27615. this.colors = this._mergeElement(this.colors, other.colors);
  27616. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  27617. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  27618. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  27619. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  27620. };
  27621. VertexData.prototype._mergeElement = function (source, other) {
  27622. if (!other)
  27623. return source;
  27624. if (!source)
  27625. return other;
  27626. var len = other.length + source.length;
  27627. var isSrcTypedArray = source instanceof Float32Array;
  27628. var isOthTypedArray = other instanceof Float32Array;
  27629. // use non-loop method when the source is Float32Array
  27630. if (isSrcTypedArray) {
  27631. var ret32 = new Float32Array(len);
  27632. ret32.set(source);
  27633. ret32.set(other, source.length);
  27634. return ret32;
  27635. }
  27636. else if (!isOthTypedArray) {
  27637. return source.concat(other);
  27638. }
  27639. else {
  27640. var ret = source.slice(0); // copy source to a separate array
  27641. for (var i = 0, len = other.length; i < len; i++) {
  27642. ret.push(other[i]);
  27643. }
  27644. return ret;
  27645. }
  27646. };
  27647. VertexData.prototype.serialize = function () {
  27648. var serializationObject = this.serialize();
  27649. if (this.positions) {
  27650. serializationObject.positions = this.positions;
  27651. }
  27652. if (this.normals) {
  27653. serializationObject.normals = this.normals;
  27654. }
  27655. if (this.uvs) {
  27656. serializationObject.uvs = this.uvs;
  27657. }
  27658. if (this.uvs2) {
  27659. serializationObject.uvs2 = this.uvs2;
  27660. }
  27661. if (this.uvs3) {
  27662. serializationObject.uvs3 = this.uvs3;
  27663. }
  27664. if (this.uvs4) {
  27665. serializationObject.uvs4 = this.uvs4;
  27666. }
  27667. if (this.uvs5) {
  27668. serializationObject.uvs5 = this.uvs5;
  27669. }
  27670. if (this.uvs6) {
  27671. serializationObject.uvs6 = this.uvs6;
  27672. }
  27673. if (this.colors) {
  27674. serializationObject.colors = this.colors;
  27675. }
  27676. if (this.matricesIndices) {
  27677. serializationObject.matricesIndices = this.matricesIndices;
  27678. serializationObject.matricesIndices._isExpanded = true;
  27679. }
  27680. if (this.matricesWeights) {
  27681. serializationObject.matricesWeights = this.matricesWeights;
  27682. }
  27683. if (this.matricesIndicesExtra) {
  27684. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27685. serializationObject.matricesIndicesExtra._isExpanded = true;
  27686. }
  27687. if (this.matricesWeightsExtra) {
  27688. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27689. }
  27690. serializationObject.indices = this.indices;
  27691. return serializationObject;
  27692. };
  27693. // Statics
  27694. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  27695. return VertexData._ExtractFrom(mesh, copyWhenShared);
  27696. };
  27697. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  27698. return VertexData._ExtractFrom(geometry, copyWhenShared);
  27699. };
  27700. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  27701. var result = new VertexData();
  27702. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27703. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  27704. }
  27705. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27706. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  27707. }
  27708. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27709. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  27710. }
  27711. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27712. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  27713. }
  27714. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27715. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  27716. }
  27717. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27718. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  27719. }
  27720. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27721. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  27722. }
  27723. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27724. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  27725. }
  27726. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27727. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  27728. }
  27729. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27730. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  27731. }
  27732. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27733. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  27734. }
  27735. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27736. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  27737. }
  27738. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27739. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  27740. }
  27741. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27742. return result;
  27743. };
  27744. VertexData.CreateRibbon = function (options) {
  27745. var pathArray = options.pathArray;
  27746. var closeArray = options.closeArray || false;
  27747. var closePath = options.closePath || false;
  27748. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27749. var offset = options.offset || defaultOffset;
  27750. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27751. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27752. var positions = [];
  27753. var indices = [];
  27754. var normals = [];
  27755. var uvs = [];
  27756. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27757. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27758. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27759. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27760. var minlg; // minimal length among all paths from pathArray
  27761. var lg = []; // array of path lengths : nb of vertex per path
  27762. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27763. var p; // path iterator
  27764. var i; // point iterator
  27765. var j; // point iterator
  27766. // if single path in pathArray
  27767. if (pathArray.length < 2) {
  27768. var ar1 = [];
  27769. var ar2 = [];
  27770. for (i = 0; i < pathArray[0].length - offset; i++) {
  27771. ar1.push(pathArray[0][i]);
  27772. ar2.push(pathArray[0][i + offset]);
  27773. }
  27774. pathArray = [ar1, ar2];
  27775. }
  27776. // positions and horizontal distances (u)
  27777. var idc = 0;
  27778. var closePathCorr = (closePath) ? 1 : 0;
  27779. var path;
  27780. var l;
  27781. minlg = pathArray[0].length;
  27782. var vectlg;
  27783. var dist;
  27784. for (p = 0; p < pathArray.length; p++) {
  27785. uTotalDistance[p] = 0;
  27786. us[p] = [0];
  27787. path = pathArray[p];
  27788. l = path.length;
  27789. minlg = (minlg < l) ? minlg : l;
  27790. j = 0;
  27791. while (j < l) {
  27792. positions.push(path[j].x, path[j].y, path[j].z);
  27793. if (j > 0) {
  27794. vectlg = path[j].subtract(path[j - 1]).length();
  27795. dist = vectlg + uTotalDistance[p];
  27796. us[p].push(dist);
  27797. uTotalDistance[p] = dist;
  27798. }
  27799. j++;
  27800. }
  27801. if (closePath) {
  27802. j--;
  27803. positions.push(path[0].x, path[0].y, path[0].z);
  27804. vectlg = path[j].subtract(path[0]).length();
  27805. dist = vectlg + uTotalDistance[p];
  27806. us[p].push(dist);
  27807. uTotalDistance[p] = dist;
  27808. }
  27809. lg[p] = l + closePathCorr;
  27810. idx[p] = idc;
  27811. idc += (l + closePathCorr);
  27812. }
  27813. // vertical distances (v)
  27814. var path1;
  27815. var path2;
  27816. var vertex1;
  27817. var vertex2;
  27818. for (i = 0; i < minlg + closePathCorr; i++) {
  27819. vTotalDistance[i] = 0;
  27820. vs[i] = [0];
  27821. for (p = 0; p < pathArray.length - 1; p++) {
  27822. path1 = pathArray[p];
  27823. path2 = pathArray[p + 1];
  27824. if (i === minlg) {
  27825. vertex1 = path1[0];
  27826. vertex2 = path2[0];
  27827. }
  27828. else {
  27829. vertex1 = path1[i];
  27830. vertex2 = path2[i];
  27831. }
  27832. vectlg = vertex2.subtract(vertex1).length();
  27833. dist = vectlg + vTotalDistance[i];
  27834. vs[i].push(dist);
  27835. vTotalDistance[i] = dist;
  27836. }
  27837. if (closeArray) {
  27838. path1 = pathArray[p];
  27839. path2 = pathArray[0];
  27840. if (i === minlg) {
  27841. vertex2 = path2[0];
  27842. }
  27843. vectlg = vertex2.subtract(vertex1).length();
  27844. dist = vectlg + vTotalDistance[i];
  27845. vTotalDistance[i] = dist;
  27846. }
  27847. }
  27848. // uvs
  27849. var u;
  27850. var v;
  27851. for (p = 0; p < pathArray.length; p++) {
  27852. for (i = 0; i < minlg + closePathCorr; i++) {
  27853. u = us[p][i] / uTotalDistance[p];
  27854. v = vs[i][p] / vTotalDistance[i];
  27855. uvs.push(u, v);
  27856. }
  27857. }
  27858. // indices
  27859. p = 0; // path index
  27860. var pi = 0; // positions array index
  27861. var l1 = lg[p] - 1; // path1 length
  27862. var l2 = lg[p + 1] - 1; // path2 length
  27863. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27864. var shft = idx[1] - idx[0]; // shift
  27865. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27866. while (pi <= min && p < path1nb) {
  27867. // 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
  27868. indices.push(pi, pi + shft, pi + 1);
  27869. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27870. pi += 1;
  27871. if (pi === min) {
  27872. p++;
  27873. if (p === lg.length - 1) {
  27874. shft = idx[0] - idx[p];
  27875. l1 = lg[p] - 1;
  27876. l2 = lg[0] - 1;
  27877. }
  27878. else {
  27879. shft = idx[p + 1] - idx[p];
  27880. l1 = lg[p] - 1;
  27881. l2 = lg[p + 1] - 1;
  27882. }
  27883. pi = idx[p];
  27884. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27885. }
  27886. }
  27887. // normals
  27888. VertexData.ComputeNormals(positions, indices, normals);
  27889. if (closePath) {
  27890. var indexFirst = 0;
  27891. var indexLast = 0;
  27892. for (p = 0; p < pathArray.length; p++) {
  27893. indexFirst = idx[p] * 3;
  27894. if (p + 1 < pathArray.length) {
  27895. indexLast = (idx[p + 1] - 1) * 3;
  27896. }
  27897. else {
  27898. indexLast = normals.length - 3;
  27899. }
  27900. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27901. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27902. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27903. normals[indexLast] = normals[indexFirst];
  27904. normals[indexLast + 1] = normals[indexFirst + 1];
  27905. normals[indexLast + 2] = normals[indexFirst + 2];
  27906. }
  27907. }
  27908. // sides
  27909. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27910. // Result
  27911. var vertexData = new VertexData();
  27912. vertexData.indices = indices;
  27913. vertexData.positions = positions;
  27914. vertexData.normals = normals;
  27915. vertexData.uvs = uvs;
  27916. if (closePath) {
  27917. vertexData._idx = idx;
  27918. }
  27919. return vertexData;
  27920. };
  27921. VertexData.CreateBox = function (options) {
  27922. var normalsSource = [
  27923. new BABYLON.Vector3(0, 0, 1),
  27924. new BABYLON.Vector3(0, 0, -1),
  27925. new BABYLON.Vector3(1, 0, 0),
  27926. new BABYLON.Vector3(-1, 0, 0),
  27927. new BABYLON.Vector3(0, 1, 0),
  27928. new BABYLON.Vector3(0, -1, 0)
  27929. ];
  27930. var indices = [];
  27931. var positions = [];
  27932. var normals = [];
  27933. var uvs = [];
  27934. var width = options.width || options.size || 1;
  27935. var height = options.height || options.size || 1;
  27936. var depth = options.depth || options.size || 1;
  27937. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27938. var faceUV = options.faceUV || new Array(6);
  27939. var faceColors = options.faceColors;
  27940. var colors = [];
  27941. // default face colors and UV if undefined
  27942. for (var f = 0; f < 6; f++) {
  27943. if (faceUV[f] === undefined) {
  27944. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27945. }
  27946. if (faceColors && faceColors[f] === undefined) {
  27947. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27948. }
  27949. }
  27950. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27951. // Create each face in turn.
  27952. for (var index = 0; index < normalsSource.length; index++) {
  27953. var normal = normalsSource[index];
  27954. // Get two vectors perpendicular to the face normal and to each other.
  27955. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27956. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27957. // Six indices (two triangles) per face.
  27958. var verticesLength = positions.length / 3;
  27959. indices.push(verticesLength);
  27960. indices.push(verticesLength + 1);
  27961. indices.push(verticesLength + 2);
  27962. indices.push(verticesLength);
  27963. indices.push(verticesLength + 2);
  27964. indices.push(verticesLength + 3);
  27965. // Four vertices per face.
  27966. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27967. positions.push(vertex.x, vertex.y, vertex.z);
  27968. normals.push(normal.x, normal.y, normal.z);
  27969. uvs.push(faceUV[index].z, faceUV[index].w);
  27970. if (faceColors) {
  27971. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27972. }
  27973. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27974. positions.push(vertex.x, vertex.y, vertex.z);
  27975. normals.push(normal.x, normal.y, normal.z);
  27976. uvs.push(faceUV[index].x, faceUV[index].w);
  27977. if (faceColors) {
  27978. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27979. }
  27980. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27981. positions.push(vertex.x, vertex.y, vertex.z);
  27982. normals.push(normal.x, normal.y, normal.z);
  27983. uvs.push(faceUV[index].x, faceUV[index].y);
  27984. if (faceColors) {
  27985. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27986. }
  27987. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27988. positions.push(vertex.x, vertex.y, vertex.z);
  27989. normals.push(normal.x, normal.y, normal.z);
  27990. uvs.push(faceUV[index].z, faceUV[index].y);
  27991. if (faceColors) {
  27992. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27993. }
  27994. }
  27995. // sides
  27996. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27997. // Result
  27998. var vertexData = new VertexData();
  27999. vertexData.indices = indices;
  28000. vertexData.positions = positions;
  28001. vertexData.normals = normals;
  28002. vertexData.uvs = uvs;
  28003. if (faceColors) {
  28004. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28005. vertexData.colors = totalColors;
  28006. }
  28007. return vertexData;
  28008. };
  28009. VertexData.CreateSphere = function (options) {
  28010. var segments = options.segments || 32;
  28011. var diameterX = options.diameterX || options.diameter || 1;
  28012. var diameterY = options.diameterY || options.diameter || 1;
  28013. var diameterZ = options.diameterZ || options.diameter || 1;
  28014. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28015. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28016. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28017. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28018. var totalZRotationSteps = 2 + segments;
  28019. var totalYRotationSteps = 2 * totalZRotationSteps;
  28020. var indices = [];
  28021. var positions = [];
  28022. var normals = [];
  28023. var uvs = [];
  28024. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28025. var normalizedZ = zRotationStep / totalZRotationSteps;
  28026. var angleZ = normalizedZ * Math.PI * slice;
  28027. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28028. var normalizedY = yRotationStep / totalYRotationSteps;
  28029. var angleY = normalizedY * Math.PI * 2 * arc;
  28030. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28031. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28032. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28033. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28034. var vertex = complete.multiply(radius);
  28035. var normal = complete.divide(radius).normalize();
  28036. positions.push(vertex.x, vertex.y, vertex.z);
  28037. normals.push(normal.x, normal.y, normal.z);
  28038. uvs.push(normalizedY, normalizedZ);
  28039. }
  28040. if (zRotationStep > 0) {
  28041. var verticesCount = positions.length / 3;
  28042. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28043. indices.push((firstIndex));
  28044. indices.push((firstIndex + 1));
  28045. indices.push(firstIndex + totalYRotationSteps + 1);
  28046. indices.push((firstIndex + totalYRotationSteps + 1));
  28047. indices.push((firstIndex + 1));
  28048. indices.push((firstIndex + totalYRotationSteps + 2));
  28049. }
  28050. }
  28051. }
  28052. // Sides
  28053. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28054. // Result
  28055. var vertexData = new VertexData();
  28056. vertexData.indices = indices;
  28057. vertexData.positions = positions;
  28058. vertexData.normals = normals;
  28059. vertexData.uvs = uvs;
  28060. return vertexData;
  28061. };
  28062. // Cylinder and cone
  28063. VertexData.CreateCylinder = function (options) {
  28064. var height = options.height || 2;
  28065. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28066. var diameterBottom = options.diameterBottom || options.diameter || 1;
  28067. var tessellation = options.tessellation || 24;
  28068. var subdivisions = options.subdivisions || 1;
  28069. var hasRings = options.hasRings;
  28070. var enclose = options.enclose;
  28071. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28072. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28073. var faceUV = options.faceUV || new Array(3);
  28074. var faceColors = options.faceColors;
  28075. // default face colors and UV if undefined
  28076. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28077. var ringNb = (hasRings) ? subdivisions : 1;
  28078. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28079. var f;
  28080. for (f = 0; f < surfaceNb; f++) {
  28081. if (faceColors && faceColors[f] === undefined) {
  28082. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28083. }
  28084. }
  28085. for (f = 0; f < surfaceNb; f++) {
  28086. if (faceUV && faceUV[f] === undefined) {
  28087. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28088. }
  28089. }
  28090. var indices = [];
  28091. var positions = [];
  28092. var normals = [];
  28093. var uvs = [];
  28094. var colors = [];
  28095. var angle_step = Math.PI * 2 * arc / tessellation;
  28096. var angle;
  28097. var h;
  28098. var radius;
  28099. var tan = (diameterBottom - diameterTop) / 2 / height;
  28100. var ringVertex = BABYLON.Vector3.Zero();
  28101. var ringNormal = BABYLON.Vector3.Zero();
  28102. var ringFirstVertex = BABYLON.Vector3.Zero();
  28103. var ringFirstNormal = BABYLON.Vector3.Zero();
  28104. var quadNormal = BABYLON.Vector3.Zero();
  28105. var Y = BABYLON.Axis.Y;
  28106. // positions, normals, uvs
  28107. var i;
  28108. var j;
  28109. var r;
  28110. var ringIdx = 1;
  28111. var s = 1; // surface index
  28112. var cs = 0;
  28113. var v = 0;
  28114. for (i = 0; i <= subdivisions; i++) {
  28115. h = i / subdivisions;
  28116. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28117. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28118. for (r = 0; r < ringIdx; r++) {
  28119. if (hasRings) {
  28120. s += r;
  28121. }
  28122. if (enclose) {
  28123. s += 2 * r;
  28124. }
  28125. for (j = 0; j <= tessellation; j++) {
  28126. angle = j * angle_step;
  28127. // position
  28128. ringVertex.x = Math.cos(-angle) * radius;
  28129. ringVertex.y = -height / 2 + h * height;
  28130. ringVertex.z = Math.sin(-angle) * radius;
  28131. // normal
  28132. if (diameterTop === 0 && i === subdivisions) {
  28133. // if no top cap, reuse former normals
  28134. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28135. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28136. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28137. }
  28138. else {
  28139. ringNormal.x = ringVertex.x;
  28140. ringNormal.z = ringVertex.z;
  28141. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28142. ringNormal.normalize();
  28143. }
  28144. // keep first ring vertex values for enclose
  28145. if (j === 0) {
  28146. ringFirstVertex.copyFrom(ringVertex);
  28147. ringFirstNormal.copyFrom(ringNormal);
  28148. }
  28149. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28150. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28151. if (hasRings) {
  28152. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28153. }
  28154. else {
  28155. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28156. }
  28157. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28158. if (faceColors) {
  28159. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28160. }
  28161. }
  28162. // if enclose, add four vertices and their dedicated normals
  28163. if (arc !== 1 && enclose) {
  28164. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28165. positions.push(0, ringVertex.y, 0);
  28166. positions.push(0, ringVertex.y, 0);
  28167. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28168. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28169. quadNormal.normalize();
  28170. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28171. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28172. quadNormal.normalize();
  28173. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28174. if (hasRings) {
  28175. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28176. }
  28177. else {
  28178. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28179. }
  28180. uvs.push(faceUV[s + 1].x, v);
  28181. uvs.push(faceUV[s + 1].z, v);
  28182. if (hasRings) {
  28183. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28184. }
  28185. else {
  28186. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28187. }
  28188. uvs.push(faceUV[s + 2].x, v);
  28189. uvs.push(faceUV[s + 2].z, v);
  28190. if (faceColors) {
  28191. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28192. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28193. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28194. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28195. }
  28196. }
  28197. if (cs !== s) {
  28198. cs = s;
  28199. }
  28200. }
  28201. }
  28202. // indices
  28203. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28204. var s;
  28205. i = 0;
  28206. for (s = 0; s < subdivisions; s++) {
  28207. for (j = 0; j < tessellation; j++) {
  28208. var i0 = i * (e + 1) + j;
  28209. var i1 = (i + 1) * (e + 1) + j;
  28210. var i2 = i * (e + 1) + (j + 1);
  28211. var i3 = (i + 1) * (e + 1) + (j + 1);
  28212. indices.push(i0, i1, i2);
  28213. indices.push(i3, i2, i1);
  28214. }
  28215. if (arc !== 1 && enclose) {
  28216. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28217. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28218. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28219. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28220. }
  28221. i = (hasRings) ? (i + 2) : (i + 1);
  28222. }
  28223. // Caps
  28224. var createCylinderCap = function (isTop) {
  28225. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28226. if (radius === 0) {
  28227. return;
  28228. }
  28229. // Cap positions, normals & uvs
  28230. var angle;
  28231. var circleVector;
  28232. var i;
  28233. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28234. var c;
  28235. if (faceColors) {
  28236. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28237. }
  28238. // cap center
  28239. var vbase = positions.length / 3;
  28240. var offset = isTop ? height / 2 : -height / 2;
  28241. var center = new BABYLON.Vector3(0, offset, 0);
  28242. positions.push(center.x, center.y, center.z);
  28243. normals.push(0, isTop ? 1 : -1, 0);
  28244. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28245. if (faceColors) {
  28246. colors.push(c.r, c.g, c.b, c.a);
  28247. }
  28248. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28249. for (i = 0; i <= tessellation; i++) {
  28250. angle = Math.PI * 2 * i * arc / tessellation;
  28251. var cos = Math.cos(-angle);
  28252. var sin = Math.sin(-angle);
  28253. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28254. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28255. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28256. normals.push(0, isTop ? 1 : -1, 0);
  28257. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28258. if (faceColors) {
  28259. colors.push(c.r, c.g, c.b, c.a);
  28260. }
  28261. }
  28262. // Cap indices
  28263. for (i = 0; i < tessellation; i++) {
  28264. if (!isTop) {
  28265. indices.push(vbase);
  28266. indices.push(vbase + (i + 1));
  28267. indices.push(vbase + (i + 2));
  28268. }
  28269. else {
  28270. indices.push(vbase);
  28271. indices.push(vbase + (i + 2));
  28272. indices.push(vbase + (i + 1));
  28273. }
  28274. }
  28275. };
  28276. // add caps to geometry
  28277. createCylinderCap(false);
  28278. createCylinderCap(true);
  28279. // Sides
  28280. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28281. var vertexData = new VertexData();
  28282. vertexData.indices = indices;
  28283. vertexData.positions = positions;
  28284. vertexData.normals = normals;
  28285. vertexData.uvs = uvs;
  28286. if (faceColors) {
  28287. vertexData.colors = colors;
  28288. }
  28289. return vertexData;
  28290. };
  28291. VertexData.CreateTorus = function (options) {
  28292. var indices = [];
  28293. var positions = [];
  28294. var normals = [];
  28295. var uvs = [];
  28296. var diameter = options.diameter || 1;
  28297. var thickness = options.thickness || 0.5;
  28298. var tessellation = options.tessellation || 16;
  28299. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28300. var stride = tessellation + 1;
  28301. for (var i = 0; i <= tessellation; i++) {
  28302. var u = i / tessellation;
  28303. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28304. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28305. for (var j = 0; j <= tessellation; j++) {
  28306. var v = 1 - j / tessellation;
  28307. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28308. var dx = Math.cos(innerAngle);
  28309. var dy = Math.sin(innerAngle);
  28310. // Create a vertex.
  28311. var normal = new BABYLON.Vector3(dx, dy, 0);
  28312. var position = normal.scale(thickness / 2);
  28313. var textureCoordinate = new BABYLON.Vector2(u, v);
  28314. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28315. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28316. positions.push(position.x, position.y, position.z);
  28317. normals.push(normal.x, normal.y, normal.z);
  28318. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28319. // And create indices for two triangles.
  28320. var nextI = (i + 1) % stride;
  28321. var nextJ = (j + 1) % stride;
  28322. indices.push(i * stride + j);
  28323. indices.push(i * stride + nextJ);
  28324. indices.push(nextI * stride + j);
  28325. indices.push(i * stride + nextJ);
  28326. indices.push(nextI * stride + nextJ);
  28327. indices.push(nextI * stride + j);
  28328. }
  28329. }
  28330. // Sides
  28331. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28332. // Result
  28333. var vertexData = new VertexData();
  28334. vertexData.indices = indices;
  28335. vertexData.positions = positions;
  28336. vertexData.normals = normals;
  28337. vertexData.uvs = uvs;
  28338. return vertexData;
  28339. };
  28340. VertexData.CreateLineSystem = function (options) {
  28341. var indices = [];
  28342. var positions = [];
  28343. var lines = options.lines;
  28344. var idx = 0;
  28345. for (var l = 0; l < lines.length; l++) {
  28346. var points = lines[l];
  28347. for (var index = 0; index < points.length; index++) {
  28348. positions.push(points[index].x, points[index].y, points[index].z);
  28349. if (index > 0) {
  28350. indices.push(idx - 1);
  28351. indices.push(idx);
  28352. }
  28353. idx++;
  28354. }
  28355. }
  28356. var vertexData = new VertexData();
  28357. vertexData.indices = indices;
  28358. vertexData.positions = positions;
  28359. return vertexData;
  28360. };
  28361. VertexData.CreateDashedLines = function (options) {
  28362. var dashSize = options.dashSize || 3;
  28363. var gapSize = options.gapSize || 1;
  28364. var dashNb = options.dashNb || 200;
  28365. var points = options.points;
  28366. var positions = new Array();
  28367. var indices = new Array();
  28368. var curvect = BABYLON.Vector3.Zero();
  28369. var lg = 0;
  28370. var nb = 0;
  28371. var shft = 0;
  28372. var dashshft = 0;
  28373. var curshft = 0;
  28374. var idx = 0;
  28375. var i = 0;
  28376. for (i = 0; i < points.length - 1; i++) {
  28377. points[i + 1].subtractToRef(points[i], curvect);
  28378. lg += curvect.length();
  28379. }
  28380. shft = lg / dashNb;
  28381. dashshft = dashSize * shft / (dashSize + gapSize);
  28382. for (i = 0; i < points.length - 1; i++) {
  28383. points[i + 1].subtractToRef(points[i], curvect);
  28384. nb = Math.floor(curvect.length() / shft);
  28385. curvect.normalize();
  28386. for (var j = 0; j < nb; j++) {
  28387. curshft = shft * j;
  28388. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28389. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28390. indices.push(idx, idx + 1);
  28391. idx += 2;
  28392. }
  28393. }
  28394. // Result
  28395. var vertexData = new VertexData();
  28396. vertexData.positions = positions;
  28397. vertexData.indices = indices;
  28398. return vertexData;
  28399. };
  28400. VertexData.CreateGround = function (options) {
  28401. var indices = [];
  28402. var positions = [];
  28403. var normals = [];
  28404. var uvs = [];
  28405. var row, col;
  28406. var width = options.width || 1;
  28407. var height = options.height || 1;
  28408. var subdivisions = options.subdivisions || 1;
  28409. for (row = 0; row <= subdivisions; row++) {
  28410. for (col = 0; col <= subdivisions; col++) {
  28411. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  28412. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28413. positions.push(position.x, position.y, position.z);
  28414. normals.push(normal.x, normal.y, normal.z);
  28415. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  28416. }
  28417. }
  28418. for (row = 0; row < subdivisions; row++) {
  28419. for (col = 0; col < subdivisions; col++) {
  28420. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28421. indices.push(col + 1 + row * (subdivisions + 1));
  28422. indices.push(col + row * (subdivisions + 1));
  28423. indices.push(col + (row + 1) * (subdivisions + 1));
  28424. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28425. indices.push(col + row * (subdivisions + 1));
  28426. }
  28427. }
  28428. // Result
  28429. var vertexData = new VertexData();
  28430. vertexData.indices = indices;
  28431. vertexData.positions = positions;
  28432. vertexData.normals = normals;
  28433. vertexData.uvs = uvs;
  28434. return vertexData;
  28435. };
  28436. VertexData.CreateTiledGround = function (options) {
  28437. var xmin = options.xmin;
  28438. var zmin = options.zmin;
  28439. var xmax = options.xmax;
  28440. var zmax = options.zmax;
  28441. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28442. var precision = options.precision || { w: 1, h: 1 };
  28443. var indices = [];
  28444. var positions = [];
  28445. var normals = [];
  28446. var uvs = [];
  28447. var row, col, tileRow, tileCol;
  28448. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  28449. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28450. precision.w = (precision.w < 1) ? 1 : precision.w;
  28451. precision.h = (precision.h < 1) ? 1 : precision.h;
  28452. var tileSize = {
  28453. 'w': (xmax - xmin) / subdivisions.w,
  28454. 'h': (zmax - zmin) / subdivisions.h
  28455. };
  28456. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28457. // Indices
  28458. var base = positions.length / 3;
  28459. var rowLength = precision.w + 1;
  28460. for (row = 0; row < precision.h; row++) {
  28461. for (col = 0; col < precision.w; col++) {
  28462. var square = [
  28463. base + col + row * rowLength,
  28464. base + (col + 1) + row * rowLength,
  28465. base + (col + 1) + (row + 1) * rowLength,
  28466. base + col + (row + 1) * rowLength
  28467. ];
  28468. indices.push(square[1]);
  28469. indices.push(square[2]);
  28470. indices.push(square[3]);
  28471. indices.push(square[0]);
  28472. indices.push(square[1]);
  28473. indices.push(square[3]);
  28474. }
  28475. }
  28476. // Position, normals and uvs
  28477. var position = BABYLON.Vector3.Zero();
  28478. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28479. for (row = 0; row <= precision.h; row++) {
  28480. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28481. for (col = 0; col <= precision.w; col++) {
  28482. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28483. position.y = 0;
  28484. positions.push(position.x, position.y, position.z);
  28485. normals.push(normal.x, normal.y, normal.z);
  28486. uvs.push(col / precision.w, row / precision.h);
  28487. }
  28488. }
  28489. }
  28490. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28491. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28492. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28493. }
  28494. }
  28495. // Result
  28496. var vertexData = new VertexData();
  28497. vertexData.indices = indices;
  28498. vertexData.positions = positions;
  28499. vertexData.normals = normals;
  28500. vertexData.uvs = uvs;
  28501. return vertexData;
  28502. };
  28503. VertexData.CreateGroundFromHeightMap = function (options) {
  28504. var indices = [];
  28505. var positions = [];
  28506. var normals = [];
  28507. var uvs = [];
  28508. var row, col;
  28509. // Vertices
  28510. for (row = 0; row <= options.subdivisions; row++) {
  28511. for (col = 0; col <= options.subdivisions; col++) {
  28512. 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));
  28513. // Compute height
  28514. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28515. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28516. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28517. var r = options.buffer[pos] / 255.0;
  28518. var g = options.buffer[pos + 1] / 255.0;
  28519. var b = options.buffer[pos + 2] / 255.0;
  28520. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28521. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28522. // Add vertex
  28523. positions.push(position.x, position.y, position.z);
  28524. normals.push(0, 0, 0);
  28525. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28526. }
  28527. }
  28528. // Indices
  28529. for (row = 0; row < options.subdivisions; row++) {
  28530. for (col = 0; col < options.subdivisions; col++) {
  28531. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28532. indices.push(col + 1 + row * (options.subdivisions + 1));
  28533. indices.push(col + row * (options.subdivisions + 1));
  28534. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28535. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28536. indices.push(col + row * (options.subdivisions + 1));
  28537. }
  28538. }
  28539. // Normals
  28540. VertexData.ComputeNormals(positions, indices, normals);
  28541. // Result
  28542. var vertexData = new VertexData();
  28543. vertexData.indices = indices;
  28544. vertexData.positions = positions;
  28545. vertexData.normals = normals;
  28546. vertexData.uvs = uvs;
  28547. return vertexData;
  28548. };
  28549. VertexData.CreatePlane = function (options) {
  28550. var indices = [];
  28551. var positions = [];
  28552. var normals = [];
  28553. var uvs = [];
  28554. var width = options.width || options.size || 1;
  28555. var height = options.height || options.size || 1;
  28556. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28557. // Vertices
  28558. var halfWidth = width / 2.0;
  28559. var halfHeight = height / 2.0;
  28560. positions.push(-halfWidth, -halfHeight, 0);
  28561. normals.push(0, 0, -1.0);
  28562. uvs.push(0.0, 0.0);
  28563. positions.push(halfWidth, -halfHeight, 0);
  28564. normals.push(0, 0, -1.0);
  28565. uvs.push(1.0, 0.0);
  28566. positions.push(halfWidth, halfHeight, 0);
  28567. normals.push(0, 0, -1.0);
  28568. uvs.push(1.0, 1.0);
  28569. positions.push(-halfWidth, halfHeight, 0);
  28570. normals.push(0, 0, -1.0);
  28571. uvs.push(0.0, 1.0);
  28572. // Indices
  28573. indices.push(0);
  28574. indices.push(1);
  28575. indices.push(2);
  28576. indices.push(0);
  28577. indices.push(2);
  28578. indices.push(3);
  28579. // Sides
  28580. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28581. // Result
  28582. var vertexData = new VertexData();
  28583. vertexData.indices = indices;
  28584. vertexData.positions = positions;
  28585. vertexData.normals = normals;
  28586. vertexData.uvs = uvs;
  28587. return vertexData;
  28588. };
  28589. VertexData.CreateDisc = function (options) {
  28590. var positions = [];
  28591. var indices = [];
  28592. var normals = [];
  28593. var uvs = [];
  28594. var radius = options.radius || 0.5;
  28595. var tessellation = options.tessellation || 64;
  28596. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28597. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28598. // positions and uvs
  28599. positions.push(0, 0, 0); // disc center first
  28600. uvs.push(0.5, 0.5);
  28601. var theta = Math.PI * 2 * arc;
  28602. var step = theta / tessellation;
  28603. for (var a = 0; a < theta; a += step) {
  28604. var x = Math.cos(a);
  28605. var y = Math.sin(a);
  28606. var u = (x + 1) / 2;
  28607. var v = (1 - y) / 2;
  28608. positions.push(radius * x, radius * y, 0);
  28609. uvs.push(u, v);
  28610. }
  28611. if (arc === 1) {
  28612. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28613. uvs.push(uvs[2], uvs[3]);
  28614. }
  28615. //indices
  28616. var vertexNb = positions.length / 3;
  28617. for (var i = 1; i < vertexNb - 1; i++) {
  28618. indices.push(i + 1, 0, i);
  28619. }
  28620. // result
  28621. VertexData.ComputeNormals(positions, indices, normals);
  28622. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28623. var vertexData = new VertexData();
  28624. vertexData.indices = indices;
  28625. vertexData.positions = positions;
  28626. vertexData.normals = normals;
  28627. vertexData.uvs = uvs;
  28628. return vertexData;
  28629. };
  28630. VertexData.CreateIcoSphere = function (options) {
  28631. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28632. var radius = options.radius || 1;
  28633. var flat = (options.flat === undefined) ? true : options.flat;
  28634. var subdivisions = options.subdivisions || 4;
  28635. var radiusX = options.radiusX || radius;
  28636. var radiusY = options.radiusY || radius;
  28637. var radiusZ = options.radiusZ || radius;
  28638. var t = (1 + Math.sqrt(5)) / 2;
  28639. // 12 vertex x,y,z
  28640. var ico_vertices = [
  28641. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28642. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28643. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28644. ];
  28645. // index of 3 vertex makes a face of icopshere
  28646. var ico_indices = [
  28647. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28648. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28649. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28650. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28651. ];
  28652. // vertex for uv have aliased position, not for UV
  28653. var vertices_unalias_id = [
  28654. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28655. // vertex alias
  28656. 0,
  28657. 2,
  28658. 3,
  28659. 3,
  28660. 3,
  28661. 4,
  28662. 7,
  28663. 8,
  28664. 9,
  28665. 9,
  28666. 10,
  28667. 11 // 23: B + 12
  28668. ];
  28669. // uv as integer step (not pixels !)
  28670. var ico_vertexuv = [
  28671. 5, 1, 3, 1, 6, 4, 0, 0,
  28672. 5, 3, 4, 2, 2, 2, 4, 0,
  28673. 2, 0, 1, 1, 6, 0, 6, 2,
  28674. // vertex alias (for same vertex on different faces)
  28675. 0, 4,
  28676. 3, 3,
  28677. 4, 4,
  28678. 3, 1,
  28679. 4, 2,
  28680. 4, 4,
  28681. 0, 2,
  28682. 1, 1,
  28683. 2, 2,
  28684. 3, 3,
  28685. 1, 3,
  28686. 2, 4 // 23: B + 12
  28687. ];
  28688. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28689. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28690. // First island of uv mapping
  28691. // v = 4h 3+ 2
  28692. // v = 3h 9+ 4
  28693. // v = 2h 9+ 5 B
  28694. // v = 1h 9 1 0
  28695. // v = 0h 3 8 7 A
  28696. // u = 0 1 2 3 4 5 6 *a
  28697. // Second island of uv mapping
  28698. // v = 4h 0+ B+ 4+
  28699. // v = 3h A+ 2+
  28700. // v = 2h 7+ 6 3+
  28701. // v = 1h 8+ 3+
  28702. // v = 0h
  28703. // u = 0 1 2 3 4 5 6 *a
  28704. // Face layout on texture UV mapping
  28705. // ============
  28706. // \ 4 /\ 16 / ======
  28707. // \ / \ / /\ 11 /
  28708. // \/ 7 \/ / \ /
  28709. // ======= / 10 \/
  28710. // /\ 17 /\ =======
  28711. // / \ / \ \ 15 /\
  28712. // / 8 \/ 12 \ \ / \
  28713. // ============ \/ 6 \
  28714. // \ 18 /\ ============
  28715. // \ / \ \ 5 /\ 0 /
  28716. // \/ 13 \ \ / \ /
  28717. // ======= \/ 1 \/
  28718. // =============
  28719. // /\ 19 /\ 2 /\
  28720. // / \ / \ / \
  28721. // / 14 \/ 9 \/ 3 \
  28722. // ===================
  28723. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28724. var ustep = 138 / 1024;
  28725. var vstep = 239 / 1024;
  28726. var uoffset = 60 / 1024;
  28727. var voffset = 26 / 1024;
  28728. // Second island should have margin, not to touch the first island
  28729. // avoid any borderline artefact in pixel rounding
  28730. var island_u_offset = -40 / 1024;
  28731. var island_v_offset = +20 / 1024;
  28732. // face is either island 0 or 1 :
  28733. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28734. var island = [
  28735. 0, 0, 0, 0, 1,
  28736. 0, 0, 1, 1, 0,
  28737. 0, 0, 1, 1, 0,
  28738. 0, 1, 1, 1, 0 // 15 - 19
  28739. ];
  28740. var indices = [];
  28741. var positions = [];
  28742. var normals = [];
  28743. var uvs = [];
  28744. var current_indice = 0;
  28745. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28746. var face_vertex_pos = new Array(3);
  28747. var face_vertex_uv = new Array(3);
  28748. var v012;
  28749. for (v012 = 0; v012 < 3; v012++) {
  28750. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28751. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28752. }
  28753. // create all with normals
  28754. for (var face = 0; face < 20; face++) {
  28755. // 3 vertex per face
  28756. for (v012 = 0; v012 < 3; v012++) {
  28757. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28758. var v_id = ico_indices[3 * face + v012];
  28759. // vertex have 3D position (x,y,z)
  28760. 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]);
  28761. // Normalize to get normal, then scale to radius
  28762. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28763. // uv Coordinates from vertex ID
  28764. 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);
  28765. }
  28766. // Subdivide the face (interpolate pos, norm, uv)
  28767. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28768. // - norm is linear interpolation of vertex corner normal
  28769. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28770. // - uv is linear interpolation
  28771. //
  28772. // Topology is as below for sub-divide by 2
  28773. // vertex shown as v0,v1,v2
  28774. // interp index is i1 to progress in range [v0,v1[
  28775. // interp index is i2 to progress in range [v0,v2[
  28776. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28777. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28778. //
  28779. //
  28780. // i2 v2
  28781. // ^ ^
  28782. // / / \
  28783. // / / \
  28784. // / / \
  28785. // / / (0,1) \
  28786. // / #---------\
  28787. // / / \ (0,0)'/ \
  28788. // / / \ / \
  28789. // / / \ / \
  28790. // / / (0,0) \ / (1,0) \
  28791. // / #---------#---------\
  28792. // v0 v1
  28793. //
  28794. // --------------------> i1
  28795. //
  28796. // interp of (i1,i2):
  28797. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28798. // along i1 : lerp(x0,x1, i1/(S-i2))
  28799. //
  28800. // centroid of triangle is needed to get help normal computation
  28801. // (c1,c2) are used for centroid location
  28802. var interp_vertex = function (i1, i2, c1, c2) {
  28803. // vertex is interpolated from
  28804. // - face_vertex_pos[0..2]
  28805. // - face_vertex_uv[0..2]
  28806. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28807. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28808. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28809. pos_interp.normalize();
  28810. var vertex_normal;
  28811. if (flat) {
  28812. // in flat mode, recalculate normal as face centroid normal
  28813. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28814. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28815. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28816. }
  28817. else {
  28818. // in smooth mode, recalculate normal from each single vertex position
  28819. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28820. }
  28821. // Vertex normal need correction due to X,Y,Z radius scaling
  28822. vertex_normal.x /= radiusX;
  28823. vertex_normal.y /= radiusY;
  28824. vertex_normal.z /= radiusZ;
  28825. vertex_normal.normalize();
  28826. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28827. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28828. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28829. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28830. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28831. uvs.push(uv_interp.x, uv_interp.y);
  28832. // push each vertex has member of a face
  28833. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28834. indices.push(current_indice);
  28835. current_indice++;
  28836. };
  28837. for (var i2 = 0; i2 < subdivisions; i2++) {
  28838. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28839. // face : (i1,i2) for /\ :
  28840. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28841. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28842. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28843. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28844. if (i1 + i2 + 1 < subdivisions) {
  28845. // face : (i1,i2)' for \/ :
  28846. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28847. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28848. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28849. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28850. }
  28851. }
  28852. }
  28853. }
  28854. // Sides
  28855. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28856. // Result
  28857. var vertexData = new VertexData();
  28858. vertexData.indices = indices;
  28859. vertexData.positions = positions;
  28860. vertexData.normals = normals;
  28861. vertexData.uvs = uvs;
  28862. return vertexData;
  28863. };
  28864. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28865. VertexData.CreatePolyhedron = function (options) {
  28866. // provided polyhedron types :
  28867. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28868. // 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)
  28869. var polyhedra = [];
  28870. 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]] };
  28871. 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]] };
  28872. polyhedra[2] = {
  28873. 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]],
  28874. 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]]
  28875. };
  28876. polyhedra[3] = {
  28877. 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]],
  28878. 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]]
  28879. };
  28880. polyhedra[4] = {
  28881. 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]],
  28882. 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]]
  28883. };
  28884. 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]] };
  28885. 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]] };
  28886. 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]] };
  28887. 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]] };
  28888. 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]] };
  28889. 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]] };
  28890. 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]] };
  28891. 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]] };
  28892. 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]] };
  28893. polyhedra[14] = {
  28894. 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]],
  28895. 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]]
  28896. };
  28897. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28898. var size = options.size;
  28899. var sizeX = options.sizeX || size || 1;
  28900. var sizeY = options.sizeY || size || 1;
  28901. var sizeZ = options.sizeZ || size || 1;
  28902. var data = options.custom || polyhedra[type];
  28903. var nbfaces = data.face.length;
  28904. var faceUV = options.faceUV || new Array(nbfaces);
  28905. var faceColors = options.faceColors;
  28906. var flat = (options.flat === undefined) ? true : options.flat;
  28907. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28908. var positions = [];
  28909. var indices = [];
  28910. var normals = [];
  28911. var uvs = [];
  28912. var colors = [];
  28913. var index = 0;
  28914. var faceIdx = 0; // face cursor in the array "indexes"
  28915. var indexes = [];
  28916. var i = 0;
  28917. var f = 0;
  28918. var u, v, ang, x, y, tmp;
  28919. // default face colors and UV if undefined
  28920. if (flat) {
  28921. for (f = 0; f < nbfaces; f++) {
  28922. if (faceColors && faceColors[f] === undefined) {
  28923. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28924. }
  28925. if (faceUV && faceUV[f] === undefined) {
  28926. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28927. }
  28928. }
  28929. }
  28930. if (!flat) {
  28931. for (i = 0; i < data.vertex.length; i++) {
  28932. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28933. uvs.push(0, 0);
  28934. }
  28935. for (f = 0; f < nbfaces; f++) {
  28936. for (i = 0; i < data.face[f].length - 2; i++) {
  28937. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28938. }
  28939. }
  28940. }
  28941. else {
  28942. for (f = 0; f < nbfaces; f++) {
  28943. var fl = data.face[f].length; // number of vertices of the current face
  28944. ang = 2 * Math.PI / fl;
  28945. x = 0.5 * Math.tan(ang / 2);
  28946. y = 0.5;
  28947. // positions, uvs, colors
  28948. for (i = 0; i < fl; i++) {
  28949. // positions
  28950. 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);
  28951. indexes.push(index);
  28952. index++;
  28953. // uvs
  28954. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28955. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28956. uvs.push(u, v);
  28957. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28958. y = x * Math.sin(ang) + y * Math.cos(ang);
  28959. x = tmp;
  28960. // colors
  28961. if (faceColors) {
  28962. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28963. }
  28964. }
  28965. // indices from indexes
  28966. for (i = 0; i < fl - 2; i++) {
  28967. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28968. }
  28969. faceIdx += fl;
  28970. }
  28971. }
  28972. VertexData.ComputeNormals(positions, indices, normals);
  28973. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28974. var vertexData = new VertexData();
  28975. vertexData.positions = positions;
  28976. vertexData.indices = indices;
  28977. vertexData.normals = normals;
  28978. vertexData.uvs = uvs;
  28979. if (faceColors && flat) {
  28980. vertexData.colors = colors;
  28981. }
  28982. return vertexData;
  28983. };
  28984. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28985. VertexData.CreateTorusKnot = function (options) {
  28986. var indices = [];
  28987. var positions = [];
  28988. var normals = [];
  28989. var uvs = [];
  28990. var radius = options.radius || 2;
  28991. var tube = options.tube || 0.5;
  28992. var radialSegments = options.radialSegments || 32;
  28993. var tubularSegments = options.tubularSegments || 32;
  28994. var p = options.p || 2;
  28995. var q = options.q || 3;
  28996. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28997. // Helper
  28998. var getPos = function (angle) {
  28999. var cu = Math.cos(angle);
  29000. var su = Math.sin(angle);
  29001. var quOverP = q / p * angle;
  29002. var cs = Math.cos(quOverP);
  29003. var tx = radius * (2 + cs) * 0.5 * cu;
  29004. var ty = radius * (2 + cs) * su * 0.5;
  29005. var tz = radius * Math.sin(quOverP) * 0.5;
  29006. return new BABYLON.Vector3(tx, ty, tz);
  29007. };
  29008. // Vertices
  29009. var i;
  29010. var j;
  29011. for (i = 0; i <= radialSegments; i++) {
  29012. var modI = i % radialSegments;
  29013. var u = modI / radialSegments * 2 * p * Math.PI;
  29014. var p1 = getPos(u);
  29015. var p2 = getPos(u + 0.01);
  29016. var tang = p2.subtract(p1);
  29017. var n = p2.add(p1);
  29018. var bitan = BABYLON.Vector3.Cross(tang, n);
  29019. n = BABYLON.Vector3.Cross(bitan, tang);
  29020. bitan.normalize();
  29021. n.normalize();
  29022. for (j = 0; j < tubularSegments; j++) {
  29023. var modJ = j % tubularSegments;
  29024. var v = modJ / tubularSegments * 2 * Math.PI;
  29025. var cx = -tube * Math.cos(v);
  29026. var cy = tube * Math.sin(v);
  29027. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29028. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29029. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29030. uvs.push(i / radialSegments);
  29031. uvs.push(j / tubularSegments);
  29032. }
  29033. }
  29034. for (i = 0; i < radialSegments; i++) {
  29035. for (j = 0; j < tubularSegments; j++) {
  29036. var jNext = (j + 1) % tubularSegments;
  29037. var a = i * tubularSegments + j;
  29038. var b = (i + 1) * tubularSegments + j;
  29039. var c = (i + 1) * tubularSegments + jNext;
  29040. var d = i * tubularSegments + jNext;
  29041. indices.push(d);
  29042. indices.push(b);
  29043. indices.push(a);
  29044. indices.push(d);
  29045. indices.push(c);
  29046. indices.push(b);
  29047. }
  29048. }
  29049. // Normals
  29050. VertexData.ComputeNormals(positions, indices, normals);
  29051. // Sides
  29052. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29053. // Result
  29054. var vertexData = new VertexData();
  29055. vertexData.indices = indices;
  29056. vertexData.positions = positions;
  29057. vertexData.normals = normals;
  29058. vertexData.uvs = uvs;
  29059. return vertexData;
  29060. };
  29061. // Tools
  29062. /**
  29063. * @param {any} - positions (number[] or Float32Array)
  29064. * @param {any} - indices (number[] or Uint16Array)
  29065. * @param {any} - normals (number[] or Float32Array)
  29066. */
  29067. VertexData.ComputeNormals = function (positions, indices, normals) {
  29068. var index = 0;
  29069. var p1p2x = 0.0;
  29070. var p1p2y = 0.0;
  29071. var p1p2z = 0.0;
  29072. var p3p2x = 0.0;
  29073. var p3p2y = 0.0;
  29074. var p3p2z = 0.0;
  29075. var faceNormalx = 0.0;
  29076. var faceNormaly = 0.0;
  29077. var faceNormalz = 0.0;
  29078. var length = 0.0;
  29079. var i1 = 0;
  29080. var i2 = 0;
  29081. var i3 = 0;
  29082. for (index = 0; index < positions.length; index++) {
  29083. normals[index] = 0.0;
  29084. }
  29085. // indice triplet = 1 face
  29086. var nbFaces = indices.length / 3;
  29087. for (index = 0; index < nbFaces; index++) {
  29088. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  29089. i2 = indices[index * 3 + 1];
  29090. i3 = indices[index * 3 + 2];
  29091. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  29092. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  29093. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  29094. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  29095. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  29096. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  29097. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  29098. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  29099. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  29100. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29101. length = (length === 0) ? 1.0 : length;
  29102. faceNormalx /= length; // normalize this normal
  29103. faceNormaly /= length;
  29104. faceNormalz /= length;
  29105. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  29106. normals[i1 * 3 + 1] += faceNormaly;
  29107. normals[i1 * 3 + 2] += faceNormalz;
  29108. normals[i2 * 3] += faceNormalx;
  29109. normals[i2 * 3 + 1] += faceNormaly;
  29110. normals[i2 * 3 + 2] += faceNormalz;
  29111. normals[i3 * 3] += faceNormalx;
  29112. normals[i3 * 3 + 1] += faceNormaly;
  29113. normals[i3 * 3 + 2] += faceNormalz;
  29114. }
  29115. // last normalization of each normal
  29116. for (index = 0; index < normals.length / 3; index++) {
  29117. faceNormalx = normals[index * 3];
  29118. faceNormaly = normals[index * 3 + 1];
  29119. faceNormalz = normals[index * 3 + 2];
  29120. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29121. length = (length === 0) ? 1.0 : length;
  29122. faceNormalx /= length;
  29123. faceNormaly /= length;
  29124. faceNormalz /= length;
  29125. normals[index * 3] = faceNormalx;
  29126. normals[index * 3 + 1] = faceNormaly;
  29127. normals[index * 3 + 2] = faceNormalz;
  29128. }
  29129. };
  29130. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  29131. var li = indices.length;
  29132. var ln = normals.length;
  29133. var i;
  29134. var n;
  29135. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29136. switch (sideOrientation) {
  29137. case BABYLON.Mesh.FRONTSIDE:
  29138. // nothing changed
  29139. break;
  29140. case BABYLON.Mesh.BACKSIDE:
  29141. var tmp;
  29142. // indices
  29143. for (i = 0; i < li; i += 3) {
  29144. tmp = indices[i];
  29145. indices[i] = indices[i + 2];
  29146. indices[i + 2] = tmp;
  29147. }
  29148. // normals
  29149. for (n = 0; n < ln; n++) {
  29150. normals[n] = -normals[n];
  29151. }
  29152. break;
  29153. case BABYLON.Mesh.DOUBLESIDE:
  29154. // positions
  29155. var lp = positions.length;
  29156. var l = lp / 3;
  29157. for (var p = 0; p < lp; p++) {
  29158. positions[lp + p] = positions[p];
  29159. }
  29160. // indices
  29161. for (i = 0; i < li; i += 3) {
  29162. indices[i + li] = indices[i + 2] + l;
  29163. indices[i + 1 + li] = indices[i + 1] + l;
  29164. indices[i + 2 + li] = indices[i] + l;
  29165. }
  29166. // normals
  29167. for (n = 0; n < ln; n++) {
  29168. normals[ln + n] = -normals[n];
  29169. }
  29170. // uvs
  29171. var lu = uvs.length;
  29172. for (var u = 0; u < lu; u++) {
  29173. uvs[u + lu] = uvs[u];
  29174. }
  29175. break;
  29176. }
  29177. };
  29178. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29179. var vertexData = new VertexData();
  29180. // positions
  29181. var positions = parsedVertexData.positions;
  29182. if (positions) {
  29183. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29184. }
  29185. // normals
  29186. var normals = parsedVertexData.normals;
  29187. if (normals) {
  29188. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29189. }
  29190. // uvs
  29191. var uvs = parsedVertexData.uvs;
  29192. if (uvs) {
  29193. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29194. }
  29195. // uv2s
  29196. var uv2s = parsedVertexData.uv2s;
  29197. if (uv2s) {
  29198. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29199. }
  29200. // uv3s
  29201. var uv3s = parsedVertexData.uv3s;
  29202. if (uv3s) {
  29203. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29204. }
  29205. // uv4s
  29206. var uv4s = parsedVertexData.uv4s;
  29207. if (uv4s) {
  29208. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29209. }
  29210. // uv5s
  29211. var uv5s = parsedVertexData.uv5s;
  29212. if (uv5s) {
  29213. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29214. }
  29215. // uv6s
  29216. var uv6s = parsedVertexData.uv6s;
  29217. if (uv6s) {
  29218. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29219. }
  29220. // colors
  29221. var colors = parsedVertexData.colors;
  29222. if (colors) {
  29223. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29224. }
  29225. // matricesIndices
  29226. var matricesIndices = parsedVertexData.matricesIndices;
  29227. if (matricesIndices) {
  29228. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29229. }
  29230. // matricesWeights
  29231. var matricesWeights = parsedVertexData.matricesWeights;
  29232. if (matricesWeights) {
  29233. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29234. }
  29235. // indices
  29236. var indices = parsedVertexData.indices;
  29237. if (indices) {
  29238. vertexData.indices = indices;
  29239. }
  29240. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29241. };
  29242. return VertexData;
  29243. })();
  29244. BABYLON.VertexData = VertexData;
  29245. })(BABYLON || (BABYLON = {}));
  29246. var BABYLON;
  29247. (function (BABYLON) {
  29248. var Tags = (function () {
  29249. function Tags() {
  29250. }
  29251. Tags.EnableFor = function (obj) {
  29252. obj._tags = obj._tags || {};
  29253. obj.hasTags = function () {
  29254. return Tags.HasTags(obj);
  29255. };
  29256. obj.addTags = function (tagsString) {
  29257. return Tags.AddTagsTo(obj, tagsString);
  29258. };
  29259. obj.removeTags = function (tagsString) {
  29260. return Tags.RemoveTagsFrom(obj, tagsString);
  29261. };
  29262. obj.matchesTagsQuery = function (tagsQuery) {
  29263. return Tags.MatchesQuery(obj, tagsQuery);
  29264. };
  29265. };
  29266. Tags.DisableFor = function (obj) {
  29267. delete obj._tags;
  29268. delete obj.hasTags;
  29269. delete obj.addTags;
  29270. delete obj.removeTags;
  29271. delete obj.matchesTagsQuery;
  29272. };
  29273. Tags.HasTags = function (obj) {
  29274. if (!obj._tags) {
  29275. return false;
  29276. }
  29277. return !BABYLON.Tools.IsEmpty(obj._tags);
  29278. };
  29279. Tags.GetTags = function (obj, asString) {
  29280. if (asString === void 0) { asString = true; }
  29281. if (!obj._tags) {
  29282. return null;
  29283. }
  29284. if (asString) {
  29285. var tagsArray = [];
  29286. for (var tag in obj._tags) {
  29287. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  29288. tagsArray.push(tag);
  29289. }
  29290. }
  29291. return tagsArray.join(" ");
  29292. }
  29293. else {
  29294. return obj._tags;
  29295. }
  29296. };
  29297. // the tags 'true' and 'false' are reserved and cannot be used as tags
  29298. // a tag cannot start with '||', '&&', and '!'
  29299. // it cannot contain whitespaces
  29300. Tags.AddTagsTo = function (obj, tagsString) {
  29301. if (!tagsString) {
  29302. return;
  29303. }
  29304. if (typeof tagsString !== "string") {
  29305. return;
  29306. }
  29307. var tags = tagsString.split(" ");
  29308. for (var t in tags) {
  29309. Tags._AddTagTo(obj, tags[t]);
  29310. }
  29311. };
  29312. Tags._AddTagTo = function (obj, tag) {
  29313. tag = tag.trim();
  29314. if (tag === "" || tag === "true" || tag === "false") {
  29315. return;
  29316. }
  29317. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  29318. return;
  29319. }
  29320. Tags.EnableFor(obj);
  29321. obj._tags[tag] = true;
  29322. };
  29323. Tags.RemoveTagsFrom = function (obj, tagsString) {
  29324. if (!Tags.HasTags(obj)) {
  29325. return;
  29326. }
  29327. var tags = tagsString.split(" ");
  29328. for (var t in tags) {
  29329. Tags._RemoveTagFrom(obj, tags[t]);
  29330. }
  29331. };
  29332. Tags._RemoveTagFrom = function (obj, tag) {
  29333. delete obj._tags[tag];
  29334. };
  29335. Tags.MatchesQuery = function (obj, tagsQuery) {
  29336. if (tagsQuery === undefined) {
  29337. return true;
  29338. }
  29339. if (tagsQuery === "") {
  29340. return Tags.HasTags(obj);
  29341. }
  29342. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  29343. };
  29344. return Tags;
  29345. })();
  29346. BABYLON.Tags = Tags;
  29347. })(BABYLON || (BABYLON = {}));
  29348. var BABYLON;
  29349. (function (BABYLON) {
  29350. var Internals;
  29351. (function (Internals) {
  29352. var AndOrNotEvaluator = (function () {
  29353. function AndOrNotEvaluator() {
  29354. }
  29355. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  29356. if (!query.match(/\([^\(\)]*\)/g)) {
  29357. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  29358. }
  29359. else {
  29360. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  29361. // remove parenthesis
  29362. r = r.slice(1, r.length - 1);
  29363. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  29364. });
  29365. }
  29366. if (query === "true") {
  29367. return true;
  29368. }
  29369. if (query === "false") {
  29370. return false;
  29371. }
  29372. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  29373. };
  29374. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  29375. evaluateCallback = evaluateCallback || (function (r) {
  29376. return r === "true" ? true : false;
  29377. });
  29378. var result;
  29379. var or = parenthesisContent.split("||");
  29380. for (var i in or) {
  29381. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  29382. var and = ori.split("&&");
  29383. if (and.length > 1) {
  29384. for (var j = 0; j < and.length; ++j) {
  29385. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  29386. if (andj !== "true" && andj !== "false") {
  29387. if (andj[0] === "!") {
  29388. result = !evaluateCallback(andj.substring(1));
  29389. }
  29390. else {
  29391. result = evaluateCallback(andj);
  29392. }
  29393. }
  29394. else {
  29395. result = andj === "true" ? true : false;
  29396. }
  29397. if (!result) {
  29398. ori = "false";
  29399. break;
  29400. }
  29401. }
  29402. }
  29403. if (result || ori === "true") {
  29404. result = true;
  29405. break;
  29406. }
  29407. // result equals false (or undefined)
  29408. if (ori !== "true" && ori !== "false") {
  29409. if (ori[0] === "!") {
  29410. result = !evaluateCallback(ori.substring(1));
  29411. }
  29412. else {
  29413. result = evaluateCallback(ori);
  29414. }
  29415. }
  29416. else {
  29417. result = ori === "true" ? true : false;
  29418. }
  29419. }
  29420. // the whole parenthesis scope is replaced by 'true' or 'false'
  29421. return result ? "true" : "false";
  29422. };
  29423. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  29424. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  29425. // remove whitespaces
  29426. r = r.replace(/[\s]/g, function () { return ""; });
  29427. return r.length % 2 ? "!" : "";
  29428. });
  29429. booleanString = booleanString.trim();
  29430. if (booleanString === "!true") {
  29431. booleanString = "false";
  29432. }
  29433. else if (booleanString === "!false") {
  29434. booleanString = "true";
  29435. }
  29436. return booleanString;
  29437. };
  29438. return AndOrNotEvaluator;
  29439. })();
  29440. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  29441. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29442. })(BABYLON || (BABYLON = {}));
  29443. var BABYLON;
  29444. (function (BABYLON) {
  29445. var PostProcessRenderPass = (function () {
  29446. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  29447. this._enabled = true;
  29448. this._refCount = 0;
  29449. this._name = name;
  29450. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  29451. this.setRenderList(renderList);
  29452. this._renderTexture.onBeforeRender = beforeRender;
  29453. this._renderTexture.onAfterRender = afterRender;
  29454. this._scene = scene;
  29455. this._renderList = renderList;
  29456. }
  29457. // private
  29458. PostProcessRenderPass.prototype._incRefCount = function () {
  29459. if (this._refCount === 0) {
  29460. this._scene.customRenderTargets.push(this._renderTexture);
  29461. }
  29462. return ++this._refCount;
  29463. };
  29464. PostProcessRenderPass.prototype._decRefCount = function () {
  29465. this._refCount--;
  29466. if (this._refCount <= 0) {
  29467. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  29468. }
  29469. return this._refCount;
  29470. };
  29471. PostProcessRenderPass.prototype._update = function () {
  29472. this.setRenderList(this._renderList);
  29473. };
  29474. // public
  29475. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  29476. this._renderTexture.renderList = renderList;
  29477. };
  29478. PostProcessRenderPass.prototype.getRenderTexture = function () {
  29479. return this._renderTexture;
  29480. };
  29481. return PostProcessRenderPass;
  29482. })();
  29483. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  29484. })(BABYLON || (BABYLON = {}));
  29485. var BABYLON;
  29486. (function (BABYLON) {
  29487. var PostProcessRenderEffect = (function () {
  29488. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  29489. this._engine = engine;
  29490. this._name = name;
  29491. this._singleInstance = singleInstance || true;
  29492. this._getPostProcess = getPostProcess;
  29493. this._cameras = [];
  29494. this._indicesForCamera = [];
  29495. this._postProcesses = {};
  29496. this._renderPasses = {};
  29497. this._renderEffectAsPasses = {};
  29498. }
  29499. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  29500. get: function () {
  29501. for (var index in this._postProcesses) {
  29502. if (!this._postProcesses[index].isSupported) {
  29503. return false;
  29504. }
  29505. }
  29506. return true;
  29507. },
  29508. enumerable: true,
  29509. configurable: true
  29510. });
  29511. PostProcessRenderEffect.prototype._update = function () {
  29512. for (var renderPassName in this._renderPasses) {
  29513. this._renderPasses[renderPassName]._update();
  29514. }
  29515. };
  29516. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  29517. this._renderPasses[renderPass._name] = renderPass;
  29518. this._linkParameters();
  29519. };
  29520. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  29521. delete this._renderPasses[renderPass._name];
  29522. this._linkParameters();
  29523. };
  29524. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  29525. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  29526. this._linkParameters();
  29527. };
  29528. PostProcessRenderEffect.prototype.getPass = function (passName) {
  29529. for (var renderPassName in this._renderPasses) {
  29530. if (renderPassName === passName) {
  29531. return this._renderPasses[passName];
  29532. }
  29533. }
  29534. };
  29535. PostProcessRenderEffect.prototype.emptyPasses = function () {
  29536. this._renderPasses = {};
  29537. this._linkParameters();
  29538. };
  29539. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  29540. var cameraKey;
  29541. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29542. for (var i = 0; i < _cam.length; i++) {
  29543. var camera = _cam[i];
  29544. var cameraName = camera.name;
  29545. if (this._singleInstance) {
  29546. cameraKey = 0;
  29547. }
  29548. else {
  29549. cameraKey = cameraName;
  29550. }
  29551. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  29552. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  29553. if (!this._indicesForCamera[cameraName]) {
  29554. this._indicesForCamera[cameraName] = [];
  29555. }
  29556. this._indicesForCamera[cameraName].push(index);
  29557. if (this._cameras.indexOf(camera) === -1) {
  29558. this._cameras[cameraName] = camera;
  29559. }
  29560. for (var passName in this._renderPasses) {
  29561. this._renderPasses[passName]._incRefCount();
  29562. }
  29563. }
  29564. this._linkParameters();
  29565. };
  29566. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  29567. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29568. for (var i = 0; i < _cam.length; i++) {
  29569. var camera = _cam[i];
  29570. var cameraName = camera.name;
  29571. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29572. var index = this._cameras.indexOf(cameraName);
  29573. this._indicesForCamera.splice(index, 1);
  29574. this._cameras.splice(index, 1);
  29575. for (var passName in this._renderPasses) {
  29576. this._renderPasses[passName]._decRefCount();
  29577. }
  29578. }
  29579. };
  29580. PostProcessRenderEffect.prototype._enable = function (cameras) {
  29581. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29582. for (var i = 0; i < _cam.length; i++) {
  29583. var camera = _cam[i];
  29584. var cameraName = camera.name;
  29585. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  29586. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  29587. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  29588. }
  29589. }
  29590. for (var passName in this._renderPasses) {
  29591. this._renderPasses[passName]._incRefCount();
  29592. }
  29593. }
  29594. };
  29595. PostProcessRenderEffect.prototype._disable = function (cameras) {
  29596. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29597. for (var i = 0; i < _cam.length; i++) {
  29598. var camera = _cam[i];
  29599. var cameraName = camera.Name;
  29600. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29601. for (var passName in this._renderPasses) {
  29602. this._renderPasses[passName]._decRefCount();
  29603. }
  29604. }
  29605. };
  29606. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  29607. if (this._singleInstance) {
  29608. return this._postProcesses[0];
  29609. }
  29610. else {
  29611. return this._postProcesses[camera.name];
  29612. }
  29613. };
  29614. PostProcessRenderEffect.prototype._linkParameters = function () {
  29615. var _this = this;
  29616. for (var index in this._postProcesses) {
  29617. if (this.applyParameters) {
  29618. this.applyParameters(this._postProcesses[index]);
  29619. }
  29620. this._postProcesses[index].onBeforeRender = function (effect) {
  29621. _this._linkTextures(effect);
  29622. };
  29623. }
  29624. };
  29625. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  29626. for (var renderPassName in this._renderPasses) {
  29627. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  29628. }
  29629. for (var renderEffectName in this._renderEffectAsPasses) {
  29630. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  29631. }
  29632. };
  29633. return PostProcessRenderEffect;
  29634. })();
  29635. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  29636. })(BABYLON || (BABYLON = {}));
  29637. var BABYLON;
  29638. (function (BABYLON) {
  29639. var PostProcessRenderPipeline = (function () {
  29640. function PostProcessRenderPipeline(engine, name) {
  29641. this._engine = engine;
  29642. this._name = name;
  29643. this._renderEffects = {};
  29644. this._renderEffectsForIsolatedPass = {};
  29645. this._cameras = [];
  29646. }
  29647. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  29648. get: function () {
  29649. for (var renderEffectName in this._renderEffects) {
  29650. if (!this._renderEffects[renderEffectName].isSupported) {
  29651. return false;
  29652. }
  29653. }
  29654. return true;
  29655. },
  29656. enumerable: true,
  29657. configurable: true
  29658. });
  29659. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  29660. this._renderEffects[renderEffect._name] = renderEffect;
  29661. };
  29662. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  29663. var renderEffects = this._renderEffects[renderEffectName];
  29664. if (!renderEffects) {
  29665. return;
  29666. }
  29667. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29668. };
  29669. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  29670. var renderEffects = this._renderEffects[renderEffectName];
  29671. if (!renderEffects) {
  29672. return;
  29673. }
  29674. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29675. };
  29676. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  29677. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29678. var indicesToDelete = [];
  29679. var i;
  29680. for (i = 0; i < _cam.length; i++) {
  29681. var camera = _cam[i];
  29682. var cameraName = camera.name;
  29683. if (this._cameras.indexOf(camera) === -1) {
  29684. this._cameras[cameraName] = camera;
  29685. }
  29686. else if (unique) {
  29687. indicesToDelete.push(i);
  29688. }
  29689. }
  29690. for (i = 0; i < indicesToDelete.length; i++) {
  29691. cameras.splice(indicesToDelete[i], 1);
  29692. }
  29693. for (var renderEffectName in this._renderEffects) {
  29694. this._renderEffects[renderEffectName]._attachCameras(_cam);
  29695. }
  29696. };
  29697. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  29698. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29699. for (var renderEffectName in this._renderEffects) {
  29700. this._renderEffects[renderEffectName]._detachCameras(_cam);
  29701. }
  29702. for (var i = 0; i < _cam.length; i++) {
  29703. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  29704. }
  29705. };
  29706. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  29707. var _this = this;
  29708. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29709. var pass = null;
  29710. var renderEffectName;
  29711. for (renderEffectName in this._renderEffects) {
  29712. pass = this._renderEffects[renderEffectName].getPass(passName);
  29713. if (pass != null) {
  29714. break;
  29715. }
  29716. }
  29717. if (pass === null) {
  29718. return;
  29719. }
  29720. for (renderEffectName in this._renderEffects) {
  29721. this._renderEffects[renderEffectName]._disable(_cam);
  29722. }
  29723. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  29724. for (var i = 0; i < _cam.length; i++) {
  29725. var camera = _cam[i];
  29726. var cameraName = camera.name;
  29727. 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); });
  29728. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  29729. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  29730. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  29731. }
  29732. };
  29733. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  29734. var _this = this;
  29735. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29736. for (var i = 0; i < _cam.length; i++) {
  29737. var camera = _cam[i];
  29738. var cameraName = camera.name;
  29739. 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); });
  29740. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  29741. }
  29742. for (var renderEffectName in this._renderEffects) {
  29743. this._renderEffects[renderEffectName]._enable(_cam);
  29744. }
  29745. };
  29746. PostProcessRenderPipeline.prototype._update = function () {
  29747. for (var renderEffectName in this._renderEffects) {
  29748. this._renderEffects[renderEffectName]._update();
  29749. }
  29750. for (var i = 0; i < this._cameras.length; i++) {
  29751. var cameraName = this._cameras[i].name;
  29752. if (this._renderEffectsForIsolatedPass[cameraName]) {
  29753. this._renderEffectsForIsolatedPass[cameraName]._update();
  29754. }
  29755. }
  29756. };
  29757. PostProcessRenderPipeline.prototype.dispose = function () {
  29758. // Must be implemented by children
  29759. };
  29760. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  29761. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  29762. return PostProcessRenderPipeline;
  29763. })();
  29764. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  29765. })(BABYLON || (BABYLON = {}));
  29766. var BABYLON;
  29767. (function (BABYLON) {
  29768. var PostProcessRenderPipelineManager = (function () {
  29769. function PostProcessRenderPipelineManager() {
  29770. this._renderPipelines = {};
  29771. }
  29772. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  29773. this._renderPipelines[renderPipeline._name] = renderPipeline;
  29774. };
  29775. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  29776. var renderPipeline = this._renderPipelines[renderPipelineName];
  29777. if (!renderPipeline) {
  29778. return;
  29779. }
  29780. renderPipeline._attachCameras(cameras, unique);
  29781. };
  29782. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  29783. var renderPipeline = this._renderPipelines[renderPipelineName];
  29784. if (!renderPipeline) {
  29785. return;
  29786. }
  29787. renderPipeline._detachCameras(cameras);
  29788. };
  29789. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29790. var renderPipeline = this._renderPipelines[renderPipelineName];
  29791. if (!renderPipeline) {
  29792. return;
  29793. }
  29794. renderPipeline._enableEffect(renderEffectName, cameras);
  29795. };
  29796. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29797. var renderPipeline = this._renderPipelines[renderPipelineName];
  29798. if (!renderPipeline) {
  29799. return;
  29800. }
  29801. renderPipeline._disableEffect(renderEffectName, cameras);
  29802. };
  29803. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  29804. var renderPipeline = this._renderPipelines[renderPipelineName];
  29805. if (!renderPipeline) {
  29806. return;
  29807. }
  29808. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  29809. };
  29810. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  29811. var renderPipeline = this._renderPipelines[renderPipelineName];
  29812. if (!renderPipeline) {
  29813. return;
  29814. }
  29815. renderPipeline._disableDisplayOnlyPass(cameras);
  29816. };
  29817. PostProcessRenderPipelineManager.prototype.update = function () {
  29818. for (var renderPipelineName in this._renderPipelines) {
  29819. var pipeline = this._renderPipelines[renderPipelineName];
  29820. if (!pipeline.isSupported) {
  29821. pipeline.dispose();
  29822. delete this._renderPipelines[renderPipelineName];
  29823. }
  29824. else {
  29825. pipeline._update();
  29826. }
  29827. }
  29828. };
  29829. return PostProcessRenderPipelineManager;
  29830. })();
  29831. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  29832. })(BABYLON || (BABYLON = {}));
  29833. var BABYLON;
  29834. (function (BABYLON) {
  29835. var BoundingBoxRenderer = (function () {
  29836. function BoundingBoxRenderer(scene) {
  29837. this.frontColor = new BABYLON.Color3(1, 1, 1);
  29838. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  29839. this.showBackLines = true;
  29840. this.renderList = new BABYLON.SmartArray(32);
  29841. this._scene = scene;
  29842. }
  29843. BoundingBoxRenderer.prototype._prepareRessources = function () {
  29844. if (this._colorShader) {
  29845. return;
  29846. }
  29847. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  29848. attributes: ["position"],
  29849. uniforms: ["worldViewProjection", "color"]
  29850. });
  29851. var engine = this._scene.getEngine();
  29852. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  29853. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  29854. 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]);
  29855. };
  29856. BoundingBoxRenderer.prototype.reset = function () {
  29857. this.renderList.reset();
  29858. };
  29859. BoundingBoxRenderer.prototype.render = function () {
  29860. if (this.renderList.length === 0) {
  29861. return;
  29862. }
  29863. this._prepareRessources();
  29864. if (!this._colorShader.isReady()) {
  29865. return;
  29866. }
  29867. var engine = this._scene.getEngine();
  29868. engine.setDepthWrite(false);
  29869. this._colorShader._preBind();
  29870. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  29871. var boundingBox = this.renderList.data[boundingBoxIndex];
  29872. var min = boundingBox.minimum;
  29873. var max = boundingBox.maximum;
  29874. var diff = max.subtract(min);
  29875. var median = min.add(diff.scale(0.5));
  29876. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  29877. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  29878. .multiply(boundingBox.getWorldMatrix());
  29879. // VBOs
  29880. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  29881. if (this.showBackLines) {
  29882. // Back
  29883. engine.setDepthFunctionToGreaterOrEqual();
  29884. this._scene.resetCachedMaterial();
  29885. this._colorShader.setColor4("color", this.backColor.toColor4());
  29886. this._colorShader.bind(worldMatrix);
  29887. // Draw order
  29888. engine.draw(false, 0, 24);
  29889. }
  29890. // Front
  29891. engine.setDepthFunctionToLess();
  29892. this._scene.resetCachedMaterial();
  29893. this._colorShader.setColor4("color", this.frontColor.toColor4());
  29894. this._colorShader.bind(worldMatrix);
  29895. // Draw order
  29896. engine.draw(false, 0, 24);
  29897. }
  29898. this._colorShader.unbind();
  29899. engine.setDepthFunctionToLessOrEqual();
  29900. engine.setDepthWrite(true);
  29901. };
  29902. BoundingBoxRenderer.prototype.dispose = function () {
  29903. if (!this._colorShader) {
  29904. return;
  29905. }
  29906. this._colorShader.dispose();
  29907. this._vb.dispose();
  29908. this._scene.getEngine()._releaseBuffer(this._ib);
  29909. };
  29910. return BoundingBoxRenderer;
  29911. })();
  29912. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  29913. })(BABYLON || (BABYLON = {}));
  29914. var BABYLON;
  29915. (function (BABYLON) {
  29916. var Condition = (function () {
  29917. function Condition(actionManager) {
  29918. this._actionManager = actionManager;
  29919. }
  29920. Condition.prototype.isValid = function () {
  29921. return true;
  29922. };
  29923. Condition.prototype._getProperty = function (propertyPath) {
  29924. return this._actionManager._getProperty(propertyPath);
  29925. };
  29926. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  29927. return this._actionManager._getEffectiveTarget(target, propertyPath);
  29928. };
  29929. return Condition;
  29930. })();
  29931. BABYLON.Condition = Condition;
  29932. var ValueCondition = (function (_super) {
  29933. __extends(ValueCondition, _super);
  29934. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  29935. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  29936. _super.call(this, actionManager);
  29937. this.propertyPath = propertyPath;
  29938. this.value = value;
  29939. this.operator = operator;
  29940. this._target = this._getEffectiveTarget(target, this.propertyPath);
  29941. this._property = this._getProperty(this.propertyPath);
  29942. }
  29943. Object.defineProperty(ValueCondition, "IsEqual", {
  29944. get: function () {
  29945. return ValueCondition._IsEqual;
  29946. },
  29947. enumerable: true,
  29948. configurable: true
  29949. });
  29950. Object.defineProperty(ValueCondition, "IsDifferent", {
  29951. get: function () {
  29952. return ValueCondition._IsDifferent;
  29953. },
  29954. enumerable: true,
  29955. configurable: true
  29956. });
  29957. Object.defineProperty(ValueCondition, "IsGreater", {
  29958. get: function () {
  29959. return ValueCondition._IsGreater;
  29960. },
  29961. enumerable: true,
  29962. configurable: true
  29963. });
  29964. Object.defineProperty(ValueCondition, "IsLesser", {
  29965. get: function () {
  29966. return ValueCondition._IsLesser;
  29967. },
  29968. enumerable: true,
  29969. configurable: true
  29970. });
  29971. // Methods
  29972. ValueCondition.prototype.isValid = function () {
  29973. switch (this.operator) {
  29974. case ValueCondition.IsGreater:
  29975. return this._target[this._property] > this.value;
  29976. case ValueCondition.IsLesser:
  29977. return this._target[this._property] < this.value;
  29978. case ValueCondition.IsEqual:
  29979. case ValueCondition.IsDifferent:
  29980. var check;
  29981. if (this.value.equals) {
  29982. check = this.value.equals(this._target[this._property]);
  29983. }
  29984. else {
  29985. check = this.value === this._target[this._property];
  29986. }
  29987. return this.operator === ValueCondition.IsEqual ? check : !check;
  29988. }
  29989. return false;
  29990. };
  29991. // Statics
  29992. ValueCondition._IsEqual = 0;
  29993. ValueCondition._IsDifferent = 1;
  29994. ValueCondition._IsGreater = 2;
  29995. ValueCondition._IsLesser = 3;
  29996. return ValueCondition;
  29997. })(Condition);
  29998. BABYLON.ValueCondition = ValueCondition;
  29999. var PredicateCondition = (function (_super) {
  30000. __extends(PredicateCondition, _super);
  30001. function PredicateCondition(actionManager, predicate) {
  30002. _super.call(this, actionManager);
  30003. this.predicate = predicate;
  30004. }
  30005. PredicateCondition.prototype.isValid = function () {
  30006. return this.predicate();
  30007. };
  30008. return PredicateCondition;
  30009. })(Condition);
  30010. BABYLON.PredicateCondition = PredicateCondition;
  30011. var StateCondition = (function (_super) {
  30012. __extends(StateCondition, _super);
  30013. function StateCondition(actionManager, target, value) {
  30014. _super.call(this, actionManager);
  30015. this.value = value;
  30016. this._target = target;
  30017. }
  30018. // Methods
  30019. StateCondition.prototype.isValid = function () {
  30020. return this._target.state === this.value;
  30021. };
  30022. return StateCondition;
  30023. })(Condition);
  30024. BABYLON.StateCondition = StateCondition;
  30025. })(BABYLON || (BABYLON = {}));
  30026. var BABYLON;
  30027. (function (BABYLON) {
  30028. var Action = (function () {
  30029. function Action(triggerOptions, condition) {
  30030. this.triggerOptions = triggerOptions;
  30031. if (triggerOptions.parameter) {
  30032. this.trigger = triggerOptions.trigger;
  30033. this._triggerParameter = triggerOptions.parameter;
  30034. }
  30035. else {
  30036. this.trigger = triggerOptions;
  30037. }
  30038. this._nextActiveAction = this;
  30039. this._condition = condition;
  30040. }
  30041. // Methods
  30042. Action.prototype._prepare = function () {
  30043. };
  30044. Action.prototype.getTriggerParameter = function () {
  30045. return this._triggerParameter;
  30046. };
  30047. Action.prototype._executeCurrent = function (evt) {
  30048. if (this._nextActiveAction._condition) {
  30049. var condition = this._nextActiveAction._condition;
  30050. var currentRenderId = this._actionManager.getScene().getRenderId();
  30051. // We cache the current evaluation for the current frame
  30052. if (condition._evaluationId === currentRenderId) {
  30053. if (!condition._currentResult) {
  30054. return;
  30055. }
  30056. }
  30057. else {
  30058. condition._evaluationId = currentRenderId;
  30059. if (!condition.isValid()) {
  30060. condition._currentResult = false;
  30061. return;
  30062. }
  30063. condition._currentResult = true;
  30064. }
  30065. }
  30066. this._nextActiveAction.execute(evt);
  30067. this.skipToNextActiveAction();
  30068. };
  30069. Action.prototype.execute = function (evt) {
  30070. };
  30071. Action.prototype.skipToNextActiveAction = function () {
  30072. if (this._nextActiveAction._child) {
  30073. if (!this._nextActiveAction._child._actionManager) {
  30074. this._nextActiveAction._child._actionManager = this._actionManager;
  30075. }
  30076. this._nextActiveAction = this._nextActiveAction._child;
  30077. }
  30078. else {
  30079. this._nextActiveAction = this;
  30080. }
  30081. };
  30082. Action.prototype.then = function (action) {
  30083. this._child = action;
  30084. action._actionManager = this._actionManager;
  30085. action._prepare();
  30086. return action;
  30087. };
  30088. Action.prototype._getProperty = function (propertyPath) {
  30089. return this._actionManager._getProperty(propertyPath);
  30090. };
  30091. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  30092. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30093. };
  30094. return Action;
  30095. })();
  30096. BABYLON.Action = Action;
  30097. })(BABYLON || (BABYLON = {}));
  30098. var BABYLON;
  30099. (function (BABYLON) {
  30100. /**
  30101. * ActionEvent is the event beint sent when an action is triggered.
  30102. */
  30103. var ActionEvent = (function () {
  30104. /**
  30105. * @constructor
  30106. * @param source The mesh or sprite that triggered the action.
  30107. * @param pointerX The X mouse cursor position at the time of the event
  30108. * @param pointerY The Y mouse cursor position at the time of the event
  30109. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  30110. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  30111. */
  30112. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  30113. this.source = source;
  30114. this.pointerX = pointerX;
  30115. this.pointerY = pointerY;
  30116. this.meshUnderPointer = meshUnderPointer;
  30117. this.sourceEvent = sourceEvent;
  30118. this.additionalData = additionalData;
  30119. }
  30120. /**
  30121. * Helper function to auto-create an ActionEvent from a source mesh.
  30122. * @param source The source mesh that triggered the event
  30123. * @param evt {Event} The original (browser) event
  30124. */
  30125. ActionEvent.CreateNew = function (source, evt, additionalData) {
  30126. var scene = source.getScene();
  30127. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30128. };
  30129. /**
  30130. * Helper function to auto-create an ActionEvent from a source mesh.
  30131. * @param source The source sprite that triggered the event
  30132. * @param scene Scene associated with the sprite
  30133. * @param evt {Event} The original (browser) event
  30134. */
  30135. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  30136. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30137. };
  30138. /**
  30139. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  30140. * @param scene the scene where the event occurred
  30141. * @param evt {Event} The original (browser) event
  30142. */
  30143. ActionEvent.CreateNewFromScene = function (scene, evt) {
  30144. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  30145. };
  30146. return ActionEvent;
  30147. })();
  30148. BABYLON.ActionEvent = ActionEvent;
  30149. /**
  30150. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  30151. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  30152. */
  30153. var ActionManager = (function () {
  30154. function ActionManager(scene) {
  30155. // Members
  30156. this.actions = new Array();
  30157. this._scene = scene;
  30158. scene._actionManagers.push(this);
  30159. }
  30160. Object.defineProperty(ActionManager, "NothingTrigger", {
  30161. get: function () {
  30162. return ActionManager._NothingTrigger;
  30163. },
  30164. enumerable: true,
  30165. configurable: true
  30166. });
  30167. Object.defineProperty(ActionManager, "OnPickTrigger", {
  30168. get: function () {
  30169. return ActionManager._OnPickTrigger;
  30170. },
  30171. enumerable: true,
  30172. configurable: true
  30173. });
  30174. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  30175. get: function () {
  30176. return ActionManager._OnLeftPickTrigger;
  30177. },
  30178. enumerable: true,
  30179. configurable: true
  30180. });
  30181. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  30182. get: function () {
  30183. return ActionManager._OnRightPickTrigger;
  30184. },
  30185. enumerable: true,
  30186. configurable: true
  30187. });
  30188. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  30189. get: function () {
  30190. return ActionManager._OnCenterPickTrigger;
  30191. },
  30192. enumerable: true,
  30193. configurable: true
  30194. });
  30195. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  30196. get: function () {
  30197. return ActionManager._OnPickDownTrigger;
  30198. },
  30199. enumerable: true,
  30200. configurable: true
  30201. });
  30202. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  30203. get: function () {
  30204. return ActionManager._OnPickUpTrigger;
  30205. },
  30206. enumerable: true,
  30207. configurable: true
  30208. });
  30209. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  30210. /// This trigger will only be raised if you also declared a OnPickDown
  30211. get: function () {
  30212. return ActionManager._OnPickOutTrigger;
  30213. },
  30214. enumerable: true,
  30215. configurable: true
  30216. });
  30217. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  30218. get: function () {
  30219. return ActionManager._OnLongPressTrigger;
  30220. },
  30221. enumerable: true,
  30222. configurable: true
  30223. });
  30224. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  30225. get: function () {
  30226. return ActionManager._OnPointerOverTrigger;
  30227. },
  30228. enumerable: true,
  30229. configurable: true
  30230. });
  30231. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  30232. get: function () {
  30233. return ActionManager._OnPointerOutTrigger;
  30234. },
  30235. enumerable: true,
  30236. configurable: true
  30237. });
  30238. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  30239. get: function () {
  30240. return ActionManager._OnEveryFrameTrigger;
  30241. },
  30242. enumerable: true,
  30243. configurable: true
  30244. });
  30245. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  30246. get: function () {
  30247. return ActionManager._OnIntersectionEnterTrigger;
  30248. },
  30249. enumerable: true,
  30250. configurable: true
  30251. });
  30252. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  30253. get: function () {
  30254. return ActionManager._OnIntersectionExitTrigger;
  30255. },
  30256. enumerable: true,
  30257. configurable: true
  30258. });
  30259. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  30260. get: function () {
  30261. return ActionManager._OnKeyDownTrigger;
  30262. },
  30263. enumerable: true,
  30264. configurable: true
  30265. });
  30266. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  30267. get: function () {
  30268. return ActionManager._OnKeyUpTrigger;
  30269. },
  30270. enumerable: true,
  30271. configurable: true
  30272. });
  30273. // Methods
  30274. ActionManager.prototype.dispose = function () {
  30275. var index = this._scene._actionManagers.indexOf(this);
  30276. if (index > -1) {
  30277. this._scene._actionManagers.splice(index, 1);
  30278. }
  30279. };
  30280. ActionManager.prototype.getScene = function () {
  30281. return this._scene;
  30282. };
  30283. /**
  30284. * Does this action manager handles actions of any of the given triggers
  30285. * @param {number[]} triggers - the triggers to be tested
  30286. * @return {boolean} whether one (or more) of the triggers is handeled
  30287. */
  30288. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  30289. for (var index = 0; index < this.actions.length; index++) {
  30290. var action = this.actions[index];
  30291. if (triggers.indexOf(action.trigger) > -1) {
  30292. return true;
  30293. }
  30294. }
  30295. return false;
  30296. };
  30297. /**
  30298. * Does this action manager handles actions of a given trigger
  30299. * @param {number} trigger - the trigger to be tested
  30300. * @return {boolean} whether the trigger is handeled
  30301. */
  30302. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  30303. for (var index = 0; index < this.actions.length; index++) {
  30304. var action = this.actions[index];
  30305. if (action.trigger === trigger) {
  30306. return true;
  30307. }
  30308. }
  30309. return false;
  30310. };
  30311. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  30312. /**
  30313. * Does this action manager has pointer triggers
  30314. * @return {boolean} whether or not it has pointer triggers
  30315. */
  30316. get: function () {
  30317. for (var index = 0; index < this.actions.length; index++) {
  30318. var action = this.actions[index];
  30319. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  30320. return true;
  30321. }
  30322. }
  30323. return false;
  30324. },
  30325. enumerable: true,
  30326. configurable: true
  30327. });
  30328. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  30329. /**
  30330. * Does this action manager has pick triggers
  30331. * @return {boolean} whether or not it has pick triggers
  30332. */
  30333. get: function () {
  30334. for (var index = 0; index < this.actions.length; index++) {
  30335. var action = this.actions[index];
  30336. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  30337. return true;
  30338. }
  30339. }
  30340. return false;
  30341. },
  30342. enumerable: true,
  30343. configurable: true
  30344. });
  30345. /**
  30346. * Registers an action to this action manager
  30347. * @param {BABYLON.Action} action - the action to be registered
  30348. * @return {BABYLON.Action} the action amended (prepared) after registration
  30349. */
  30350. ActionManager.prototype.registerAction = function (action) {
  30351. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  30352. if (this.getScene().actionManager !== this) {
  30353. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  30354. return null;
  30355. }
  30356. }
  30357. this.actions.push(action);
  30358. action._actionManager = this;
  30359. action._prepare();
  30360. return action;
  30361. };
  30362. /**
  30363. * Process a specific trigger
  30364. * @param {number} trigger - the trigger to process
  30365. * @param evt {BABYLON.ActionEvent} the event details to be processed
  30366. */
  30367. ActionManager.prototype.processTrigger = function (trigger, evt) {
  30368. for (var index = 0; index < this.actions.length; index++) {
  30369. var action = this.actions[index];
  30370. if (action.trigger === trigger) {
  30371. if (trigger === ActionManager.OnKeyUpTrigger
  30372. || trigger === ActionManager.OnKeyDownTrigger) {
  30373. var parameter = action.getTriggerParameter();
  30374. if (parameter) {
  30375. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  30376. var actualkey = String.fromCharCode(unicode).toLowerCase();
  30377. if (actualkey !== parameter.toLowerCase()) {
  30378. continue;
  30379. }
  30380. }
  30381. }
  30382. action._executeCurrent(evt);
  30383. }
  30384. }
  30385. };
  30386. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  30387. var properties = propertyPath.split(".");
  30388. for (var index = 0; index < properties.length - 1; index++) {
  30389. target = target[properties[index]];
  30390. }
  30391. return target;
  30392. };
  30393. ActionManager.prototype._getProperty = function (propertyPath) {
  30394. var properties = propertyPath.split(".");
  30395. return properties[properties.length - 1];
  30396. };
  30397. ActionManager.Parse = function (parsedActions, object, scene) {
  30398. var actionManager = new BABYLON.ActionManager(scene);
  30399. if (object === null)
  30400. scene.actionManager = actionManager;
  30401. else
  30402. object.actionManager = actionManager;
  30403. // instanciate a new object
  30404. var instanciate = function (name, params) {
  30405. var newInstance = Object.create(BABYLON[name].prototype);
  30406. newInstance.constructor.apply(newInstance, params);
  30407. return newInstance;
  30408. };
  30409. var parseParameter = function (name, value, target, propertyPath) {
  30410. if (propertyPath === null) {
  30411. // String, boolean or float
  30412. var floatValue = parseFloat(value);
  30413. if (value === "true" || value === "false")
  30414. return value === "true";
  30415. else
  30416. return isNaN(floatValue) ? value : floatValue;
  30417. }
  30418. var effectiveTarget = propertyPath.split(".");
  30419. var values = value.split(",");
  30420. // Get effective Target
  30421. for (var i = 0; i < effectiveTarget.length; i++) {
  30422. target = target[effectiveTarget[i]];
  30423. }
  30424. // Return appropriate value with its type
  30425. if (typeof (target) === "boolean")
  30426. return values[0] === "true";
  30427. if (typeof (target) === "string")
  30428. return values[0];
  30429. // Parameters with multiple values such as Vector3 etc.
  30430. var split = new Array();
  30431. for (var i = 0; i < values.length; i++)
  30432. split.push(parseFloat(values[i]));
  30433. if (target instanceof BABYLON.Vector3)
  30434. return BABYLON.Vector3.FromArray(split);
  30435. if (target instanceof BABYLON.Vector4)
  30436. return BABYLON.Vector4.FromArray(split);
  30437. if (target instanceof BABYLON.Color3)
  30438. return BABYLON.Color3.FromArray(split);
  30439. if (target instanceof BABYLON.Color4)
  30440. return BABYLON.Color4.FromArray(split);
  30441. return parseFloat(values[0]);
  30442. };
  30443. // traverse graph per trigger
  30444. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  30445. if (combineArray === void 0) { combineArray = null; }
  30446. if (parsedAction.detached)
  30447. return;
  30448. var parameters = new Array();
  30449. var target = null;
  30450. var propertyPath = null;
  30451. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  30452. // Parameters
  30453. if (parsedAction.type === 2)
  30454. parameters.push(actionManager);
  30455. else
  30456. parameters.push(trigger);
  30457. if (combine) {
  30458. var actions = new Array();
  30459. for (var j = 0; j < parsedAction.combine.length; j++) {
  30460. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  30461. }
  30462. parameters.push(actions);
  30463. }
  30464. else {
  30465. for (var i = 0; i < parsedAction.properties.length; i++) {
  30466. var value = parsedAction.properties[i].value;
  30467. var name = parsedAction.properties[i].name;
  30468. var targetType = parsedAction.properties[i].targetType;
  30469. if (name === "target")
  30470. if (targetType !== null && targetType === "SceneProperties")
  30471. value = target = scene;
  30472. else
  30473. value = target = scene.getNodeByName(value);
  30474. else if (name === "parent")
  30475. value = scene.getNodeByName(value);
  30476. else if (name === "sound")
  30477. value = scene.getSoundByName(value);
  30478. else if (name !== "propertyPath") {
  30479. if (parsedAction.type === 2 && name === "operator")
  30480. value = BABYLON.ValueCondition[value];
  30481. else
  30482. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  30483. }
  30484. else {
  30485. propertyPath = value;
  30486. }
  30487. parameters.push(value);
  30488. }
  30489. }
  30490. if (combineArray === null) {
  30491. parameters.push(condition);
  30492. }
  30493. else {
  30494. parameters.push(null);
  30495. }
  30496. // If interpolate value action
  30497. if (parsedAction.name === "InterpolateValueAction") {
  30498. var param = parameters[parameters.length - 2];
  30499. parameters[parameters.length - 1] = param;
  30500. parameters[parameters.length - 2] = condition;
  30501. }
  30502. // Action or condition(s) and not CombineAction
  30503. var newAction = instanciate(parsedAction.name, parameters);
  30504. if (newAction instanceof BABYLON.Condition && condition !== null) {
  30505. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  30506. if (action)
  30507. action.then(nothing);
  30508. else
  30509. actionManager.registerAction(nothing);
  30510. action = nothing;
  30511. }
  30512. if (combineArray === null) {
  30513. if (newAction instanceof BABYLON.Condition) {
  30514. condition = newAction;
  30515. newAction = action;
  30516. }
  30517. else {
  30518. condition = null;
  30519. if (action)
  30520. action.then(newAction);
  30521. else
  30522. actionManager.registerAction(newAction);
  30523. }
  30524. }
  30525. else {
  30526. combineArray.push(newAction);
  30527. }
  30528. for (var i = 0; i < parsedAction.children.length; i++)
  30529. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  30530. };
  30531. // triggers
  30532. for (var i = 0; i < parsedActions.children.length; i++) {
  30533. var triggerParams;
  30534. var trigger = parsedActions.children[i];
  30535. if (trigger.properties.length > 0) {
  30536. var param = trigger.properties[0].value;
  30537. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  30538. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  30539. }
  30540. else
  30541. triggerParams = BABYLON.ActionManager[trigger.name];
  30542. for (var j = 0; j < trigger.children.length; j++) {
  30543. if (!trigger.detached)
  30544. traverse(trigger.children[j], triggerParams, null, null);
  30545. }
  30546. }
  30547. };
  30548. // Statics
  30549. ActionManager._NothingTrigger = 0;
  30550. ActionManager._OnPickTrigger = 1;
  30551. ActionManager._OnLeftPickTrigger = 2;
  30552. ActionManager._OnRightPickTrigger = 3;
  30553. ActionManager._OnCenterPickTrigger = 4;
  30554. ActionManager._OnPickDownTrigger = 5;
  30555. ActionManager._OnPickUpTrigger = 6;
  30556. ActionManager._OnLongPressTrigger = 7;
  30557. ActionManager._OnPointerOverTrigger = 8;
  30558. ActionManager._OnPointerOutTrigger = 9;
  30559. ActionManager._OnEveryFrameTrigger = 10;
  30560. ActionManager._OnIntersectionEnterTrigger = 11;
  30561. ActionManager._OnIntersectionExitTrigger = 12;
  30562. ActionManager._OnKeyDownTrigger = 13;
  30563. ActionManager._OnKeyUpTrigger = 14;
  30564. ActionManager._OnPickOutTrigger = 15;
  30565. ActionManager.DragMovementThreshold = 10; // in pixels
  30566. ActionManager.LongPressDelay = 500; // in milliseconds
  30567. return ActionManager;
  30568. })();
  30569. BABYLON.ActionManager = ActionManager;
  30570. })(BABYLON || (BABYLON = {}));
  30571. var BABYLON;
  30572. (function (BABYLON) {
  30573. var InterpolateValueAction = (function (_super) {
  30574. __extends(InterpolateValueAction, _super);
  30575. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  30576. if (duration === void 0) { duration = 1000; }
  30577. _super.call(this, triggerOptions, condition);
  30578. this.propertyPath = propertyPath;
  30579. this.value = value;
  30580. this.duration = duration;
  30581. this.stopOtherAnimations = stopOtherAnimations;
  30582. this.onInterpolationDone = onInterpolationDone;
  30583. this._target = target;
  30584. }
  30585. InterpolateValueAction.prototype._prepare = function () {
  30586. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30587. this._property = this._getProperty(this.propertyPath);
  30588. };
  30589. InterpolateValueAction.prototype.execute = function () {
  30590. var scene = this._actionManager.getScene();
  30591. var keys = [
  30592. {
  30593. frame: 0,
  30594. value: this._target[this._property]
  30595. }, {
  30596. frame: 100,
  30597. value: this.value
  30598. }
  30599. ];
  30600. var dataType;
  30601. if (typeof this.value === "number") {
  30602. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  30603. }
  30604. else if (this.value instanceof BABYLON.Color3) {
  30605. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  30606. }
  30607. else if (this.value instanceof BABYLON.Vector3) {
  30608. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  30609. }
  30610. else if (this.value instanceof BABYLON.Matrix) {
  30611. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  30612. }
  30613. else if (this.value instanceof BABYLON.Quaternion) {
  30614. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  30615. }
  30616. else {
  30617. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  30618. return;
  30619. }
  30620. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30621. animation.setKeys(keys);
  30622. if (this.stopOtherAnimations) {
  30623. scene.stopAnimation(this._target);
  30624. }
  30625. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  30626. };
  30627. return InterpolateValueAction;
  30628. })(BABYLON.Action);
  30629. BABYLON.InterpolateValueAction = InterpolateValueAction;
  30630. })(BABYLON || (BABYLON = {}));
  30631. var BABYLON;
  30632. (function (BABYLON) {
  30633. var SwitchBooleanAction = (function (_super) {
  30634. __extends(SwitchBooleanAction, _super);
  30635. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  30636. _super.call(this, triggerOptions, condition);
  30637. this.propertyPath = propertyPath;
  30638. this._target = target;
  30639. }
  30640. SwitchBooleanAction.prototype._prepare = function () {
  30641. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30642. this._property = this._getProperty(this.propertyPath);
  30643. };
  30644. SwitchBooleanAction.prototype.execute = function () {
  30645. this._target[this._property] = !this._target[this._property];
  30646. };
  30647. return SwitchBooleanAction;
  30648. })(BABYLON.Action);
  30649. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  30650. var SetStateAction = (function (_super) {
  30651. __extends(SetStateAction, _super);
  30652. function SetStateAction(triggerOptions, target, value, condition) {
  30653. _super.call(this, triggerOptions, condition);
  30654. this.value = value;
  30655. this._target = target;
  30656. }
  30657. SetStateAction.prototype.execute = function () {
  30658. this._target.state = this.value;
  30659. };
  30660. return SetStateAction;
  30661. })(BABYLON.Action);
  30662. BABYLON.SetStateAction = SetStateAction;
  30663. var SetValueAction = (function (_super) {
  30664. __extends(SetValueAction, _super);
  30665. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  30666. _super.call(this, triggerOptions, condition);
  30667. this.propertyPath = propertyPath;
  30668. this.value = value;
  30669. this._target = target;
  30670. }
  30671. SetValueAction.prototype._prepare = function () {
  30672. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30673. this._property = this._getProperty(this.propertyPath);
  30674. };
  30675. SetValueAction.prototype.execute = function () {
  30676. this._target[this._property] = this.value;
  30677. };
  30678. return SetValueAction;
  30679. })(BABYLON.Action);
  30680. BABYLON.SetValueAction = SetValueAction;
  30681. var IncrementValueAction = (function (_super) {
  30682. __extends(IncrementValueAction, _super);
  30683. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  30684. _super.call(this, triggerOptions, condition);
  30685. this.propertyPath = propertyPath;
  30686. this.value = value;
  30687. this._target = target;
  30688. }
  30689. IncrementValueAction.prototype._prepare = function () {
  30690. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30691. this._property = this._getProperty(this.propertyPath);
  30692. if (typeof this._target[this._property] !== "number") {
  30693. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  30694. }
  30695. };
  30696. IncrementValueAction.prototype.execute = function () {
  30697. this._target[this._property] += this.value;
  30698. };
  30699. return IncrementValueAction;
  30700. })(BABYLON.Action);
  30701. BABYLON.IncrementValueAction = IncrementValueAction;
  30702. var PlayAnimationAction = (function (_super) {
  30703. __extends(PlayAnimationAction, _super);
  30704. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  30705. _super.call(this, triggerOptions, condition);
  30706. this.from = from;
  30707. this.to = to;
  30708. this.loop = loop;
  30709. this._target = target;
  30710. }
  30711. PlayAnimationAction.prototype._prepare = function () {
  30712. };
  30713. PlayAnimationAction.prototype.execute = function () {
  30714. var scene = this._actionManager.getScene();
  30715. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  30716. };
  30717. return PlayAnimationAction;
  30718. })(BABYLON.Action);
  30719. BABYLON.PlayAnimationAction = PlayAnimationAction;
  30720. var StopAnimationAction = (function (_super) {
  30721. __extends(StopAnimationAction, _super);
  30722. function StopAnimationAction(triggerOptions, target, condition) {
  30723. _super.call(this, triggerOptions, condition);
  30724. this._target = target;
  30725. }
  30726. StopAnimationAction.prototype._prepare = function () {
  30727. };
  30728. StopAnimationAction.prototype.execute = function () {
  30729. var scene = this._actionManager.getScene();
  30730. scene.stopAnimation(this._target);
  30731. };
  30732. return StopAnimationAction;
  30733. })(BABYLON.Action);
  30734. BABYLON.StopAnimationAction = StopAnimationAction;
  30735. var DoNothingAction = (function (_super) {
  30736. __extends(DoNothingAction, _super);
  30737. function DoNothingAction(triggerOptions, condition) {
  30738. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  30739. _super.call(this, triggerOptions, condition);
  30740. }
  30741. DoNothingAction.prototype.execute = function () {
  30742. };
  30743. return DoNothingAction;
  30744. })(BABYLON.Action);
  30745. BABYLON.DoNothingAction = DoNothingAction;
  30746. var CombineAction = (function (_super) {
  30747. __extends(CombineAction, _super);
  30748. function CombineAction(triggerOptions, children, condition) {
  30749. _super.call(this, triggerOptions, condition);
  30750. this.children = children;
  30751. }
  30752. CombineAction.prototype._prepare = function () {
  30753. for (var index = 0; index < this.children.length; index++) {
  30754. this.children[index]._actionManager = this._actionManager;
  30755. this.children[index]._prepare();
  30756. }
  30757. };
  30758. CombineAction.prototype.execute = function (evt) {
  30759. for (var index = 0; index < this.children.length; index++) {
  30760. this.children[index].execute(evt);
  30761. }
  30762. };
  30763. return CombineAction;
  30764. })(BABYLON.Action);
  30765. BABYLON.CombineAction = CombineAction;
  30766. var ExecuteCodeAction = (function (_super) {
  30767. __extends(ExecuteCodeAction, _super);
  30768. function ExecuteCodeAction(triggerOptions, func, condition) {
  30769. _super.call(this, triggerOptions, condition);
  30770. this.func = func;
  30771. }
  30772. ExecuteCodeAction.prototype.execute = function (evt) {
  30773. this.func(evt);
  30774. };
  30775. return ExecuteCodeAction;
  30776. })(BABYLON.Action);
  30777. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  30778. var SetParentAction = (function (_super) {
  30779. __extends(SetParentAction, _super);
  30780. function SetParentAction(triggerOptions, target, parent, condition) {
  30781. _super.call(this, triggerOptions, condition);
  30782. this._target = target;
  30783. this._parent = parent;
  30784. }
  30785. SetParentAction.prototype._prepare = function () {
  30786. };
  30787. SetParentAction.prototype.execute = function () {
  30788. if (this._target.parent === this._parent) {
  30789. return;
  30790. }
  30791. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  30792. invertParentWorldMatrix.invert();
  30793. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  30794. this._target.parent = this._parent;
  30795. };
  30796. return SetParentAction;
  30797. })(BABYLON.Action);
  30798. BABYLON.SetParentAction = SetParentAction;
  30799. var PlaySoundAction = (function (_super) {
  30800. __extends(PlaySoundAction, _super);
  30801. function PlaySoundAction(triggerOptions, sound, condition) {
  30802. _super.call(this, triggerOptions, condition);
  30803. this._sound = sound;
  30804. }
  30805. PlaySoundAction.prototype._prepare = function () {
  30806. };
  30807. PlaySoundAction.prototype.execute = function () {
  30808. if (this._sound !== undefined)
  30809. this._sound.play();
  30810. };
  30811. return PlaySoundAction;
  30812. })(BABYLON.Action);
  30813. BABYLON.PlaySoundAction = PlaySoundAction;
  30814. var StopSoundAction = (function (_super) {
  30815. __extends(StopSoundAction, _super);
  30816. function StopSoundAction(triggerOptions, sound, condition) {
  30817. _super.call(this, triggerOptions, condition);
  30818. this._sound = sound;
  30819. }
  30820. StopSoundAction.prototype._prepare = function () {
  30821. };
  30822. StopSoundAction.prototype.execute = function () {
  30823. if (this._sound !== undefined)
  30824. this._sound.stop();
  30825. };
  30826. return StopSoundAction;
  30827. })(BABYLON.Action);
  30828. BABYLON.StopSoundAction = StopSoundAction;
  30829. })(BABYLON || (BABYLON = {}));
  30830. var BABYLON;
  30831. (function (BABYLON) {
  30832. var Geometry = (function () {
  30833. function Geometry(id, scene, vertexData, updatable, mesh) {
  30834. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30835. this._totalVertices = 0;
  30836. this._isDisposed = false;
  30837. this.id = id;
  30838. this._engine = scene.getEngine();
  30839. this._meshes = [];
  30840. this._scene = scene;
  30841. //Init vertex buffer cache
  30842. this._vertexBuffers = {};
  30843. this._indices = [];
  30844. // vertexData
  30845. if (vertexData) {
  30846. this.setAllVerticesData(vertexData, updatable);
  30847. }
  30848. else {
  30849. this._totalVertices = 0;
  30850. this._indices = [];
  30851. }
  30852. // applyToMesh
  30853. if (mesh) {
  30854. if (mesh instanceof BABYLON.LinesMesh) {
  30855. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30856. this.updateExtend();
  30857. }
  30858. this.applyToMesh(mesh);
  30859. mesh.computeWorldMatrix(true);
  30860. }
  30861. }
  30862. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30863. /**
  30864. * The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  30865. * @returns The Bias Vector
  30866. */
  30867. get: function () {
  30868. return this._boundingBias;
  30869. },
  30870. set: function (value) {
  30871. if (this._boundingBias && this._boundingBias.equals(value)) {
  30872. return;
  30873. }
  30874. this._boundingBias = value.clone();
  30875. this.updateExtend();
  30876. },
  30877. enumerable: true,
  30878. configurable: true
  30879. });
  30880. Object.defineProperty(Geometry.prototype, "extend", {
  30881. get: function () {
  30882. return this._extend;
  30883. },
  30884. enumerable: true,
  30885. configurable: true
  30886. });
  30887. Geometry.prototype.getScene = function () {
  30888. return this._scene;
  30889. };
  30890. Geometry.prototype.getEngine = function () {
  30891. return this._engine;
  30892. };
  30893. Geometry.prototype.isReady = function () {
  30894. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30895. };
  30896. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30897. vertexData.applyToGeometry(this, updatable);
  30898. this.notifyUpdate();
  30899. };
  30900. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30901. if (this._vertexBuffers[kind]) {
  30902. this._vertexBuffers[kind].dispose();
  30903. }
  30904. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30905. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30906. stride = this._vertexBuffers[kind].getStrideSize();
  30907. this._totalVertices = data.length / stride;
  30908. this.updateExtend(data);
  30909. var meshes = this._meshes;
  30910. var numOfMeshes = meshes.length;
  30911. for (var index = 0; index < numOfMeshes; index++) {
  30912. var mesh = meshes[index];
  30913. mesh._resetPointsArrayCache();
  30914. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30915. mesh._createGlobalSubMesh();
  30916. mesh.computeWorldMatrix(true);
  30917. }
  30918. }
  30919. this.notifyUpdate(kind);
  30920. };
  30921. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30922. var vertexBuffer = this.getVertexBuffer(kind);
  30923. if (!vertexBuffer) {
  30924. return;
  30925. }
  30926. vertexBuffer.updateDirectly(data, offset);
  30927. this.notifyUpdate(kind);
  30928. };
  30929. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30930. var vertexBuffer = this.getVertexBuffer(kind);
  30931. if (!vertexBuffer) {
  30932. return;
  30933. }
  30934. vertexBuffer.update(data);
  30935. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30936. var stride = vertexBuffer.getStrideSize();
  30937. this._totalVertices = data.length / stride;
  30938. if (updateExtends) {
  30939. this.updateExtend(data);
  30940. }
  30941. var meshes = this._meshes;
  30942. var numOfMeshes = meshes.length;
  30943. for (var index = 0; index < numOfMeshes; index++) {
  30944. var mesh = meshes[index];
  30945. mesh._resetPointsArrayCache();
  30946. if (updateExtends) {
  30947. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30948. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30949. var subMesh = mesh.subMeshes[subIndex];
  30950. subMesh.refreshBoundingInfo();
  30951. }
  30952. }
  30953. }
  30954. }
  30955. this.notifyUpdate(kind);
  30956. };
  30957. Geometry.prototype.getTotalVertices = function () {
  30958. if (!this.isReady()) {
  30959. return 0;
  30960. }
  30961. return this._totalVertices;
  30962. };
  30963. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  30964. var vertexBuffer = this.getVertexBuffer(kind);
  30965. if (!vertexBuffer) {
  30966. return null;
  30967. }
  30968. var orig = vertexBuffer.getData();
  30969. if (!copyWhenShared || this._meshes.length === 1) {
  30970. return orig;
  30971. }
  30972. else {
  30973. var len = orig.length;
  30974. var copy = [];
  30975. for (var i = 0; i < len; i++) {
  30976. copy.push(orig[i]);
  30977. }
  30978. return copy;
  30979. }
  30980. };
  30981. Geometry.prototype.getVertexBuffer = function (kind) {
  30982. if (!this.isReady()) {
  30983. return null;
  30984. }
  30985. return this._vertexBuffers[kind];
  30986. };
  30987. Geometry.prototype.getVertexBuffers = function () {
  30988. if (!this.isReady()) {
  30989. return null;
  30990. }
  30991. return this._vertexBuffers;
  30992. };
  30993. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30994. if (!this._vertexBuffers) {
  30995. if (this._delayInfo) {
  30996. return this._delayInfo.indexOf(kind) !== -1;
  30997. }
  30998. return false;
  30999. }
  31000. return this._vertexBuffers[kind] !== undefined;
  31001. };
  31002. Geometry.prototype.getVerticesDataKinds = function () {
  31003. var result = [];
  31004. var kind;
  31005. if (!this._vertexBuffers && this._delayInfo) {
  31006. for (kind in this._delayInfo) {
  31007. result.push(kind);
  31008. }
  31009. }
  31010. else {
  31011. for (kind in this._vertexBuffers) {
  31012. result.push(kind);
  31013. }
  31014. }
  31015. return result;
  31016. };
  31017. Geometry.prototype.setIndices = function (indices, totalVertices) {
  31018. if (this._indexBuffer) {
  31019. this._engine._releaseBuffer(this._indexBuffer);
  31020. }
  31021. this._indices = indices;
  31022. if (this._meshes.length !== 0 && this._indices) {
  31023. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31024. }
  31025. if (totalVertices !== undefined) {
  31026. this._totalVertices = totalVertices;
  31027. }
  31028. var meshes = this._meshes;
  31029. var numOfMeshes = meshes.length;
  31030. for (var index = 0; index < numOfMeshes; index++) {
  31031. meshes[index]._createGlobalSubMesh();
  31032. }
  31033. this.notifyUpdate();
  31034. };
  31035. Geometry.prototype.getTotalIndices = function () {
  31036. if (!this.isReady()) {
  31037. return 0;
  31038. }
  31039. return this._indices.length;
  31040. };
  31041. Geometry.prototype.getIndices = function (copyWhenShared) {
  31042. if (!this.isReady()) {
  31043. return null;
  31044. }
  31045. var orig = this._indices;
  31046. if (!copyWhenShared || this._meshes.length === 1) {
  31047. return orig;
  31048. }
  31049. else {
  31050. var len = orig.length;
  31051. var copy = [];
  31052. for (var i = 0; i < len; i++) {
  31053. copy.push(orig[i]);
  31054. }
  31055. return copy;
  31056. }
  31057. };
  31058. Geometry.prototype.getIndexBuffer = function () {
  31059. if (!this.isReady()) {
  31060. return null;
  31061. }
  31062. return this._indexBuffer;
  31063. };
  31064. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31065. var meshes = this._meshes;
  31066. var index = meshes.indexOf(mesh);
  31067. if (index === -1) {
  31068. return;
  31069. }
  31070. for (var kind in this._vertexBuffers) {
  31071. this._vertexBuffers[kind].dispose();
  31072. }
  31073. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  31074. this._indexBuffer = null;
  31075. }
  31076. meshes.splice(index, 1);
  31077. mesh._geometry = null;
  31078. if (meshes.length === 0 && shouldDispose) {
  31079. this.dispose();
  31080. }
  31081. };
  31082. Geometry.prototype.applyToMesh = function (mesh) {
  31083. if (mesh._geometry === this) {
  31084. return;
  31085. }
  31086. var previousGeometry = mesh._geometry;
  31087. if (previousGeometry) {
  31088. previousGeometry.releaseForMesh(mesh);
  31089. }
  31090. var meshes = this._meshes;
  31091. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31092. mesh._geometry = this;
  31093. this._scene.pushGeometry(this);
  31094. meshes.push(mesh);
  31095. if (this.isReady()) {
  31096. this._applyToMesh(mesh);
  31097. }
  31098. else {
  31099. mesh._boundingInfo = this._boundingInfo;
  31100. }
  31101. };
  31102. Geometry.prototype.updateExtend = function (data) {
  31103. if (data === void 0) { data = null; }
  31104. if (!data) {
  31105. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31106. }
  31107. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
  31108. };
  31109. Geometry.prototype._applyToMesh = function (mesh) {
  31110. var numOfMeshes = this._meshes.length;
  31111. // vertexBuffers
  31112. for (var kind in this._vertexBuffers) {
  31113. if (numOfMeshes === 1) {
  31114. this._vertexBuffers[kind].create();
  31115. }
  31116. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  31117. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31118. mesh._resetPointsArrayCache();
  31119. if (!this._extend) {
  31120. this.updateExtend(this._vertexBuffers[kind].getData());
  31121. }
  31122. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31123. mesh._createGlobalSubMesh();
  31124. //bounding info was just created again, world matrix should be applied again.
  31125. mesh._updateBoundingInfo();
  31126. }
  31127. }
  31128. // indexBuffer
  31129. if (numOfMeshes === 1 && this._indices) {
  31130. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31131. }
  31132. if (this._indexBuffer) {
  31133. this._indexBuffer.references = numOfMeshes;
  31134. }
  31135. };
  31136. Geometry.prototype.notifyUpdate = function (kind) {
  31137. if (this.onGeometryUpdated) {
  31138. this.onGeometryUpdated(this, kind);
  31139. }
  31140. };
  31141. Geometry.prototype.load = function (scene, onLoaded) {
  31142. var _this = this;
  31143. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31144. return;
  31145. }
  31146. if (this.isReady()) {
  31147. if (onLoaded) {
  31148. onLoaded();
  31149. }
  31150. return;
  31151. }
  31152. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31153. scene._addPendingData(this);
  31154. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31155. _this._delayLoadingFunction(JSON.parse(data), _this);
  31156. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31157. _this._delayInfo = [];
  31158. scene._removePendingData(_this);
  31159. var meshes = _this._meshes;
  31160. var numOfMeshes = meshes.length;
  31161. for (var index = 0; index < numOfMeshes; index++) {
  31162. _this._applyToMesh(meshes[index]);
  31163. }
  31164. if (onLoaded) {
  31165. onLoaded();
  31166. }
  31167. }, function () { }, scene.database);
  31168. };
  31169. Geometry.prototype.isDisposed = function () {
  31170. return this._isDisposed;
  31171. };
  31172. Geometry.prototype.dispose = function () {
  31173. var meshes = this._meshes;
  31174. var numOfMeshes = meshes.length;
  31175. var index;
  31176. for (index = 0; index < numOfMeshes; index++) {
  31177. this.releaseForMesh(meshes[index]);
  31178. }
  31179. this._meshes = [];
  31180. for (var kind in this._vertexBuffers) {
  31181. this._vertexBuffers[kind].dispose();
  31182. }
  31183. this._vertexBuffers = [];
  31184. this._totalVertices = 0;
  31185. if (this._indexBuffer) {
  31186. this._engine._releaseBuffer(this._indexBuffer);
  31187. }
  31188. this._indexBuffer = null;
  31189. this._indices = [];
  31190. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31191. this.delayLoadingFile = null;
  31192. this._delayLoadingFunction = null;
  31193. this._delayInfo = [];
  31194. this._boundingInfo = null;
  31195. this._scene.removeGeometry(this);
  31196. this._isDisposed = true;
  31197. };
  31198. Geometry.prototype.copy = function (id) {
  31199. var vertexData = new BABYLON.VertexData();
  31200. vertexData.indices = [];
  31201. var indices = this.getIndices();
  31202. for (var index = 0; index < indices.length; index++) {
  31203. vertexData.indices.push(indices[index]);
  31204. }
  31205. var updatable = false;
  31206. var stopChecking = false;
  31207. var kind;
  31208. for (kind in this._vertexBuffers) {
  31209. // using slice() to make a copy of the array and not just reference it
  31210. var data = this.getVerticesData(kind);
  31211. if (data instanceof Float32Array) {
  31212. vertexData.set(new Float32Array(data), kind);
  31213. }
  31214. else {
  31215. vertexData.set(data.slice(0), kind);
  31216. }
  31217. if (!stopChecking) {
  31218. updatable = this.getVertexBuffer(kind).isUpdatable();
  31219. stopChecking = !updatable;
  31220. }
  31221. }
  31222. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  31223. geometry.delayLoadState = this.delayLoadState;
  31224. geometry.delayLoadingFile = this.delayLoadingFile;
  31225. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31226. for (kind in this._delayInfo) {
  31227. geometry._delayInfo = geometry._delayInfo || [];
  31228. geometry._delayInfo.push(kind);
  31229. }
  31230. // Bounding info
  31231. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31232. return geometry;
  31233. };
  31234. Geometry.prototype.serialize = function () {
  31235. var serializationObject = {};
  31236. serializationObject.id = this.id;
  31237. if (BABYLON.Tags.HasTags(this)) {
  31238. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31239. }
  31240. return serializationObject;
  31241. };
  31242. Geometry.prototype.serializeVerticeData = function () {
  31243. var serializationObject = this.serialize();
  31244. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31245. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31246. }
  31247. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31248. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31249. }
  31250. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31251. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31252. }
  31253. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31254. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  31255. }
  31256. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31257. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  31258. }
  31259. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31260. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  31261. }
  31262. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31263. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  31264. }
  31265. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31266. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  31267. }
  31268. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31269. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31270. }
  31271. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31272. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31273. serializationObject.matricesIndices._isExpanded = true;
  31274. }
  31275. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31276. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31277. }
  31278. serializationObject.indices = this.getIndices();
  31279. return serializationObject;
  31280. };
  31281. // Statics
  31282. Geometry.ExtractFromMesh = function (mesh, id) {
  31283. var geometry = mesh._geometry;
  31284. if (!geometry) {
  31285. return null;
  31286. }
  31287. return geometry.copy(id);
  31288. };
  31289. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31290. // be aware Math.random() could cause collisions
  31291. Geometry.RandomId = function () {
  31292. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  31293. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  31294. return v.toString(16);
  31295. });
  31296. };
  31297. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31298. var scene = mesh.getScene();
  31299. // Geometry
  31300. var geometryId = parsedGeometry.geometryId;
  31301. if (geometryId) {
  31302. var geometry = scene.getGeometryByID(geometryId);
  31303. if (geometry) {
  31304. geometry.applyToMesh(mesh);
  31305. }
  31306. }
  31307. else if (parsedGeometry instanceof ArrayBuffer) {
  31308. var binaryInfo = mesh._binaryInfo;
  31309. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31310. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31311. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31312. }
  31313. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31314. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31315. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31316. }
  31317. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31318. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31319. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31320. }
  31321. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31322. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31323. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31324. }
  31325. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31326. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31327. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31328. }
  31329. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31330. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31331. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31332. }
  31333. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31334. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31335. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31336. }
  31337. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31338. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31339. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31340. }
  31341. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31342. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31343. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31344. }
  31345. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31346. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31347. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31348. }
  31349. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31350. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31351. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31352. }
  31353. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31354. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31355. mesh.setIndices(indicesData);
  31356. }
  31357. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31358. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31359. mesh.subMeshes = [];
  31360. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31361. var materialIndex = subMeshesData[(i * 5) + 0];
  31362. var verticesStart = subMeshesData[(i * 5) + 1];
  31363. var verticesCount = subMeshesData[(i * 5) + 2];
  31364. var indexStart = subMeshesData[(i * 5) + 3];
  31365. var indexCount = subMeshesData[(i * 5) + 4];
  31366. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31367. }
  31368. }
  31369. }
  31370. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31371. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  31372. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  31373. if (parsedGeometry.uvs) {
  31374. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  31375. }
  31376. if (parsedGeometry.uvs2) {
  31377. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  31378. }
  31379. if (parsedGeometry.uvs3) {
  31380. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  31381. }
  31382. if (parsedGeometry.uvs4) {
  31383. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  31384. }
  31385. if (parsedGeometry.uvs5) {
  31386. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  31387. }
  31388. if (parsedGeometry.uvs6) {
  31389. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  31390. }
  31391. if (parsedGeometry.colors) {
  31392. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  31393. }
  31394. if (parsedGeometry.matricesIndices) {
  31395. if (!parsedGeometry.matricesIndices._isExpanded) {
  31396. var floatIndices = [];
  31397. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31398. var matricesIndex = parsedGeometry.matricesIndices[i];
  31399. floatIndices.push(matricesIndex & 0x000000FF);
  31400. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31401. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31402. floatIndices.push(matricesIndex >> 24);
  31403. }
  31404. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  31405. }
  31406. else {
  31407. delete parsedGeometry.matricesIndices._isExpanded;
  31408. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  31409. }
  31410. }
  31411. if (parsedGeometry.matricesIndicesExtra) {
  31412. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31413. var floatIndices = [];
  31414. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31415. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31416. floatIndices.push(matricesIndex & 0x000000FF);
  31417. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31418. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31419. floatIndices.push(matricesIndex >> 24);
  31420. }
  31421. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  31422. }
  31423. else {
  31424. delete parsedGeometry.matricesIndices._isExpanded;
  31425. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  31426. }
  31427. }
  31428. if (parsedGeometry.matricesWeights) {
  31429. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  31430. }
  31431. if (parsedGeometry.matricesWeightsExtra) {
  31432. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  31433. }
  31434. mesh.setIndices(parsedGeometry.indices);
  31435. }
  31436. // SubMeshes
  31437. if (parsedGeometry.subMeshes) {
  31438. mesh.subMeshes = [];
  31439. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31440. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31441. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31442. }
  31443. }
  31444. // Flat shading
  31445. if (mesh._shouldGenerateFlatShading) {
  31446. mesh.convertToFlatShadedMesh();
  31447. delete mesh._shouldGenerateFlatShading;
  31448. }
  31449. // Update
  31450. mesh.computeWorldMatrix(true);
  31451. // Octree
  31452. if (scene['_selectionOctree']) {
  31453. scene['_selectionOctree'].addMesh(mesh);
  31454. }
  31455. };
  31456. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31457. if (scene.getGeometryByID(parsedVertexData.id)) {
  31458. return null; // null since geometry could be something else than a box...
  31459. }
  31460. var geometry = new Geometry(parsedVertexData.id, scene);
  31461. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31462. if (parsedVertexData.delayLoadingFile) {
  31463. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31464. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31465. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31466. geometry._delayInfo = [];
  31467. if (parsedVertexData.hasUVs) {
  31468. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31469. }
  31470. if (parsedVertexData.hasUVs2) {
  31471. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31472. }
  31473. if (parsedVertexData.hasUVs3) {
  31474. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31475. }
  31476. if (parsedVertexData.hasUVs4) {
  31477. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31478. }
  31479. if (parsedVertexData.hasUVs5) {
  31480. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31481. }
  31482. if (parsedVertexData.hasUVs6) {
  31483. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31484. }
  31485. if (parsedVertexData.hasColors) {
  31486. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31487. }
  31488. if (parsedVertexData.hasMatricesIndices) {
  31489. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31490. }
  31491. if (parsedVertexData.hasMatricesWeights) {
  31492. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31493. }
  31494. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31495. }
  31496. else {
  31497. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31498. }
  31499. scene.pushGeometry(geometry, true);
  31500. return geometry;
  31501. };
  31502. return Geometry;
  31503. })();
  31504. BABYLON.Geometry = Geometry;
  31505. /////// Primitives //////////////////////////////////////////////
  31506. var Geometry;
  31507. (function (Geometry) {
  31508. var Primitives;
  31509. (function (Primitives) {
  31510. /// Abstract class
  31511. var _Primitive = (function (_super) {
  31512. __extends(_Primitive, _super);
  31513. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31514. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  31515. this._canBeRegenerated = _canBeRegenerated;
  31516. this._beingRegenerated = true;
  31517. this.regenerate();
  31518. this._beingRegenerated = false;
  31519. }
  31520. _Primitive.prototype.canBeRegenerated = function () {
  31521. return this._canBeRegenerated;
  31522. };
  31523. _Primitive.prototype.regenerate = function () {
  31524. if (!this._canBeRegenerated) {
  31525. return;
  31526. }
  31527. this._beingRegenerated = true;
  31528. this.setAllVerticesData(this._regenerateVertexData(), false);
  31529. this._beingRegenerated = false;
  31530. };
  31531. _Primitive.prototype.asNewGeometry = function (id) {
  31532. return _super.prototype.copy.call(this, id);
  31533. };
  31534. // overrides
  31535. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31536. if (!this._beingRegenerated) {
  31537. return;
  31538. }
  31539. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31540. };
  31541. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31542. if (!this._beingRegenerated) {
  31543. return;
  31544. }
  31545. _super.prototype.setVerticesData.call(this, kind, data, false);
  31546. };
  31547. // to override
  31548. // protected
  31549. _Primitive.prototype._regenerateVertexData = function () {
  31550. throw new Error("Abstract method");
  31551. };
  31552. _Primitive.prototype.copy = function (id) {
  31553. throw new Error("Must be overriden in sub-classes.");
  31554. };
  31555. _Primitive.prototype.serialize = function () {
  31556. var serializationObject = _super.prototype.serialize.call(this);
  31557. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31558. return serializationObject;
  31559. };
  31560. return _Primitive;
  31561. })(Geometry);
  31562. Primitives._Primitive = _Primitive;
  31563. var Ribbon = (function (_super) {
  31564. __extends(Ribbon, _super);
  31565. // Members
  31566. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31567. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31568. _super.call(this, id, scene, canBeRegenerated, mesh);
  31569. this.pathArray = pathArray;
  31570. this.closeArray = closeArray;
  31571. this.closePath = closePath;
  31572. this.offset = offset;
  31573. this.side = side;
  31574. }
  31575. Ribbon.prototype._regenerateVertexData = function () {
  31576. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31577. };
  31578. Ribbon.prototype.copy = function (id) {
  31579. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  31580. };
  31581. return Ribbon;
  31582. })(_Primitive);
  31583. Primitives.Ribbon = Ribbon;
  31584. var Box = (function (_super) {
  31585. __extends(Box, _super);
  31586. // Members
  31587. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31588. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31589. _super.call(this, id, scene, canBeRegenerated, mesh);
  31590. this.size = size;
  31591. this.side = side;
  31592. }
  31593. Box.prototype._regenerateVertexData = function () {
  31594. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31595. };
  31596. Box.prototype.copy = function (id) {
  31597. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31598. };
  31599. Box.prototype.serialize = function () {
  31600. var serializationObject = _super.prototype.serialize.call(this);
  31601. serializationObject.size = this.size;
  31602. return serializationObject;
  31603. };
  31604. Box.Parse = function (parsedBox, scene) {
  31605. if (scene.getGeometryByID(parsedBox.id)) {
  31606. return null; // null since geometry could be something else than a box...
  31607. }
  31608. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31609. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31610. scene.pushGeometry(box, true);
  31611. return box;
  31612. };
  31613. return Box;
  31614. })(_Primitive);
  31615. Primitives.Box = Box;
  31616. var Sphere = (function (_super) {
  31617. __extends(Sphere, _super);
  31618. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31619. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31620. _super.call(this, id, scene, canBeRegenerated, mesh);
  31621. this.segments = segments;
  31622. this.diameter = diameter;
  31623. this.side = side;
  31624. }
  31625. Sphere.prototype._regenerateVertexData = function () {
  31626. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31627. };
  31628. Sphere.prototype.copy = function (id) {
  31629. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31630. };
  31631. Sphere.prototype.serialize = function () {
  31632. var serializationObject = _super.prototype.serialize.call(this);
  31633. serializationObject.segments = this.segments;
  31634. serializationObject.diameter = this.diameter;
  31635. return serializationObject;
  31636. };
  31637. Sphere.Parse = function (parsedSphere, scene) {
  31638. if (scene.getGeometryByID(parsedSphere.id)) {
  31639. return null; // null since geometry could be something else than a sphere...
  31640. }
  31641. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31642. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31643. scene.pushGeometry(sphere, true);
  31644. return sphere;
  31645. };
  31646. return Sphere;
  31647. })(_Primitive);
  31648. Primitives.Sphere = Sphere;
  31649. var Disc = (function (_super) {
  31650. __extends(Disc, _super);
  31651. // Members
  31652. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31653. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31654. _super.call(this, id, scene, canBeRegenerated, mesh);
  31655. this.radius = radius;
  31656. this.tessellation = tessellation;
  31657. this.side = side;
  31658. }
  31659. Disc.prototype._regenerateVertexData = function () {
  31660. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31661. };
  31662. Disc.prototype.copy = function (id) {
  31663. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31664. };
  31665. return Disc;
  31666. })(_Primitive);
  31667. Primitives.Disc = Disc;
  31668. var Cylinder = (function (_super) {
  31669. __extends(Cylinder, _super);
  31670. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31671. if (subdivisions === void 0) { subdivisions = 1; }
  31672. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31673. _super.call(this, id, scene, canBeRegenerated, mesh);
  31674. this.height = height;
  31675. this.diameterTop = diameterTop;
  31676. this.diameterBottom = diameterBottom;
  31677. this.tessellation = tessellation;
  31678. this.subdivisions = subdivisions;
  31679. this.side = side;
  31680. }
  31681. Cylinder.prototype._regenerateVertexData = function () {
  31682. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31683. };
  31684. Cylinder.prototype.copy = function (id) {
  31685. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31686. };
  31687. Cylinder.prototype.serialize = function () {
  31688. var serializationObject = _super.prototype.serialize.call(this);
  31689. serializationObject.height = this.height;
  31690. serializationObject.diameterTop = this.diameterTop;
  31691. serializationObject.diameterBottom = this.diameterBottom;
  31692. serializationObject.tessellation = this.tessellation;
  31693. return serializationObject;
  31694. };
  31695. Cylinder.Parse = function (parsedCylinder, scene) {
  31696. if (scene.getGeometryByID(parsedCylinder.id)) {
  31697. return null; // null since geometry could be something else than a cylinder...
  31698. }
  31699. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31700. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31701. scene.pushGeometry(cylinder, true);
  31702. return cylinder;
  31703. };
  31704. return Cylinder;
  31705. })(_Primitive);
  31706. Primitives.Cylinder = Cylinder;
  31707. var Torus = (function (_super) {
  31708. __extends(Torus, _super);
  31709. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31710. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31711. _super.call(this, id, scene, canBeRegenerated, mesh);
  31712. this.diameter = diameter;
  31713. this.thickness = thickness;
  31714. this.tessellation = tessellation;
  31715. this.side = side;
  31716. }
  31717. Torus.prototype._regenerateVertexData = function () {
  31718. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31719. };
  31720. Torus.prototype.copy = function (id) {
  31721. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31722. };
  31723. Torus.prototype.serialize = function () {
  31724. var serializationObject = _super.prototype.serialize.call(this);
  31725. serializationObject.diameter = this.diameter;
  31726. serializationObject.thickness = this.thickness;
  31727. serializationObject.tessellation = this.tessellation;
  31728. return serializationObject;
  31729. };
  31730. Torus.Parse = function (parsedTorus, scene) {
  31731. if (scene.getGeometryByID(parsedTorus.id)) {
  31732. return null; // null since geometry could be something else than a torus...
  31733. }
  31734. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31735. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31736. scene.pushGeometry(torus, true);
  31737. return torus;
  31738. };
  31739. return Torus;
  31740. })(_Primitive);
  31741. Primitives.Torus = Torus;
  31742. var Ground = (function (_super) {
  31743. __extends(Ground, _super);
  31744. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31745. _super.call(this, id, scene, canBeRegenerated, mesh);
  31746. this.width = width;
  31747. this.height = height;
  31748. this.subdivisions = subdivisions;
  31749. }
  31750. Ground.prototype._regenerateVertexData = function () {
  31751. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31752. };
  31753. Ground.prototype.copy = function (id) {
  31754. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31755. };
  31756. Ground.prototype.serialize = function () {
  31757. var serializationObject = _super.prototype.serialize.call(this);
  31758. serializationObject.width = this.width;
  31759. serializationObject.height = this.height;
  31760. serializationObject.subdivisions = this.subdivisions;
  31761. return serializationObject;
  31762. };
  31763. Ground.Parse = function (parsedGround, scene) {
  31764. if (scene.getGeometryByID(parsedGround.id)) {
  31765. return null; // null since geometry could be something else than a ground...
  31766. }
  31767. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31768. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31769. scene.pushGeometry(ground, true);
  31770. return ground;
  31771. };
  31772. return Ground;
  31773. })(_Primitive);
  31774. Primitives.Ground = Ground;
  31775. var TiledGround = (function (_super) {
  31776. __extends(TiledGround, _super);
  31777. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31778. _super.call(this, id, scene, canBeRegenerated, mesh);
  31779. this.xmin = xmin;
  31780. this.zmin = zmin;
  31781. this.xmax = xmax;
  31782. this.zmax = zmax;
  31783. this.subdivisions = subdivisions;
  31784. this.precision = precision;
  31785. }
  31786. TiledGround.prototype._regenerateVertexData = function () {
  31787. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31788. };
  31789. TiledGround.prototype.copy = function (id) {
  31790. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31791. };
  31792. return TiledGround;
  31793. })(_Primitive);
  31794. Primitives.TiledGround = TiledGround;
  31795. var Plane = (function (_super) {
  31796. __extends(Plane, _super);
  31797. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31798. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31799. _super.call(this, id, scene, canBeRegenerated, mesh);
  31800. this.size = size;
  31801. this.side = side;
  31802. }
  31803. Plane.prototype._regenerateVertexData = function () {
  31804. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31805. };
  31806. Plane.prototype.copy = function (id) {
  31807. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31808. };
  31809. Plane.prototype.serialize = function () {
  31810. var serializationObject = _super.prototype.serialize.call(this);
  31811. serializationObject.size = this.size;
  31812. return serializationObject;
  31813. };
  31814. Plane.Parse = function (parsedPlane, scene) {
  31815. if (scene.getGeometryByID(parsedPlane.id)) {
  31816. return null; // null since geometry could be something else than a ground...
  31817. }
  31818. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31819. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31820. scene.pushGeometry(plane, true);
  31821. return plane;
  31822. };
  31823. return Plane;
  31824. })(_Primitive);
  31825. Primitives.Plane = Plane;
  31826. var TorusKnot = (function (_super) {
  31827. __extends(TorusKnot, _super);
  31828. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31829. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31830. _super.call(this, id, scene, canBeRegenerated, mesh);
  31831. this.radius = radius;
  31832. this.tube = tube;
  31833. this.radialSegments = radialSegments;
  31834. this.tubularSegments = tubularSegments;
  31835. this.p = p;
  31836. this.q = q;
  31837. this.side = side;
  31838. }
  31839. TorusKnot.prototype._regenerateVertexData = function () {
  31840. 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 });
  31841. };
  31842. TorusKnot.prototype.copy = function (id) {
  31843. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31844. };
  31845. TorusKnot.prototype.serialize = function () {
  31846. var serializationObject = _super.prototype.serialize.call(this);
  31847. serializationObject.radius = this.radius;
  31848. serializationObject.tube = this.tube;
  31849. serializationObject.radialSegments = this.radialSegments;
  31850. serializationObject.tubularSegments = this.tubularSegments;
  31851. serializationObject.p = this.p;
  31852. serializationObject.q = this.q;
  31853. return serializationObject;
  31854. };
  31855. ;
  31856. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31857. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31858. return null; // null since geometry could be something else than a ground...
  31859. }
  31860. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31861. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31862. scene.pushGeometry(torusKnot, true);
  31863. return torusKnot;
  31864. };
  31865. return TorusKnot;
  31866. })(_Primitive);
  31867. Primitives.TorusKnot = TorusKnot;
  31868. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31869. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31870. })(BABYLON || (BABYLON = {}));
  31871. var BABYLON;
  31872. (function (BABYLON) {
  31873. var GroundMesh = (function (_super) {
  31874. __extends(GroundMesh, _super);
  31875. function GroundMesh(name, scene) {
  31876. _super.call(this, name, scene);
  31877. this.generateOctree = false;
  31878. this._worldInverse = new BABYLON.Matrix();
  31879. }
  31880. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  31881. get: function () {
  31882. return this._subdivisions;
  31883. },
  31884. enumerable: true,
  31885. configurable: true
  31886. });
  31887. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  31888. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  31889. this._subdivisions = chunksCount;
  31890. this.subdivide(this._subdivisions);
  31891. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  31892. };
  31893. /**
  31894. * Returns a height (y) value in the Worl system :
  31895. * the ground altitude at the coordinates (x, z) expressed in the World system.
  31896. * Returns the ground y position if (x, z) are outside the ground surface.
  31897. * Not pertinent if the ground is rotated.
  31898. */
  31899. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  31900. // express x and y in the ground local system
  31901. x -= this.position.x;
  31902. z -= this.position.z;
  31903. x /= this.scaling.x;
  31904. z /= this.scaling.z;
  31905. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31906. return this.position.y;
  31907. }
  31908. if (!this._heightQuads || this._heightQuads.length == 0) {
  31909. this._initHeightQuads();
  31910. this._computeHeightQuads();
  31911. }
  31912. var facet = this._getFacetAt(x, z);
  31913. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  31914. // return y in the World system
  31915. return y * this.scaling.y + this.position.y;
  31916. };
  31917. /**
  31918. * Returns a normalized vector (Vector3) orthogonal to the ground
  31919. * at the ground coordinates (x, z) expressed in the World system.
  31920. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  31921. * Not pertinent if the ground is rotated.
  31922. */
  31923. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  31924. var normal = new BABYLON.Vector3(0, 1, 0);
  31925. this.getNormalAtCoordinatesToRef(x, z, normal);
  31926. return normal;
  31927. };
  31928. /**
  31929. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  31930. * at the ground coordinates (x, z) expressed in the World system.
  31931. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  31932. * Not pertinent if the ground is rotated.
  31933. */
  31934. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  31935. // express x and y in the ground local system
  31936. x -= this.position.x;
  31937. z -= this.position.z;
  31938. x /= this.scaling.x;
  31939. z /= this.scaling.z;
  31940. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31941. return;
  31942. }
  31943. if (!this._heightQuads || this._heightQuads.length == 0) {
  31944. this._initHeightQuads();
  31945. this._computeHeightQuads();
  31946. }
  31947. var facet = this._getFacetAt(x, z);
  31948. ref.x = facet.x;
  31949. ref.y = facet.y;
  31950. ref.z = facet.z;
  31951. };
  31952. /**
  31953. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  31954. * if the ground has been updated.
  31955. * This can be used in the render loop
  31956. */
  31957. GroundMesh.prototype.updateCoordinateHeights = function () {
  31958. if (!this._heightQuads || this._heightQuads.length == 0) {
  31959. this._initHeightQuads();
  31960. }
  31961. this._computeHeightQuads();
  31962. };
  31963. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  31964. GroundMesh.prototype._getFacetAt = function (x, z) {
  31965. // retrieve col and row from x, z coordinates in the ground local system
  31966. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  31967. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  31968. var quad = this._heightQuads[row * this._subdivisions + col];
  31969. var facet;
  31970. if (z < quad.slope.x * x + quad.slope.y) {
  31971. facet = quad.facet1;
  31972. }
  31973. else {
  31974. facet = quad.facet2;
  31975. }
  31976. return facet;
  31977. };
  31978. // Creates and populates the heightMap array with "facet" elements :
  31979. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  31980. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  31981. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  31982. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  31983. GroundMesh.prototype._initHeightQuads = function () {
  31984. this._heightQuads = new Array();
  31985. for (var row = 0; row < this._subdivisions; row++) {
  31986. for (var col = 0; col < this._subdivisions; col++) {
  31987. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  31988. this._heightQuads[row * this._subdivisions + col] = quad;
  31989. }
  31990. }
  31991. };
  31992. // Compute each quad element values and update the the heightMap array :
  31993. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  31994. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  31995. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  31996. GroundMesh.prototype._computeHeightQuads = function () {
  31997. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31998. var v1 = BABYLON.Tmp.Vector3[0];
  31999. var v2 = BABYLON.Tmp.Vector3[1];
  32000. var v3 = BABYLON.Tmp.Vector3[2];
  32001. var v4 = BABYLON.Tmp.Vector3[3];
  32002. var v1v2 = BABYLON.Tmp.Vector3[4];
  32003. var v1v3 = BABYLON.Tmp.Vector3[5];
  32004. var v1v4 = BABYLON.Tmp.Vector3[6];
  32005. var norm1 = BABYLON.Tmp.Vector3[7];
  32006. var norm2 = BABYLON.Tmp.Vector3[8];
  32007. var i = 0;
  32008. var j = 0;
  32009. var k = 0;
  32010. var cd = 0; // 2D slope coefficient : z = cd * x + h
  32011. var h = 0;
  32012. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  32013. var d2 = 0;
  32014. for (var row = 0; row < this._subdivisions; row++) {
  32015. for (var col = 0; col < this._subdivisions; col++) {
  32016. i = col * 3;
  32017. j = row * (this._subdivisions + 1) * 3;
  32018. k = (row + 1) * (this._subdivisions + 1) * 3;
  32019. v1.x = positions[j + i];
  32020. v1.y = positions[j + i + 1];
  32021. v1.z = positions[j + i + 2];
  32022. v2.x = positions[j + i + 3];
  32023. v2.y = positions[j + i + 4];
  32024. v2.z = positions[j + i + 5];
  32025. v3.x = positions[k + i];
  32026. v3.y = positions[k + i + 1];
  32027. v3.z = positions[k + i + 2];
  32028. v4.x = positions[k + i + 3];
  32029. v4.y = positions[k + i + 4];
  32030. v4.z = positions[k + i + 5];
  32031. // 2D slope V1V4
  32032. cd = (v4.z - v1.z) / (v4.x - v1.x);
  32033. h = v1.z - cd * v1.x; // v1 belongs to the slope
  32034. // facet equations :
  32035. // we compute each facet normal vector
  32036. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  32037. // we compute the value d by applying the equation to v1 which belongs to the plane
  32038. // then we store the facet equation in a Vector4
  32039. v2.subtractToRef(v1, v1v2);
  32040. v3.subtractToRef(v1, v1v3);
  32041. v4.subtractToRef(v1, v1v4);
  32042. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  32043. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  32044. norm1.normalize();
  32045. norm2.normalize();
  32046. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  32047. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  32048. var quad = this._heightQuads[row * this._subdivisions + col];
  32049. quad.slope.copyFromFloats(cd, h);
  32050. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  32051. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  32052. }
  32053. }
  32054. };
  32055. return GroundMesh;
  32056. })(BABYLON.Mesh);
  32057. BABYLON.GroundMesh = GroundMesh;
  32058. })(BABYLON || (BABYLON = {}));
  32059. var BABYLON;
  32060. (function (BABYLON) {
  32061. var LinesMesh = (function (_super) {
  32062. __extends(LinesMesh, _super);
  32063. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  32064. if (parent === void 0) { parent = null; }
  32065. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  32066. this.color = new BABYLON.Color3(1, 1, 1);
  32067. this.alpha = 1;
  32068. this._intersectionThreshold = 0.1;
  32069. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  32070. attributes: ["position"],
  32071. uniforms: ["worldViewProjection", "color"],
  32072. needAlphaBlending: true
  32073. });
  32074. }
  32075. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  32076. /**
  32077. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32078. * This margin is expressed in world space coordinates, so its value may vary.
  32079. * Default value is 0.1
  32080. * @returns the intersection Threshold value.
  32081. */
  32082. get: function () {
  32083. return this._intersectionThreshold;
  32084. },
  32085. /**
  32086. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32087. * This margin is expressed in world space coordinates, so its value may vary.
  32088. * @param value the new threshold to apply
  32089. */
  32090. set: function (value) {
  32091. if (this._intersectionThreshold === value) {
  32092. return;
  32093. }
  32094. this._intersectionThreshold = value;
  32095. if (this.geometry) {
  32096. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  32097. }
  32098. },
  32099. enumerable: true,
  32100. configurable: true
  32101. });
  32102. Object.defineProperty(LinesMesh.prototype, "material", {
  32103. get: function () {
  32104. return this._colorShader;
  32105. },
  32106. enumerable: true,
  32107. configurable: true
  32108. });
  32109. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  32110. get: function () {
  32111. return true;
  32112. },
  32113. enumerable: true,
  32114. configurable: true
  32115. });
  32116. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  32117. get: function () {
  32118. return false;
  32119. },
  32120. enumerable: true,
  32121. configurable: true
  32122. });
  32123. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  32124. var engine = this.getScene().getEngine();
  32125. var indexToBind = this._geometry.getIndexBuffer();
  32126. // VBOs
  32127. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  32128. // Color
  32129. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  32130. };
  32131. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  32132. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  32133. return;
  32134. }
  32135. var engine = this.getScene().getEngine();
  32136. // Draw order
  32137. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  32138. };
  32139. LinesMesh.prototype.dispose = function (doNotRecurse) {
  32140. this._colorShader.dispose();
  32141. _super.prototype.dispose.call(this, doNotRecurse);
  32142. };
  32143. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  32144. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  32145. };
  32146. return LinesMesh;
  32147. })(BABYLON.Mesh);
  32148. BABYLON.LinesMesh = LinesMesh;
  32149. })(BABYLON || (BABYLON = {}));
  32150. var BABYLON;
  32151. (function (BABYLON) {
  32152. var DebugLayer = (function () {
  32153. function DebugLayer(scene) {
  32154. var _this = this;
  32155. this._transformationMatrix = BABYLON.Matrix.Identity();
  32156. this._enabled = false;
  32157. this._labelsEnabled = false;
  32158. this._displayStatistics = true;
  32159. this._displayTree = false;
  32160. this._displayLogs = false;
  32161. this._skeletonViewers = new Array();
  32162. this._identityMatrix = BABYLON.Matrix.Identity();
  32163. this.axisRatio = 0.02;
  32164. this.accentColor = "orange";
  32165. this._scene = scene;
  32166. this._syncPositions = function () {
  32167. var engine = _this._scene.getEngine();
  32168. var canvasRect = engine.getRenderingCanvasClientRect();
  32169. if (_this._showUI) {
  32170. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  32171. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  32172. _this._statsDiv.style.width = "400px";
  32173. _this._statsDiv.style.height = "auto";
  32174. _this._statsSubsetDiv.style.maxHeight = "240px";
  32175. _this._optionsDiv.style.left = "0px";
  32176. _this._optionsDiv.style.top = "10px";
  32177. _this._optionsDiv.style.width = "200px";
  32178. _this._optionsDiv.style.height = "auto";
  32179. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  32180. _this._logDiv.style.left = "0px";
  32181. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  32182. _this._logDiv.style.width = "600px";
  32183. _this._logDiv.style.height = "160px";
  32184. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  32185. _this._treeDiv.style.top = "10px";
  32186. _this._treeDiv.style.width = "300px";
  32187. _this._treeDiv.style.height = "auto";
  32188. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  32189. }
  32190. _this._globalDiv.style.left = canvasRect.left + "px";
  32191. _this._globalDiv.style.top = canvasRect.top + "px";
  32192. _this._drawingCanvas.style.left = "0px";
  32193. _this._drawingCanvas.style.top = "0px";
  32194. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  32195. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  32196. var devicePixelRatio = window.devicePixelRatio || 1;
  32197. var context = _this._drawingContext;
  32198. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  32199. context.mozBackingStorePixelRatio ||
  32200. context.msBackingStorePixelRatio ||
  32201. context.oBackingStorePixelRatio ||
  32202. context.backingStorePixelRatio || 1;
  32203. _this._ratio = devicePixelRatio / backingStoreRatio;
  32204. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  32205. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  32206. };
  32207. this._onCanvasClick = function (evt) {
  32208. _this._clickPosition = {
  32209. x: evt.clientX * _this._ratio,
  32210. y: evt.clientY * _this._ratio
  32211. };
  32212. };
  32213. this._syncUI = function () {
  32214. if (_this._showUI) {
  32215. if (_this._displayStatistics) {
  32216. _this._displayStats();
  32217. _this._statsDiv.style.display = "";
  32218. }
  32219. else {
  32220. _this._statsDiv.style.display = "none";
  32221. }
  32222. if (_this._displayLogs) {
  32223. _this._logDiv.style.display = "";
  32224. }
  32225. else {
  32226. _this._logDiv.style.display = "none";
  32227. }
  32228. if (_this._displayTree) {
  32229. _this._treeDiv.style.display = "";
  32230. if (_this._needToRefreshMeshesTree) {
  32231. _this._needToRefreshMeshesTree = false;
  32232. _this._refreshMeshesTreeContent();
  32233. }
  32234. }
  32235. else {
  32236. _this._treeDiv.style.display = "none";
  32237. }
  32238. }
  32239. };
  32240. this._syncData = function () {
  32241. if (_this._labelsEnabled || !_this._showUI) {
  32242. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  32243. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  32244. var engine = _this._scene.getEngine();
  32245. var viewport = _this._camera.viewport;
  32246. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  32247. // Meshes
  32248. var meshes = _this._camera.getActiveMeshes();
  32249. var index;
  32250. var projectedPosition;
  32251. for (index = 0; index < meshes.length; index++) {
  32252. var mesh = meshes.data[index];
  32253. var position = mesh.getBoundingInfo().boundingSphere.center;
  32254. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32255. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  32256. _this._renderAxis(projectedPosition, mesh, globalViewport);
  32257. }
  32258. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  32259. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  32260. }
  32261. }
  32262. // Cameras
  32263. var cameras = _this._scene.cameras;
  32264. for (index = 0; index < cameras.length; index++) {
  32265. var camera = cameras[index];
  32266. if (camera === _this._camera) {
  32267. continue;
  32268. }
  32269. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32270. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  32271. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  32272. _this._camera.detachControl(engine.getRenderingCanvas());
  32273. _this._camera = camera;
  32274. _this._camera.attachControl(engine.getRenderingCanvas());
  32275. }, function () { return "purple"; });
  32276. }
  32277. }
  32278. // Lights
  32279. var lights = _this._scene.lights;
  32280. for (index = 0; index < lights.length; index++) {
  32281. var light = lights[index];
  32282. if (light.position) {
  32283. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  32284. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  32285. _this._renderLabel(light.name, projectedPosition, -20, function () {
  32286. light.setEnabled(!light.isEnabled());
  32287. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  32288. }
  32289. }
  32290. }
  32291. }
  32292. _this._clickPosition = undefined;
  32293. };
  32294. }
  32295. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  32296. while (this._treeSubsetDiv.hasChildNodes()) {
  32297. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  32298. }
  32299. // Add meshes
  32300. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  32301. sortedArray.sort(function (a, b) {
  32302. if (a.name === b.name) {
  32303. return 0;
  32304. }
  32305. return (a.name > b.name) ? 1 : -1;
  32306. });
  32307. for (var index = 0; index < sortedArray.length; index++) {
  32308. var mesh = sortedArray[index];
  32309. if (!mesh.isEnabled()) {
  32310. continue;
  32311. }
  32312. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  32313. m.isVisible = element.checked;
  32314. }, mesh);
  32315. }
  32316. };
  32317. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  32318. this._drawingContext.beginPath();
  32319. this._drawingContext.moveTo(zero.x, zero.y);
  32320. this._drawingContext.lineTo(unit.x, unit.y);
  32321. this._drawingContext.strokeStyle = color;
  32322. this._drawingContext.lineWidth = 4;
  32323. this._drawingContext.stroke();
  32324. this._drawingContext.font = "normal 14px Segoe UI";
  32325. this._drawingContext.fillStyle = color;
  32326. this._drawingContext.fillText(label, unitText.x, unitText.y);
  32327. };
  32328. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  32329. var position = mesh.getBoundingInfo().boundingSphere.center;
  32330. var worldMatrix = mesh.getWorldMatrix();
  32331. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  32332. var unit = (unprojectedVector.subtract(position)).length();
  32333. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32334. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32335. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  32336. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32337. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32338. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  32339. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  32340. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  32341. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  32342. };
  32343. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  32344. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  32345. this._drawingContext.font = "normal 12px Segoe UI";
  32346. var textMetrics = this._drawingContext.measureText(text);
  32347. var centerX = projectedPosition.x - textMetrics.width / 2;
  32348. var centerY = projectedPosition.y;
  32349. var clientRect = this._drawingCanvas.getBoundingClientRect();
  32350. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  32351. onClick();
  32352. }
  32353. this._drawingContext.beginPath();
  32354. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  32355. this._drawingContext.fillStyle = getFillStyle();
  32356. this._drawingContext.globalAlpha = 0.5;
  32357. this._drawingContext.fill();
  32358. this._drawingContext.globalAlpha = 1.0;
  32359. this._drawingContext.strokeStyle = '#FFFFFF';
  32360. this._drawingContext.lineWidth = 1;
  32361. this._drawingContext.stroke();
  32362. this._drawingContext.fillStyle = "#FFFFFF";
  32363. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  32364. this._drawingContext.beginPath();
  32365. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  32366. this._drawingContext.fill();
  32367. }
  32368. };
  32369. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  32370. if (!this._clickPosition) {
  32371. return false;
  32372. }
  32373. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  32374. return false;
  32375. }
  32376. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  32377. return false;
  32378. }
  32379. return true;
  32380. };
  32381. DebugLayer.prototype.isVisible = function () {
  32382. return this._enabled;
  32383. };
  32384. DebugLayer.prototype.hide = function () {
  32385. if (!this._enabled) {
  32386. return;
  32387. }
  32388. this._enabled = false;
  32389. var engine = this._scene.getEngine();
  32390. this._scene.unregisterBeforeRender(this._syncData);
  32391. this._scene.unregisterAfterRender(this._syncUI);
  32392. this._rootElement.removeChild(this._globalDiv);
  32393. this._scene.forceShowBoundingBoxes = false;
  32394. this._scene.forceWireframe = false;
  32395. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  32396. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  32397. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  32398. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  32399. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  32400. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  32401. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  32402. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  32403. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  32404. this._scene.shadowsEnabled = true;
  32405. this._scene.particlesEnabled = true;
  32406. this._scene.postProcessesEnabled = true;
  32407. this._scene.collisionsEnabled = true;
  32408. this._scene.lightsEnabled = true;
  32409. this._scene.texturesEnabled = true;
  32410. this._scene.lensFlaresEnabled = true;
  32411. this._scene.proceduralTexturesEnabled = true;
  32412. this._scene.renderTargetsEnabled = true;
  32413. this._scene.probesEnabled = true;
  32414. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  32415. this._clearSkeletonViewers();
  32416. };
  32417. DebugLayer.prototype._clearSkeletonViewers = function () {
  32418. for (var index = 0; index < this._skeletonViewers.length; index++) {
  32419. this._skeletonViewers[index].dispose();
  32420. }
  32421. this._skeletonViewers = [];
  32422. };
  32423. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  32424. if (showUI === void 0) { showUI = true; }
  32425. if (camera === void 0) { camera = null; }
  32426. if (rootElement === void 0) { rootElement = null; }
  32427. if (this._enabled) {
  32428. return;
  32429. }
  32430. this._enabled = true;
  32431. if (camera) {
  32432. this._camera = camera;
  32433. }
  32434. else {
  32435. this._camera = this._scene.activeCamera;
  32436. }
  32437. this._showUI = showUI;
  32438. var engine = this._scene.getEngine();
  32439. this._globalDiv = document.createElement("div");
  32440. this._rootElement = rootElement || document.body;
  32441. this._rootElement.appendChild(this._globalDiv);
  32442. this._generateDOMelements();
  32443. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  32444. this._syncPositions();
  32445. this._scene.registerBeforeRender(this._syncData);
  32446. this._scene.registerAfterRender(this._syncUI);
  32447. };
  32448. DebugLayer.prototype._clearLabels = function () {
  32449. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  32450. for (var index = 0; index < this._scene.meshes.length; index++) {
  32451. var mesh = this._scene.meshes[index];
  32452. mesh.renderOverlay = false;
  32453. }
  32454. };
  32455. DebugLayer.prototype._generateheader = function (root, text) {
  32456. var header = document.createElement("div");
  32457. header.innerHTML = text + "&nbsp;";
  32458. header.style.textAlign = "right";
  32459. header.style.width = "100%";
  32460. header.style.color = "white";
  32461. header.style.backgroundColor = "Black";
  32462. header.style.padding = "5px 5px 4px 0px";
  32463. header.style.marginLeft = "-5px";
  32464. header.style.fontWeight = "bold";
  32465. root.appendChild(header);
  32466. };
  32467. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  32468. var label = document.createElement("label");
  32469. label.style.display = "inline";
  32470. label.innerHTML = title;
  32471. label.style.color = color;
  32472. root.appendChild(label);
  32473. root.appendChild(document.createElement("br"));
  32474. };
  32475. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  32476. if (tag === void 0) { tag = null; }
  32477. var label = document.createElement("label");
  32478. label.style.display = "inline";
  32479. var boundingBoxesCheckbox = document.createElement("input");
  32480. boundingBoxesCheckbox.type = "checkbox";
  32481. boundingBoxesCheckbox.checked = initialState;
  32482. boundingBoxesCheckbox.style.display = "inline";
  32483. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  32484. boundingBoxesCheckbox.style.verticalAlign = "sub";
  32485. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  32486. task(evt.target, tag);
  32487. });
  32488. label.appendChild(boundingBoxesCheckbox);
  32489. var container = document.createElement("span");
  32490. var leftPart = document.createElement("span");
  32491. var rightPart = document.createElement("span");
  32492. rightPart.style.cssFloat = "right";
  32493. leftPart.innerHTML = leftTitle;
  32494. rightPart.innerHTML = rightTitle;
  32495. rightPart.style.fontSize = "12px";
  32496. rightPart.style.maxWidth = "200px";
  32497. container.appendChild(leftPart);
  32498. container.appendChild(rightPart);
  32499. label.appendChild(container);
  32500. root.appendChild(label);
  32501. root.appendChild(document.createElement("br"));
  32502. };
  32503. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  32504. if (tag === void 0) { tag = null; }
  32505. var label = document.createElement("label");
  32506. label.style.display = "inline";
  32507. var checkBox = document.createElement("input");
  32508. checkBox.type = "checkbox";
  32509. checkBox.checked = initialState;
  32510. checkBox.style.display = "inline";
  32511. checkBox.style.margin = "0px 5px 0px 0px";
  32512. checkBox.style.verticalAlign = "sub";
  32513. checkBox.addEventListener("change", function (evt) {
  32514. task(evt.target, tag);
  32515. });
  32516. label.appendChild(checkBox);
  32517. label.appendChild(document.createTextNode(title));
  32518. root.appendChild(label);
  32519. root.appendChild(document.createElement("br"));
  32520. };
  32521. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  32522. if (tag === void 0) { tag = null; }
  32523. var button = document.createElement("button");
  32524. button.innerHTML = title;
  32525. button.style.height = "24px";
  32526. button.style.width = "150px";
  32527. button.style.marginBottom = "5px";
  32528. button.style.color = "#444444";
  32529. button.style.border = "1px solid white";
  32530. button.className = "debugLayerButton";
  32531. button.addEventListener("click", function (evt) {
  32532. task(evt.target, tag);
  32533. });
  32534. root.appendChild(button);
  32535. root.appendChild(document.createElement("br"));
  32536. };
  32537. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  32538. if (tag === void 0) { tag = null; }
  32539. var label = document.createElement("label");
  32540. label.style.display = "inline";
  32541. var boundingBoxesRadio = document.createElement("input");
  32542. boundingBoxesRadio.type = "radio";
  32543. boundingBoxesRadio.name = name;
  32544. boundingBoxesRadio.checked = initialState;
  32545. boundingBoxesRadio.style.display = "inline";
  32546. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  32547. boundingBoxesRadio.style.verticalAlign = "sub";
  32548. boundingBoxesRadio.addEventListener("change", function (evt) {
  32549. task(evt.target, tag);
  32550. });
  32551. label.appendChild(boundingBoxesRadio);
  32552. label.appendChild(document.createTextNode(title));
  32553. root.appendChild(label);
  32554. root.appendChild(document.createElement("br"));
  32555. };
  32556. DebugLayer.prototype._generateDOMelements = function () {
  32557. var _this = this;
  32558. this._globalDiv.id = "DebugLayer";
  32559. this._globalDiv.style.position = "absolute";
  32560. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  32561. this._globalDiv.style.fontSize = "14px";
  32562. this._globalDiv.style.color = "white";
  32563. // Drawing canvas
  32564. this._drawingCanvas = document.createElement("canvas");
  32565. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  32566. this._drawingCanvas.style.position = "absolute";
  32567. this._drawingCanvas.style.pointerEvents = "none";
  32568. this._drawingCanvas.style.backgroundColor = "transparent";
  32569. this._drawingContext = this._drawingCanvas.getContext("2d");
  32570. this._globalDiv.appendChild(this._drawingCanvas);
  32571. if (this._showUI) {
  32572. var background = "rgba(128, 128, 128, 0.4)";
  32573. var border = "rgb(180, 180, 180) solid 1px";
  32574. // Stats
  32575. this._statsDiv = document.createElement("div");
  32576. this._statsDiv.id = "DebugLayerStats";
  32577. this._statsDiv.style.border = border;
  32578. this._statsDiv.style.position = "absolute";
  32579. this._statsDiv.style.background = background;
  32580. this._statsDiv.style.padding = "0px 0px 0px 5px";
  32581. this._generateheader(this._statsDiv, "STATISTICS");
  32582. this._statsSubsetDiv = document.createElement("div");
  32583. this._statsSubsetDiv.style.paddingTop = "5px";
  32584. this._statsSubsetDiv.style.paddingBottom = "5px";
  32585. this._statsSubsetDiv.style.overflowY = "auto";
  32586. this._statsDiv.appendChild(this._statsSubsetDiv);
  32587. // Tree
  32588. this._treeDiv = document.createElement("div");
  32589. this._treeDiv.id = "DebugLayerTree";
  32590. this._treeDiv.style.border = border;
  32591. this._treeDiv.style.position = "absolute";
  32592. this._treeDiv.style.background = background;
  32593. this._treeDiv.style.padding = "0px 0px 0px 5px";
  32594. this._treeDiv.style.display = "none";
  32595. this._generateheader(this._treeDiv, "MESHES TREE");
  32596. this._treeSubsetDiv = document.createElement("div");
  32597. this._treeSubsetDiv.style.paddingTop = "5px";
  32598. this._treeSubsetDiv.style.paddingRight = "5px";
  32599. this._treeSubsetDiv.style.overflowY = "auto";
  32600. this._treeSubsetDiv.style.maxHeight = "300px";
  32601. this._treeDiv.appendChild(this._treeSubsetDiv);
  32602. this._needToRefreshMeshesTree = true;
  32603. // Logs
  32604. this._logDiv = document.createElement("div");
  32605. this._logDiv.style.border = border;
  32606. this._logDiv.id = "DebugLayerLogs";
  32607. this._logDiv.style.position = "absolute";
  32608. this._logDiv.style.background = background;
  32609. this._logDiv.style.padding = "0px 0px 0px 5px";
  32610. this._logDiv.style.display = "none";
  32611. this._generateheader(this._logDiv, "LOGS");
  32612. this._logSubsetDiv = document.createElement("div");
  32613. this._logSubsetDiv.style.height = "127px";
  32614. this._logSubsetDiv.style.paddingTop = "5px";
  32615. this._logSubsetDiv.style.overflowY = "auto";
  32616. this._logSubsetDiv.style.fontSize = "12px";
  32617. this._logSubsetDiv.style.fontFamily = "consolas";
  32618. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  32619. this._logDiv.appendChild(this._logSubsetDiv);
  32620. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  32621. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  32622. };
  32623. // Options
  32624. this._optionsDiv = document.createElement("div");
  32625. this._optionsDiv.id = "DebugLayerOptions";
  32626. this._optionsDiv.style.border = border;
  32627. this._optionsDiv.style.position = "absolute";
  32628. this._optionsDiv.style.background = background;
  32629. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  32630. this._optionsDiv.style.overflowY = "auto";
  32631. this._generateheader(this._optionsDiv, "OPTIONS");
  32632. this._optionsSubsetDiv = document.createElement("div");
  32633. this._optionsSubsetDiv.style.paddingTop = "5px";
  32634. this._optionsSubsetDiv.style.paddingBottom = "5px";
  32635. this._optionsSubsetDiv.style.overflowY = "auto";
  32636. this._optionsSubsetDiv.style.maxHeight = "200px";
  32637. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  32638. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  32639. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  32640. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  32641. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  32642. _this._displayTree = element.checked;
  32643. _this._needToRefreshMeshesTree = true;
  32644. });
  32645. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32646. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  32647. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  32648. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  32649. _this._labelsEnabled = element.checked;
  32650. if (!_this._labelsEnabled) {
  32651. _this._clearLabels();
  32652. }
  32653. });
  32654. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  32655. if (element.checked) {
  32656. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  32657. }
  32658. else {
  32659. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  32660. }
  32661. });
  32662. ;
  32663. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32664. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  32665. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  32666. if (element.checked) {
  32667. _this._scene.forceWireframe = false;
  32668. _this._scene.forcePointsCloud = false;
  32669. }
  32670. });
  32671. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  32672. if (element.checked) {
  32673. _this._scene.forceWireframe = true;
  32674. _this._scene.forcePointsCloud = false;
  32675. }
  32676. });
  32677. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  32678. if (element.checked) {
  32679. _this._scene.forceWireframe = false;
  32680. _this._scene.forcePointsCloud = true;
  32681. }
  32682. });
  32683. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32684. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  32685. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  32686. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  32687. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  32688. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  32689. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  32690. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  32691. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  32692. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  32693. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  32694. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  32695. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32696. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  32697. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  32698. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  32699. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  32700. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  32701. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  32702. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  32703. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  32704. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  32705. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  32706. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  32707. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  32708. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  32709. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  32710. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  32711. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  32712. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32713. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  32714. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  32715. if (element.checked) {
  32716. _this._scene.headphone = true;
  32717. }
  32718. });
  32719. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  32720. if (element.checked) {
  32721. _this._scene.headphone = false;
  32722. }
  32723. });
  32724. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  32725. _this._scene.audioEnabled = !element.checked;
  32726. });
  32727. }
  32728. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32729. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  32730. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  32731. if (!element.checked) {
  32732. _this._clearSkeletonViewers();
  32733. return;
  32734. }
  32735. for (var index = 0; index < _this._scene.meshes.length; index++) {
  32736. var mesh = _this._scene.meshes[index];
  32737. if (mesh.skeleton) {
  32738. var found = false;
  32739. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  32740. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  32741. found = true;
  32742. break;
  32743. }
  32744. }
  32745. if (found) {
  32746. continue;
  32747. }
  32748. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  32749. viewer.isEnabled = true;
  32750. _this._skeletonViewers.push(viewer);
  32751. }
  32752. }
  32753. });
  32754. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32755. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  32756. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  32757. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  32758. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  32759. if (_this._camera) {
  32760. console.log(_this._camera);
  32761. }
  32762. else {
  32763. console.warn("No camera defined, or debug layer created before camera creation!");
  32764. }
  32765. });
  32766. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32767. this._globalDiv.appendChild(this._statsDiv);
  32768. this._globalDiv.appendChild(this._logDiv);
  32769. this._globalDiv.appendChild(this._optionsDiv);
  32770. this._globalDiv.appendChild(this._treeDiv);
  32771. }
  32772. };
  32773. DebugLayer.prototype._displayStats = function () {
  32774. var scene = this._scene;
  32775. var engine = scene.getEngine();
  32776. var glInfo = engine.getGlInfo();
  32777. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  32778. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32779. + "<b>Count</b><br>"
  32780. + "Total meshes: " + scene.meshes.length + "<br>"
  32781. + "Total lights: " + scene.lights.length + "<br>"
  32782. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  32783. + "Total materials: " + scene.materials.length + "<br>"
  32784. + "Total textures: " + scene.textures.length + "<br>"
  32785. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  32786. + "Active indices: " + scene.getActiveIndices() + "<br>"
  32787. + "Active bones: " + scene.getActiveBones() + "<br>"
  32788. + "Active particles: " + scene.getActiveParticles() + "<br>"
  32789. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  32790. + "<b>Duration</b><br>"
  32791. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  32792. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  32793. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  32794. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  32795. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  32796. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  32797. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  32798. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  32799. + "</div>"
  32800. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32801. + "<b>Extensions</b><br>"
  32802. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  32803. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  32804. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  32805. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  32806. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  32807. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  32808. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  32809. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  32810. + "</div><br>"
  32811. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32812. + "<b>Caps.</b><br>"
  32813. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  32814. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  32815. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  32816. + "<b>Info</b><br>"
  32817. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  32818. + glInfo.version + "<br>"
  32819. + "</div><br>"
  32820. + glInfo.renderer + "<br>";
  32821. if (this.customStatsFunction) {
  32822. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  32823. }
  32824. };
  32825. return DebugLayer;
  32826. })();
  32827. BABYLON.DebugLayer = DebugLayer;
  32828. })(BABYLON || (BABYLON = {}));
  32829. var BABYLON;
  32830. (function (BABYLON) {
  32831. var DefaultLoadingScreen = (function () {
  32832. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  32833. var _this = this;
  32834. if (_loadingText === void 0) { _loadingText = ""; }
  32835. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  32836. this._renderingCanvas = _renderingCanvas;
  32837. this._loadingText = _loadingText;
  32838. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  32839. // Resize
  32840. this._resizeLoadingUI = function () {
  32841. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  32842. _this._loadingDiv.style.position = "absolute";
  32843. _this._loadingDiv.style.left = canvasRect.left + "px";
  32844. _this._loadingDiv.style.top = canvasRect.top + "px";
  32845. _this._loadingDiv.style.width = canvasRect.width + "px";
  32846. _this._loadingDiv.style.height = canvasRect.height + "px";
  32847. };
  32848. }
  32849. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  32850. var _this = this;
  32851. if (this._loadingDiv) {
  32852. // Do not add a loading screen if there is already one
  32853. return;
  32854. }
  32855. this._loadingDiv = document.createElement("div");
  32856. this._loadingDiv.id = "babylonjsLoadingDiv";
  32857. this._loadingDiv.style.opacity = "0";
  32858. this._loadingDiv.style.transition = "opacity 1.5s ease";
  32859. // Loading text
  32860. this._loadingTextDiv = document.createElement("div");
  32861. this._loadingTextDiv.style.position = "absolute";
  32862. this._loadingTextDiv.style.left = "0";
  32863. this._loadingTextDiv.style.top = "50%";
  32864. this._loadingTextDiv.style.marginTop = "80px";
  32865. this._loadingTextDiv.style.width = "100%";
  32866. this._loadingTextDiv.style.height = "20px";
  32867. this._loadingTextDiv.style.fontFamily = "Arial";
  32868. this._loadingTextDiv.style.fontSize = "14px";
  32869. this._loadingTextDiv.style.color = "white";
  32870. this._loadingTextDiv.style.textAlign = "center";
  32871. this._loadingTextDiv.innerHTML = "Loading";
  32872. this._loadingDiv.appendChild(this._loadingTextDiv);
  32873. //set the predefined text
  32874. this._loadingTextDiv.innerHTML = this._loadingText;
  32875. // Loading img
  32876. var imgBack = new Image();
  32877. 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==";
  32878. imgBack.style.position = "absolute";
  32879. imgBack.style.left = "50%";
  32880. imgBack.style.top = "50%";
  32881. imgBack.style.marginLeft = "-50px";
  32882. imgBack.style.marginTop = "-50px";
  32883. imgBack.style.transition = "transform 1.0s ease";
  32884. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  32885. var deg = 360;
  32886. var onTransitionEnd = function () {
  32887. deg += 360;
  32888. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  32889. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  32890. };
  32891. imgBack.addEventListener("transitionend", onTransitionEnd);
  32892. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  32893. this._loadingDiv.appendChild(imgBack);
  32894. // front image
  32895. var imgFront = new Image();
  32896. 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=";
  32897. imgFront.style.position = "absolute";
  32898. imgFront.style.left = "50%";
  32899. imgFront.style.top = "50%";
  32900. imgFront.style.marginLeft = "-50px";
  32901. imgFront.style.marginTop = "-50px";
  32902. this._loadingDiv.appendChild(imgFront);
  32903. this._resizeLoadingUI();
  32904. window.addEventListener("resize", this._resizeLoadingUI);
  32905. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32906. document.body.appendChild(this._loadingDiv);
  32907. setTimeout(function () {
  32908. _this._loadingDiv.style.opacity = "1";
  32909. imgBack.style.transform = "rotateZ(360deg)";
  32910. imgBack.style.webkitTransform = "rotateZ(360deg)";
  32911. }, 0);
  32912. };
  32913. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  32914. var _this = this;
  32915. if (!this._loadingDiv) {
  32916. return;
  32917. }
  32918. var onTransitionEnd = function () {
  32919. if (!_this._loadingDiv) {
  32920. return;
  32921. }
  32922. document.body.removeChild(_this._loadingDiv);
  32923. window.removeEventListener("resize", _this._resizeLoadingUI);
  32924. _this._loadingDiv = null;
  32925. };
  32926. this._loadingDiv.style.opacity = "0";
  32927. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  32928. };
  32929. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  32930. set: function (text) {
  32931. this._loadingText = text;
  32932. if (this._loadingTextDiv) {
  32933. this._loadingTextDiv.innerHTML = this._loadingText;
  32934. }
  32935. },
  32936. enumerable: true,
  32937. configurable: true
  32938. });
  32939. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  32940. get: function () {
  32941. return this._loadingDivBackgroundColor;
  32942. },
  32943. set: function (color) {
  32944. this._loadingDivBackgroundColor = color;
  32945. if (!this._loadingDiv) {
  32946. return;
  32947. }
  32948. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32949. },
  32950. enumerable: true,
  32951. configurable: true
  32952. });
  32953. return DefaultLoadingScreen;
  32954. })();
  32955. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  32956. })(BABYLON || (BABYLON = {}));
  32957. var BABYLON;
  32958. (function (BABYLON) {
  32959. var AudioEngine = (function () {
  32960. function AudioEngine() {
  32961. this._audioContext = null;
  32962. this._audioContextInitialized = false;
  32963. this.canUseWebAudio = false;
  32964. this.WarnedWebAudioUnsupported = false;
  32965. this.unlocked = false;
  32966. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  32967. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  32968. this.canUseWebAudio = true;
  32969. }
  32970. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  32971. this._unlockiOSaudio();
  32972. }
  32973. else {
  32974. this.unlocked = true;
  32975. }
  32976. }
  32977. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  32978. get: function () {
  32979. if (!this._audioContextInitialized) {
  32980. this._initializeAudioContext();
  32981. }
  32982. return this._audioContext;
  32983. },
  32984. enumerable: true,
  32985. configurable: true
  32986. });
  32987. AudioEngine.prototype._unlockiOSaudio = function () {
  32988. var _this = this;
  32989. var unlockaudio = function () {
  32990. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  32991. var source = _this.audioContext.createBufferSource();
  32992. source.buffer = buffer;
  32993. source.connect(_this.audioContext.destination);
  32994. source.start(0);
  32995. setTimeout(function () {
  32996. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  32997. _this.unlocked = true;
  32998. window.removeEventListener('touchend', unlockaudio, false);
  32999. if (_this.onAudioUnlocked) {
  33000. _this.onAudioUnlocked();
  33001. }
  33002. }
  33003. }, 0);
  33004. };
  33005. window.addEventListener('touchend', unlockaudio, false);
  33006. };
  33007. AudioEngine.prototype._initializeAudioContext = function () {
  33008. try {
  33009. if (this.canUseWebAudio) {
  33010. this._audioContext = new AudioContext();
  33011. // create a global volume gain node
  33012. this.masterGain = this._audioContext.createGain();
  33013. this.masterGain.gain.value = 1;
  33014. this.masterGain.connect(this._audioContext.destination);
  33015. this._audioContextInitialized = true;
  33016. }
  33017. }
  33018. catch (e) {
  33019. this.canUseWebAudio = false;
  33020. BABYLON.Tools.Error("Web Audio: " + e.message);
  33021. }
  33022. };
  33023. AudioEngine.prototype.dispose = function () {
  33024. if (this.canUseWebAudio && this._audioContextInitialized) {
  33025. if (this._connectedAnalyser) {
  33026. this._connectedAnalyser.stopDebugCanvas();
  33027. this._connectedAnalyser.dispose();
  33028. this.masterGain.disconnect();
  33029. this.masterGain.connect(this._audioContext.destination);
  33030. this._connectedAnalyser = null;
  33031. }
  33032. this.masterGain.gain.value = 1;
  33033. }
  33034. this.WarnedWebAudioUnsupported = false;
  33035. };
  33036. AudioEngine.prototype.getGlobalVolume = function () {
  33037. if (this.canUseWebAudio && this._audioContextInitialized) {
  33038. return this.masterGain.gain.value;
  33039. }
  33040. else {
  33041. return -1;
  33042. }
  33043. };
  33044. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33045. if (this.canUseWebAudio && this._audioContextInitialized) {
  33046. this.masterGain.gain.value = newVolume;
  33047. }
  33048. };
  33049. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33050. if (this._connectedAnalyser) {
  33051. this._connectedAnalyser.stopDebugCanvas();
  33052. }
  33053. if (this.canUseWebAudio && this._audioContextInitialized) {
  33054. this._connectedAnalyser = analyser;
  33055. this.masterGain.disconnect();
  33056. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33057. }
  33058. };
  33059. return AudioEngine;
  33060. })();
  33061. BABYLON.AudioEngine = AudioEngine;
  33062. })(BABYLON || (BABYLON = {}));
  33063. var BABYLON;
  33064. (function (BABYLON) {
  33065. var Sound = (function () {
  33066. /**
  33067. * Create a sound and attach it to a scene
  33068. * @param name Name of your sound
  33069. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33070. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33071. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33072. */
  33073. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33074. var _this = this;
  33075. this.autoplay = false;
  33076. this.loop = false;
  33077. this.useCustomAttenuation = false;
  33078. this.spatialSound = false;
  33079. this.refDistance = 1;
  33080. this.rolloffFactor = 1;
  33081. this.maxDistance = 100;
  33082. this.distanceModel = "linear";
  33083. this._panningModel = "equalpower";
  33084. this._playbackRate = 1;
  33085. this._streaming = false;
  33086. this._startTime = 0;
  33087. this._startOffset = 0;
  33088. this._position = BABYLON.Vector3.Zero();
  33089. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33090. this._volume = 1;
  33091. this._isLoaded = false;
  33092. this._isReadyToPlay = false;
  33093. this.isPlaying = false;
  33094. this.isPaused = false;
  33095. this._isDirectional = false;
  33096. // Used if you'd like to create a directional sound.
  33097. // If not set, the sound will be omnidirectional
  33098. this._coneInnerAngle = 360;
  33099. this._coneOuterAngle = 360;
  33100. this._coneOuterGain = 0;
  33101. this._isOutputConnected = false;
  33102. this.name = name;
  33103. this._scene = scene;
  33104. this._readyToPlayCallback = readyToPlayCallback;
  33105. // Default custom attenuation function is a linear attenuation
  33106. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33107. if (currentDistance < maxDistance) {
  33108. return currentVolume * (1 - currentDistance / maxDistance);
  33109. }
  33110. else {
  33111. return 0;
  33112. }
  33113. };
  33114. if (options) {
  33115. this.autoplay = options.autoplay || false;
  33116. this.loop = options.loop || false;
  33117. // if volume === 0, we need another way to check this option
  33118. if (options.volume !== undefined) {
  33119. this._volume = options.volume;
  33120. }
  33121. this.spatialSound = options.spatialSound || false;
  33122. this.maxDistance = options.maxDistance || 100;
  33123. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33124. this.rolloffFactor = options.rolloffFactor || 1;
  33125. this.refDistance = options.refDistance || 1;
  33126. this.distanceModel = options.distanceModel || "linear";
  33127. this._playbackRate = options.playbackRate || 1;
  33128. this._streaming = options.streaming || false;
  33129. }
  33130. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33131. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33132. this._soundGain.gain.value = this._volume;
  33133. this._inputAudioNode = this._soundGain;
  33134. this._ouputAudioNode = this._soundGain;
  33135. if (this.spatialSound) {
  33136. this._createSpatialParameters();
  33137. }
  33138. this._scene.mainSoundTrack.AddSound(this);
  33139. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33140. if (urlOrArrayBuffer) {
  33141. // If it's an URL
  33142. if (typeof (urlOrArrayBuffer) === "string") {
  33143. // Loading sound using XHR2
  33144. if (!this._streaming) {
  33145. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  33146. }
  33147. else {
  33148. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  33149. this._htmlAudioElement.controls = false;
  33150. this._htmlAudioElement.loop = this.loop;
  33151. this._htmlAudioElement.crossOrigin = "anonymous";
  33152. this._htmlAudioElement.preload = "auto";
  33153. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  33154. _this._isReadyToPlay = true;
  33155. if (_this.autoplay) {
  33156. _this.play();
  33157. }
  33158. if (_this._readyToPlayCallback) {
  33159. _this._readyToPlayCallback();
  33160. }
  33161. });
  33162. document.body.appendChild(this._htmlAudioElement);
  33163. }
  33164. }
  33165. else {
  33166. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33167. if (urlOrArrayBuffer.byteLength > 0) {
  33168. this._soundLoaded(urlOrArrayBuffer);
  33169. }
  33170. }
  33171. else {
  33172. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33173. }
  33174. }
  33175. }
  33176. }
  33177. else {
  33178. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33179. this._scene.mainSoundTrack.AddSound(this);
  33180. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33181. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33182. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33183. }
  33184. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33185. if (this._readyToPlayCallback) {
  33186. window.setTimeout(function () {
  33187. _this._readyToPlayCallback();
  33188. }, 1000);
  33189. }
  33190. }
  33191. }
  33192. Sound.prototype.dispose = function () {
  33193. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33194. if (this.isPlaying) {
  33195. this.stop();
  33196. }
  33197. this._isReadyToPlay = false;
  33198. if (this.soundTrackId === -1) {
  33199. this._scene.mainSoundTrack.RemoveSound(this);
  33200. }
  33201. else {
  33202. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33203. }
  33204. if (this._soundGain) {
  33205. this._soundGain.disconnect();
  33206. this._soundGain = null;
  33207. }
  33208. if (this._soundPanner) {
  33209. this._soundPanner.disconnect();
  33210. this._soundPanner = null;
  33211. }
  33212. if (this._soundSource) {
  33213. this._soundSource.disconnect();
  33214. this._soundSource = null;
  33215. }
  33216. this._audioBuffer = null;
  33217. if (this._htmlAudioElement) {
  33218. this._htmlAudioElement.pause();
  33219. this._htmlAudioElement.src = "";
  33220. document.body.removeChild(this._htmlAudioElement);
  33221. }
  33222. if (this._connectedMesh) {
  33223. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33224. this._connectedMesh = null;
  33225. }
  33226. }
  33227. };
  33228. Sound.prototype._soundLoaded = function (audioData) {
  33229. var _this = this;
  33230. this._isLoaded = true;
  33231. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33232. _this._audioBuffer = buffer;
  33233. _this._isReadyToPlay = true;
  33234. if (_this.autoplay) {
  33235. _this.play();
  33236. }
  33237. if (_this._readyToPlayCallback) {
  33238. _this._readyToPlayCallback();
  33239. }
  33240. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33241. };
  33242. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33243. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33244. this._audioBuffer = audioBuffer;
  33245. this._isReadyToPlay = true;
  33246. }
  33247. };
  33248. Sound.prototype.updateOptions = function (options) {
  33249. if (options) {
  33250. this.loop = options.loop || this.loop;
  33251. this.maxDistance = options.maxDistance || this.maxDistance;
  33252. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33253. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33254. this.refDistance = options.refDistance || this.refDistance;
  33255. this.distanceModel = options.distanceModel || this.distanceModel;
  33256. this._playbackRate = options.playbackRate || this._playbackRate;
  33257. this._updateSpatialParameters();
  33258. if (this.isPlaying) {
  33259. if (this._streaming) {
  33260. this._htmlAudioElement.playbackRate = this._playbackRate;
  33261. }
  33262. else {
  33263. this._soundSource.playbackRate.value = this._playbackRate;
  33264. }
  33265. }
  33266. }
  33267. };
  33268. Sound.prototype._createSpatialParameters = function () {
  33269. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33270. if (this._scene.headphone) {
  33271. this._panningModel = "HRTF";
  33272. }
  33273. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33274. this._updateSpatialParameters();
  33275. this._soundPanner.connect(this._ouputAudioNode);
  33276. this._inputAudioNode = this._soundPanner;
  33277. }
  33278. };
  33279. Sound.prototype._updateSpatialParameters = function () {
  33280. if (this.spatialSound) {
  33281. if (this.useCustomAttenuation) {
  33282. // Tricks to disable in a way embedded Web Audio attenuation
  33283. this._soundPanner.distanceModel = "linear";
  33284. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33285. this._soundPanner.refDistance = 1;
  33286. this._soundPanner.rolloffFactor = 1;
  33287. this._soundPanner.panningModel = this._panningModel;
  33288. }
  33289. else {
  33290. this._soundPanner.distanceModel = this.distanceModel;
  33291. this._soundPanner.maxDistance = this.maxDistance;
  33292. this._soundPanner.refDistance = this.refDistance;
  33293. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33294. this._soundPanner.panningModel = this._panningModel;
  33295. }
  33296. }
  33297. };
  33298. Sound.prototype.switchPanningModelToHRTF = function () {
  33299. this._panningModel = "HRTF";
  33300. this._switchPanningModel();
  33301. };
  33302. Sound.prototype.switchPanningModelToEqualPower = function () {
  33303. this._panningModel = "equalpower";
  33304. this._switchPanningModel();
  33305. };
  33306. Sound.prototype._switchPanningModel = function () {
  33307. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33308. this._soundPanner.panningModel = this._panningModel;
  33309. }
  33310. };
  33311. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33312. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33313. if (this._isOutputConnected) {
  33314. this._ouputAudioNode.disconnect();
  33315. }
  33316. this._ouputAudioNode.connect(soundTrackAudioNode);
  33317. this._isOutputConnected = true;
  33318. }
  33319. };
  33320. /**
  33321. * Transform this sound into a directional source
  33322. * @param coneInnerAngle Size of the inner cone in degree
  33323. * @param coneOuterAngle Size of the outer cone in degree
  33324. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33325. */
  33326. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33327. if (coneOuterAngle < coneInnerAngle) {
  33328. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33329. return;
  33330. }
  33331. this._coneInnerAngle = coneInnerAngle;
  33332. this._coneOuterAngle = coneOuterAngle;
  33333. this._coneOuterGain = coneOuterGain;
  33334. this._isDirectional = true;
  33335. if (this.isPlaying && this.loop) {
  33336. this.stop();
  33337. this.play();
  33338. }
  33339. };
  33340. Sound.prototype.setPosition = function (newPosition) {
  33341. this._position = newPosition;
  33342. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33343. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33344. }
  33345. };
  33346. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33347. this._localDirection = newLocalDirection;
  33348. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33349. this._updateDirection();
  33350. }
  33351. };
  33352. Sound.prototype._updateDirection = function () {
  33353. var mat = this._connectedMesh.getWorldMatrix();
  33354. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33355. direction.normalize();
  33356. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33357. };
  33358. Sound.prototype.updateDistanceFromListener = function () {
  33359. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33360. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33361. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33362. }
  33363. };
  33364. Sound.prototype.setAttenuationFunction = function (callback) {
  33365. this._customAttenuationFunction = callback;
  33366. };
  33367. /**
  33368. * Play the sound
  33369. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33370. */
  33371. Sound.prototype.play = function (time) {
  33372. var _this = this;
  33373. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33374. try {
  33375. if (this._startOffset < 0) {
  33376. time = -this._startOffset;
  33377. this._startOffset = 0;
  33378. }
  33379. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33380. if (!this._soundSource || !this._streamingSource) {
  33381. if (this.spatialSound) {
  33382. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33383. if (this._isDirectional) {
  33384. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33385. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33386. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33387. if (this._connectedMesh) {
  33388. this._updateDirection();
  33389. }
  33390. else {
  33391. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33392. }
  33393. }
  33394. }
  33395. }
  33396. if (this._streaming) {
  33397. if (!this._streamingSource) {
  33398. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33399. this._htmlAudioElement.onended = function () { _this._onended(); };
  33400. this._htmlAudioElement.playbackRate = this._playbackRate;
  33401. }
  33402. this._streamingSource.disconnect();
  33403. this._streamingSource.connect(this._inputAudioNode);
  33404. this._htmlAudioElement.play();
  33405. }
  33406. else {
  33407. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33408. this._soundSource.buffer = this._audioBuffer;
  33409. this._soundSource.connect(this._inputAudioNode);
  33410. this._soundSource.loop = this.loop;
  33411. this._soundSource.playbackRate.value = this._playbackRate;
  33412. this._soundSource.onended = function () { _this._onended(); };
  33413. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33414. }
  33415. this._startTime = startTime;
  33416. this.isPlaying = true;
  33417. this.isPaused = false;
  33418. }
  33419. catch (ex) {
  33420. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33421. }
  33422. }
  33423. };
  33424. Sound.prototype._onended = function () {
  33425. this.isPlaying = false;
  33426. if (this.onended) {
  33427. this.onended();
  33428. }
  33429. };
  33430. /**
  33431. * Stop the sound
  33432. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33433. */
  33434. Sound.prototype.stop = function (time) {
  33435. if (this.isPlaying) {
  33436. if (this._streaming) {
  33437. this._htmlAudioElement.pause();
  33438. // Test needed for Firefox or it will generate an Invalid State Error
  33439. if (this._htmlAudioElement.currentTime > 0) {
  33440. this._htmlAudioElement.currentTime = 0;
  33441. }
  33442. }
  33443. else {
  33444. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33445. this._soundSource.stop(stopTime);
  33446. if (!this.isPaused) {
  33447. this._startOffset = 0;
  33448. }
  33449. }
  33450. this.isPlaying = false;
  33451. }
  33452. };
  33453. Sound.prototype.pause = function () {
  33454. if (this.isPlaying) {
  33455. this.isPaused = true;
  33456. if (this._streaming) {
  33457. this._htmlAudioElement.pause();
  33458. }
  33459. else {
  33460. this.stop(0);
  33461. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33462. }
  33463. }
  33464. };
  33465. Sound.prototype.setVolume = function (newVolume, time) {
  33466. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33467. if (time) {
  33468. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  33469. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33470. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  33471. }
  33472. else {
  33473. this._soundGain.gain.value = newVolume;
  33474. }
  33475. }
  33476. this._volume = newVolume;
  33477. };
  33478. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33479. this._playbackRate = newPlaybackRate;
  33480. if (this.isPlaying) {
  33481. if (this._streaming) {
  33482. this._htmlAudioElement.playbackRate = this._playbackRate;
  33483. }
  33484. else {
  33485. this._soundSource.playbackRate.value = this._playbackRate;
  33486. }
  33487. }
  33488. };
  33489. Sound.prototype.getVolume = function () {
  33490. return this._volume;
  33491. };
  33492. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33493. var _this = this;
  33494. if (this._connectedMesh) {
  33495. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33496. this._registerFunc = null;
  33497. }
  33498. this._connectedMesh = meshToConnectTo;
  33499. if (!this.spatialSound) {
  33500. this.spatialSound = true;
  33501. this._createSpatialParameters();
  33502. if (this.isPlaying && this.loop) {
  33503. this.stop();
  33504. this.play();
  33505. }
  33506. }
  33507. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33508. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33509. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33510. };
  33511. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33512. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33513. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33514. this._updateDirection();
  33515. }
  33516. };
  33517. Sound.prototype.clone = function () {
  33518. var _this = this;
  33519. if (!this._streaming) {
  33520. var setBufferAndRun = function () {
  33521. if (_this._isReadyToPlay) {
  33522. clonedSound._audioBuffer = _this.getAudioBuffer();
  33523. clonedSound._isReadyToPlay = true;
  33524. if (clonedSound.autoplay) {
  33525. clonedSound.play();
  33526. }
  33527. }
  33528. else {
  33529. window.setTimeout(setBufferAndRun, 300);
  33530. }
  33531. };
  33532. var currentOptions = {
  33533. autoplay: this.autoplay, loop: this.loop,
  33534. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  33535. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  33536. refDistance: this.refDistance, distanceModel: this.distanceModel
  33537. };
  33538. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  33539. if (this.useCustomAttenuation) {
  33540. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  33541. }
  33542. clonedSound.setPosition(this._position);
  33543. clonedSound.setPlaybackRate(this._playbackRate);
  33544. setBufferAndRun();
  33545. return clonedSound;
  33546. }
  33547. else {
  33548. return null;
  33549. }
  33550. };
  33551. Sound.prototype.getAudioBuffer = function () {
  33552. return this._audioBuffer;
  33553. };
  33554. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  33555. var soundName = parsedSound.name;
  33556. var soundUrl;
  33557. if (parsedSound.url) {
  33558. soundUrl = rootUrl + parsedSound.url;
  33559. }
  33560. else {
  33561. soundUrl = rootUrl + soundName;
  33562. }
  33563. var options = {
  33564. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  33565. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  33566. rolloffFactor: parsedSound.rolloffFactor,
  33567. refDistance: parsedSound.refDistance,
  33568. distanceModel: parsedSound.distanceModel,
  33569. playbackRate: parsedSound.playbackRate
  33570. };
  33571. var newSound;
  33572. if (!sourceSound) {
  33573. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  33574. scene._addPendingData(newSound);
  33575. }
  33576. else {
  33577. var setBufferAndRun = function () {
  33578. if (sourceSound._isReadyToPlay) {
  33579. newSound._audioBuffer = sourceSound.getAudioBuffer();
  33580. newSound._isReadyToPlay = true;
  33581. if (newSound.autoplay) {
  33582. newSound.play();
  33583. }
  33584. }
  33585. else {
  33586. window.setTimeout(setBufferAndRun, 300);
  33587. }
  33588. };
  33589. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  33590. setBufferAndRun();
  33591. }
  33592. if (parsedSound.position) {
  33593. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  33594. newSound.setPosition(soundPosition);
  33595. }
  33596. if (parsedSound.isDirectional) {
  33597. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  33598. if (parsedSound.localDirectionToMesh) {
  33599. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  33600. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  33601. }
  33602. }
  33603. if (parsedSound.connectedMeshId) {
  33604. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  33605. if (connectedMesh) {
  33606. newSound.attachToMesh(connectedMesh);
  33607. }
  33608. }
  33609. return newSound;
  33610. };
  33611. return Sound;
  33612. })();
  33613. BABYLON.Sound = Sound;
  33614. })(BABYLON || (BABYLON = {}));
  33615. var BABYLON;
  33616. (function (BABYLON) {
  33617. var SoundTrack = (function () {
  33618. function SoundTrack(scene, options) {
  33619. this.id = -1;
  33620. this._isMainTrack = false;
  33621. this._isInitialized = false;
  33622. this._scene = scene;
  33623. this.soundCollection = new Array();
  33624. this._options = options;
  33625. if (!this._isMainTrack) {
  33626. this._scene.soundTracks.push(this);
  33627. this.id = this._scene.soundTracks.length - 1;
  33628. }
  33629. }
  33630. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33631. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33632. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33633. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33634. if (this._options) {
  33635. if (this._options.volume) {
  33636. this._outputAudioNode.gain.value = this._options.volume;
  33637. }
  33638. if (this._options.mainTrack) {
  33639. this._isMainTrack = this._options.mainTrack;
  33640. }
  33641. }
  33642. this._isInitialized = true;
  33643. }
  33644. };
  33645. SoundTrack.prototype.dispose = function () {
  33646. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33647. if (this._connectedAnalyser) {
  33648. this._connectedAnalyser.stopDebugCanvas();
  33649. }
  33650. while (this.soundCollection.length) {
  33651. this.soundCollection[0].dispose();
  33652. }
  33653. if (this._outputAudioNode) {
  33654. this._outputAudioNode.disconnect();
  33655. }
  33656. this._outputAudioNode = null;
  33657. }
  33658. };
  33659. SoundTrack.prototype.AddSound = function (sound) {
  33660. if (!this._isInitialized) {
  33661. this._initializeSoundTrackAudioGraph();
  33662. }
  33663. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33664. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33665. }
  33666. if (sound.soundTrackId) {
  33667. if (sound.soundTrackId === -1) {
  33668. this._scene.mainSoundTrack.RemoveSound(sound);
  33669. }
  33670. else {
  33671. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33672. }
  33673. }
  33674. this.soundCollection.push(sound);
  33675. sound.soundTrackId = this.id;
  33676. };
  33677. SoundTrack.prototype.RemoveSound = function (sound) {
  33678. var index = this.soundCollection.indexOf(sound);
  33679. if (index !== -1) {
  33680. this.soundCollection.splice(index, 1);
  33681. }
  33682. };
  33683. SoundTrack.prototype.setVolume = function (newVolume) {
  33684. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33685. this._outputAudioNode.gain.value = newVolume;
  33686. }
  33687. };
  33688. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  33689. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33690. for (var i = 0; i < this.soundCollection.length; i++) {
  33691. this.soundCollection[i].switchPanningModelToHRTF();
  33692. }
  33693. }
  33694. };
  33695. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  33696. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33697. for (var i = 0; i < this.soundCollection.length; i++) {
  33698. this.soundCollection[i].switchPanningModelToEqualPower();
  33699. }
  33700. }
  33701. };
  33702. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  33703. if (this._connectedAnalyser) {
  33704. this._connectedAnalyser.stopDebugCanvas();
  33705. }
  33706. this._connectedAnalyser = analyser;
  33707. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33708. this._outputAudioNode.disconnect();
  33709. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  33710. }
  33711. };
  33712. return SoundTrack;
  33713. })();
  33714. BABYLON.SoundTrack = SoundTrack;
  33715. })(BABYLON || (BABYLON = {}));
  33716. var BABYLON;
  33717. (function (BABYLON) {
  33718. var SIMDVector3 = (function () {
  33719. function SIMDVector3() {
  33720. }
  33721. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  33722. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  33723. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33724. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33725. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33726. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33727. 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));
  33728. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33729. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33730. };
  33731. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  33732. var v0 = SIMD.float32x4.splat(x);
  33733. var v1 = SIMD.float32x4.splat(y);
  33734. var v2 = SIMD.float32x4.splat(z);
  33735. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33736. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33737. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33738. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33739. 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));
  33740. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33741. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33742. };
  33743. return SIMDVector3;
  33744. })();
  33745. BABYLON.SIMDVector3 = SIMDVector3;
  33746. var SIMDMatrix = (function () {
  33747. function SIMDMatrix() {
  33748. }
  33749. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  33750. if (offset === void 0) { offset = 0; }
  33751. var tm = this.m;
  33752. var om = other.m;
  33753. var om0 = SIMD.float32x4.load(om, 0);
  33754. var om1 = SIMD.float32x4.load(om, 4);
  33755. var om2 = SIMD.float32x4.load(om, 8);
  33756. var om3 = SIMD.float32x4.load(om, 12);
  33757. var tm0 = SIMD.float32x4.load(tm, 0);
  33758. 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)))));
  33759. var tm1 = SIMD.float32x4.load(tm, 4);
  33760. 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)))));
  33761. var tm2 = SIMD.float32x4.load(tm, 8);
  33762. 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)))));
  33763. var tm3 = SIMD.float32x4.load(tm, 12);
  33764. 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)))));
  33765. };
  33766. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  33767. var src = this.m;
  33768. var dest = other.m;
  33769. var row0, row1, row2, row3;
  33770. var tmp1;
  33771. var minor0, minor1, minor2, minor3;
  33772. var det;
  33773. // Load the 4 rows
  33774. var src0 = SIMD.float32x4.load(src, 0);
  33775. var src1 = SIMD.float32x4.load(src, 4);
  33776. var src2 = SIMD.float32x4.load(src, 8);
  33777. var src3 = SIMD.float32x4.load(src, 12);
  33778. // Transpose the source matrix. Sort of. Not a true transpose operation
  33779. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33780. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33781. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  33782. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  33783. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33784. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33785. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  33786. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  33787. // This is a true transposition, but it will lead to an incorrect result
  33788. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33789. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33790. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33791. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33792. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33793. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33794. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33795. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33796. // ----
  33797. tmp1 = SIMD.float32x4.mul(row2, row3);
  33798. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33799. minor0 = SIMD.float32x4.mul(row1, tmp1);
  33800. minor1 = SIMD.float32x4.mul(row0, tmp1);
  33801. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33802. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  33803. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  33804. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  33805. // ----
  33806. tmp1 = SIMD.float32x4.mul(row1, row2);
  33807. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33808. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  33809. minor3 = SIMD.float32x4.mul(row0, tmp1);
  33810. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33811. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  33812. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  33813. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  33814. // ----
  33815. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  33816. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33817. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  33818. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  33819. minor2 = SIMD.float32x4.mul(row0, tmp1);
  33820. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33821. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  33822. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  33823. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  33824. // ----
  33825. tmp1 = SIMD.float32x4.mul(row0, row1);
  33826. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33827. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  33828. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  33829. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33830. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  33831. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  33832. // ----
  33833. tmp1 = SIMD.float32x4.mul(row0, row3);
  33834. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33835. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  33836. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  33837. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33838. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  33839. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  33840. // ----
  33841. tmp1 = SIMD.float32x4.mul(row0, row2);
  33842. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33843. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  33844. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  33845. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33846. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  33847. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  33848. // Compute determinant
  33849. det = SIMD.float32x4.mul(row0, minor0);
  33850. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  33851. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  33852. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  33853. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  33854. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  33855. // These shuffles aren't necessary if the faulty transposition is done
  33856. // up at the top of this function.
  33857. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  33858. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  33859. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  33860. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  33861. // Compute final values by multiplying with 1/det
  33862. minor0 = SIMD.float32x4.mul(det, minor0);
  33863. minor1 = SIMD.float32x4.mul(det, minor1);
  33864. minor2 = SIMD.float32x4.mul(det, minor2);
  33865. minor3 = SIMD.float32x4.mul(det, minor3);
  33866. SIMD.float32x4.store(dest, 0, minor0);
  33867. SIMD.float32x4.store(dest, 4, minor1);
  33868. SIMD.float32x4.store(dest, 8, minor2);
  33869. SIMD.float32x4.store(dest, 12, minor3);
  33870. return this;
  33871. };
  33872. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  33873. var out = result.m;
  33874. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  33875. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  33876. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  33877. // cc.kmVec3Subtract(f, pCenter, pEye);
  33878. var f = SIMD.float32x4.sub(center, eye);
  33879. // cc.kmVec3Normalize(f, f);
  33880. var tmp = SIMD.float32x4.mul(f, f);
  33881. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33882. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33883. // cc.kmVec3Assign(up, pUp);
  33884. // cc.kmVec3Normalize(up, up);
  33885. tmp = SIMD.float32x4.mul(up, up);
  33886. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33887. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33888. // cc.kmVec3Cross(s, f, up);
  33889. 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)));
  33890. // cc.kmVec3Normalize(s, s);
  33891. tmp = SIMD.float32x4.mul(s, s);
  33892. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33893. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33894. // cc.kmVec3Cross(u, s, f);
  33895. 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)));
  33896. // cc.kmVec3Normalize(s, s);
  33897. tmp = SIMD.float32x4.mul(s, s);
  33898. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33899. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33900. var zero = SIMD.float32x4.splat(0.0);
  33901. s = SIMD.float32x4.neg(s);
  33902. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  33903. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  33904. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33905. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  33906. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  33907. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  33908. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33909. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  33910. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  33911. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  33912. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  33913. var b3 = SIMD.float32x4.neg(eye);
  33914. b3 = SIMD.float32x4.withW(b3, 1.0);
  33915. 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)))));
  33916. 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)))));
  33917. 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)))));
  33918. 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)))));
  33919. };
  33920. return SIMDMatrix;
  33921. })();
  33922. BABYLON.SIMDMatrix = SIMDMatrix;
  33923. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  33924. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  33925. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  33926. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  33927. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  33928. var SIMDHelper = (function () {
  33929. function SIMDHelper() {
  33930. }
  33931. Object.defineProperty(SIMDHelper, "IsEnabled", {
  33932. get: function () {
  33933. return SIMDHelper._isEnabled;
  33934. },
  33935. enumerable: true,
  33936. configurable: true
  33937. });
  33938. SIMDHelper.DisableSIMD = function () {
  33939. // Replace functions
  33940. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  33941. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  33942. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  33943. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  33944. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  33945. SIMDHelper._isEnabled = false;
  33946. };
  33947. SIMDHelper.EnableSIMD = function () {
  33948. if (window.SIMD === undefined) {
  33949. return;
  33950. }
  33951. // Replace functions
  33952. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  33953. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  33954. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  33955. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  33956. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  33957. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  33958. get: function () { return this._data[0]; },
  33959. set: function (value) {
  33960. if (!this._data) {
  33961. this._data = new Float32Array(3);
  33962. }
  33963. this._data[0] = value;
  33964. }
  33965. });
  33966. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  33967. get: function () { return this._data[1]; },
  33968. set: function (value) {
  33969. this._data[1] = value;
  33970. }
  33971. });
  33972. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  33973. get: function () { return this._data[2]; },
  33974. set: function (value) {
  33975. this._data[2] = value;
  33976. }
  33977. });
  33978. SIMDHelper._isEnabled = true;
  33979. };
  33980. SIMDHelper._isEnabled = false;
  33981. return SIMDHelper;
  33982. })();
  33983. BABYLON.SIMDHelper = SIMDHelper;
  33984. })(BABYLON || (BABYLON = {}));
  33985. var BABYLON;
  33986. (function (BABYLON) {
  33987. var ShaderMaterial = (function (_super) {
  33988. __extends(ShaderMaterial, _super);
  33989. function ShaderMaterial(name, scene, shaderPath, options) {
  33990. _super.call(this, name, scene);
  33991. this._textures = {};
  33992. this._floats = {};
  33993. this._floatsArrays = {};
  33994. this._colors3 = {};
  33995. this._colors4 = {};
  33996. this._vectors2 = {};
  33997. this._vectors3 = {};
  33998. this._vectors4 = {};
  33999. this._matrices = {};
  34000. this._matrices3x3 = {};
  34001. this._matrices2x2 = {};
  34002. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  34003. this._shaderPath = shaderPath;
  34004. options.needAlphaBlending = options.needAlphaBlending || false;
  34005. options.needAlphaTesting = options.needAlphaTesting || false;
  34006. options.attributes = options.attributes || ["position", "normal", "uv"];
  34007. options.uniforms = options.uniforms || ["worldViewProjection"];
  34008. options.samplers = options.samplers || [];
  34009. options.defines = options.defines || [];
  34010. this._options = options;
  34011. }
  34012. ShaderMaterial.prototype.needAlphaBlending = function () {
  34013. return this._options.needAlphaBlending;
  34014. };
  34015. ShaderMaterial.prototype.needAlphaTesting = function () {
  34016. return this._options.needAlphaTesting;
  34017. };
  34018. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  34019. if (this._options.uniforms.indexOf(uniformName) === -1) {
  34020. this._options.uniforms.push(uniformName);
  34021. }
  34022. };
  34023. ShaderMaterial.prototype.setTexture = function (name, texture) {
  34024. if (this._options.samplers.indexOf(name) === -1) {
  34025. this._options.samplers.push(name);
  34026. }
  34027. this._textures[name] = texture;
  34028. return this;
  34029. };
  34030. ShaderMaterial.prototype.setFloat = function (name, value) {
  34031. this._checkUniform(name);
  34032. this._floats[name] = value;
  34033. return this;
  34034. };
  34035. ShaderMaterial.prototype.setFloats = function (name, value) {
  34036. this._checkUniform(name);
  34037. this._floatsArrays[name] = value;
  34038. return this;
  34039. };
  34040. ShaderMaterial.prototype.setColor3 = function (name, value) {
  34041. this._checkUniform(name);
  34042. this._colors3[name] = value;
  34043. return this;
  34044. };
  34045. ShaderMaterial.prototype.setColor4 = function (name, value) {
  34046. this._checkUniform(name);
  34047. this._colors4[name] = value;
  34048. return this;
  34049. };
  34050. ShaderMaterial.prototype.setVector2 = function (name, value) {
  34051. this._checkUniform(name);
  34052. this._vectors2[name] = value;
  34053. return this;
  34054. };
  34055. ShaderMaterial.prototype.setVector3 = function (name, value) {
  34056. this._checkUniform(name);
  34057. this._vectors3[name] = value;
  34058. return this;
  34059. };
  34060. ShaderMaterial.prototype.setVector4 = function (name, value) {
  34061. this._checkUniform(name);
  34062. this._vectors4[name] = value;
  34063. return this;
  34064. };
  34065. ShaderMaterial.prototype.setMatrix = function (name, value) {
  34066. this._checkUniform(name);
  34067. this._matrices[name] = value;
  34068. return this;
  34069. };
  34070. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  34071. this._checkUniform(name);
  34072. this._matrices3x3[name] = value;
  34073. return this;
  34074. };
  34075. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  34076. this._checkUniform(name);
  34077. this._matrices2x2[name] = value;
  34078. return this;
  34079. };
  34080. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  34081. var scene = this.getScene();
  34082. var engine = scene.getEngine();
  34083. if (!this.checkReadyOnEveryCall) {
  34084. if (this._renderId === scene.getRenderId()) {
  34085. return true;
  34086. }
  34087. }
  34088. // Instances
  34089. var defines = [];
  34090. var fallbacks = new BABYLON.EffectFallbacks();
  34091. if (useInstances) {
  34092. defines.push("#define INSTANCES");
  34093. }
  34094. for (var index = 0; index < this._options.defines.length; index++) {
  34095. defines.push(this._options.defines[index]);
  34096. }
  34097. // Bones
  34098. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34099. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34100. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34101. fallbacks.addCPUSkinningFallback(0, mesh);
  34102. }
  34103. // Alpha test
  34104. if (engine.getAlphaTesting()) {
  34105. defines.push("#define ALPHATEST");
  34106. }
  34107. var previousEffect = this._effect;
  34108. var join = defines.join("\n");
  34109. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  34110. if (!this._effect.isReady()) {
  34111. return false;
  34112. }
  34113. if (previousEffect !== this._effect) {
  34114. scene.resetCachedMaterial();
  34115. }
  34116. this._renderId = scene.getRenderId();
  34117. return true;
  34118. };
  34119. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34120. var scene = this.getScene();
  34121. if (this._options.uniforms.indexOf("world") !== -1) {
  34122. this._effect.setMatrix("world", world);
  34123. }
  34124. if (this._options.uniforms.indexOf("worldView") !== -1) {
  34125. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  34126. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  34127. }
  34128. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  34129. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  34130. }
  34131. };
  34132. ShaderMaterial.prototype.bind = function (world, mesh) {
  34133. // Std values
  34134. this.bindOnlyWorldMatrix(world);
  34135. if (this.getScene().getCachedMaterial() !== this) {
  34136. if (this._options.uniforms.indexOf("view") !== -1) {
  34137. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  34138. }
  34139. if (this._options.uniforms.indexOf("projection") !== -1) {
  34140. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  34141. }
  34142. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  34143. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34144. }
  34145. // Bones
  34146. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34147. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  34148. }
  34149. // Texture
  34150. for (var name in this._textures) {
  34151. this._effect.setTexture(name, this._textures[name]);
  34152. }
  34153. // Float
  34154. for (name in this._floats) {
  34155. this._effect.setFloat(name, this._floats[name]);
  34156. }
  34157. // Float s
  34158. for (name in this._floatsArrays) {
  34159. this._effect.setArray(name, this._floatsArrays[name]);
  34160. }
  34161. // Color3
  34162. for (name in this._colors3) {
  34163. this._effect.setColor3(name, this._colors3[name]);
  34164. }
  34165. // Color4
  34166. for (name in this._colors4) {
  34167. var color = this._colors4[name];
  34168. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  34169. }
  34170. // Vector2
  34171. for (name in this._vectors2) {
  34172. this._effect.setVector2(name, this._vectors2[name]);
  34173. }
  34174. // Vector3
  34175. for (name in this._vectors3) {
  34176. this._effect.setVector3(name, this._vectors3[name]);
  34177. }
  34178. // Vector4
  34179. for (name in this._vectors4) {
  34180. this._effect.setVector4(name, this._vectors4[name]);
  34181. }
  34182. // Matrix
  34183. for (name in this._matrices) {
  34184. this._effect.setMatrix(name, this._matrices[name]);
  34185. }
  34186. // Matrix 3x3
  34187. for (name in this._matrices3x3) {
  34188. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  34189. }
  34190. // Matrix 2x2
  34191. for (name in this._matrices2x2) {
  34192. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  34193. }
  34194. }
  34195. _super.prototype.bind.call(this, world, mesh);
  34196. };
  34197. ShaderMaterial.prototype.clone = function (name) {
  34198. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  34199. return newShaderMaterial;
  34200. };
  34201. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  34202. for (var name in this._textures) {
  34203. this._textures[name].dispose();
  34204. }
  34205. this._textures = {};
  34206. _super.prototype.dispose.call(this, forceDisposeEffect);
  34207. };
  34208. ShaderMaterial.prototype.serialize = function () {
  34209. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34210. serializationObject.customType = "BABYLON.ShaderMaterial";
  34211. serializationObject.options = this._options;
  34212. serializationObject.shaderPath = this._shaderPath;
  34213. // Texture
  34214. serializationObject.textures = {};
  34215. for (var name in this._textures) {
  34216. serializationObject.textures[name] = this._textures[name].serialize();
  34217. }
  34218. // Float
  34219. serializationObject.floats = {};
  34220. for (name in this._floats) {
  34221. serializationObject.floats[name] = this._floats[name];
  34222. }
  34223. // Float s
  34224. serializationObject.floatArrays = {};
  34225. for (name in this._floatsArrays) {
  34226. serializationObject.floatArrays[name] = this._floatsArrays[name];
  34227. }
  34228. // Color3
  34229. serializationObject.colors3 = {};
  34230. for (name in this._colors3) {
  34231. serializationObject.colors3[name] = this._colors3[name].asArray();
  34232. }
  34233. // Color4
  34234. serializationObject.colors4 = {};
  34235. for (name in this._colors4) {
  34236. serializationObject.colors4[name] = this._colors4[name].asArray();
  34237. }
  34238. // Vector2
  34239. serializationObject.vectors2 = {};
  34240. for (name in this._vectors2) {
  34241. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  34242. }
  34243. // Vector3
  34244. serializationObject.vectors3 = {};
  34245. for (name in this._vectors3) {
  34246. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  34247. }
  34248. // Vector4
  34249. serializationObject.vectors4 = {};
  34250. for (name in this._vectors4) {
  34251. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  34252. }
  34253. // Matrix
  34254. serializationObject.matrices = {};
  34255. for (name in this._matrices) {
  34256. serializationObject.matrices[name] = this._matrices[name].asArray();
  34257. }
  34258. // Matrix 3x3
  34259. serializationObject.matrices3x3 = {};
  34260. for (name in this._matrices3x3) {
  34261. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  34262. }
  34263. // Matrix 2x2
  34264. serializationObject.matrices2x2 = {};
  34265. for (name in this._matrices2x2) {
  34266. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  34267. }
  34268. return serializationObject;
  34269. };
  34270. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  34271. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  34272. // Texture
  34273. for (var name in source.textures) {
  34274. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  34275. }
  34276. // Float
  34277. for (name in source.floats) {
  34278. material.setFloat(name, source.floats[name]);
  34279. }
  34280. // Float s
  34281. for (name in source.floatsArrays) {
  34282. material.setFloats(name, source.floatsArrays[name]);
  34283. }
  34284. // Color3
  34285. for (name in source.colors3) {
  34286. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  34287. }
  34288. // Color4
  34289. for (name in source.colors4) {
  34290. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  34291. }
  34292. // Vector2
  34293. for (name in source.vectors2) {
  34294. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  34295. }
  34296. // Vector3
  34297. for (name in source.vectors3) {
  34298. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  34299. }
  34300. // Vector4
  34301. for (name in source.vectors4) {
  34302. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  34303. }
  34304. // Matrix
  34305. for (name in source.matrices) {
  34306. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  34307. }
  34308. // Matrix 3x3
  34309. for (name in source.matrices3x3) {
  34310. material.setMatrix3x3(name, source.matrices3x3[name]);
  34311. }
  34312. // Matrix 2x2
  34313. for (name in source.matrices2x2) {
  34314. material.setMatrix2x2(name, source.matrices2x2[name]);
  34315. }
  34316. return material;
  34317. };
  34318. return ShaderMaterial;
  34319. })(BABYLON.Material);
  34320. BABYLON.ShaderMaterial = ShaderMaterial;
  34321. })(BABYLON || (BABYLON = {}));
  34322. var BABYLON;
  34323. (function (BABYLON) {
  34324. var Internals;
  34325. (function (Internals) {
  34326. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34327. // All values and structures referenced from:
  34328. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34329. var DDS_MAGIC = 0x20534444;
  34330. 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;
  34331. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34332. 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;
  34333. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34334. function FourCCToInt32(value) {
  34335. return value.charCodeAt(0) +
  34336. (value.charCodeAt(1) << 8) +
  34337. (value.charCodeAt(2) << 16) +
  34338. (value.charCodeAt(3) << 24);
  34339. }
  34340. function Int32ToFourCC(value) {
  34341. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34342. }
  34343. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34344. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34345. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34346. var headerLengthInt = 31; // The header length in 32 bit ints
  34347. // Offsets into the header array
  34348. var off_magic = 0;
  34349. var off_size = 1;
  34350. var off_flags = 2;
  34351. var off_height = 3;
  34352. var off_width = 4;
  34353. var off_mipmapCount = 7;
  34354. var off_pfFlags = 20;
  34355. var off_pfFourCC = 21;
  34356. var off_RGBbpp = 22;
  34357. var off_RMask = 23;
  34358. var off_GMask = 24;
  34359. var off_BMask = 25;
  34360. var off_AMask = 26;
  34361. var off_caps1 = 27;
  34362. var off_caps2 = 28;
  34363. ;
  34364. var DDSTools = (function () {
  34365. function DDSTools() {
  34366. }
  34367. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34368. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34369. var mipmapCount = 1;
  34370. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34371. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34372. }
  34373. return {
  34374. width: header[off_width],
  34375. height: header[off_height],
  34376. mipmapCount: mipmapCount,
  34377. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34378. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34379. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34380. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  34381. };
  34382. };
  34383. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34384. var byteArray = new Uint8Array(dataLength);
  34385. var srcData = new Uint8Array(arrayBuffer);
  34386. var index = 0;
  34387. for (var y = height - 1; y >= 0; y--) {
  34388. for (var x = 0; x < width; x++) {
  34389. var srcPos = dataOffset + (x + y * width) * 4;
  34390. byteArray[index + 2] = srcData[srcPos];
  34391. byteArray[index + 1] = srcData[srcPos + 1];
  34392. byteArray[index] = srcData[srcPos + 2];
  34393. byteArray[index + 3] = srcData[srcPos + 3];
  34394. index += 4;
  34395. }
  34396. }
  34397. return byteArray;
  34398. };
  34399. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34400. var byteArray = new Uint8Array(dataLength);
  34401. var srcData = new Uint8Array(arrayBuffer);
  34402. var index = 0;
  34403. for (var y = height - 1; y >= 0; y--) {
  34404. for (var x = 0; x < width; x++) {
  34405. var srcPos = dataOffset + (x + y * width) * 3;
  34406. byteArray[index + 2] = srcData[srcPos];
  34407. byteArray[index + 1] = srcData[srcPos + 1];
  34408. byteArray[index] = srcData[srcPos + 2];
  34409. index += 3;
  34410. }
  34411. }
  34412. return byteArray;
  34413. };
  34414. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34415. var byteArray = new Uint8Array(dataLength);
  34416. var srcData = new Uint8Array(arrayBuffer);
  34417. var index = 0;
  34418. for (var y = height - 1; y >= 0; y--) {
  34419. for (var x = 0; x < width; x++) {
  34420. var srcPos = dataOffset + (x + y * width);
  34421. byteArray[index] = srcData[srcPos];
  34422. index++;
  34423. }
  34424. }
  34425. return byteArray;
  34426. };
  34427. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  34428. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  34429. if (header[off_magic] != DDS_MAGIC) {
  34430. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34431. return;
  34432. }
  34433. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34434. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34435. return;
  34436. }
  34437. if (info.isFourCC) {
  34438. fourCC = header[off_pfFourCC];
  34439. switch (fourCC) {
  34440. case FOURCC_DXT1:
  34441. blockBytes = 8;
  34442. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34443. break;
  34444. case FOURCC_DXT3:
  34445. blockBytes = 16;
  34446. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34447. break;
  34448. case FOURCC_DXT5:
  34449. blockBytes = 16;
  34450. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34451. break;
  34452. default:
  34453. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34454. return;
  34455. }
  34456. }
  34457. mipmapCount = 1;
  34458. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34459. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34460. }
  34461. var bpp = header[off_RGBbpp];
  34462. for (var face = 0; face < faces; face++) {
  34463. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34464. width = header[off_width];
  34465. height = header[off_height];
  34466. dataOffset = header[off_size] + 4;
  34467. for (i = 0; i < mipmapCount; ++i) {
  34468. if (info.isRGB) {
  34469. if (bpp === 24) {
  34470. dataLength = width * height * 3;
  34471. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34472. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34473. }
  34474. else {
  34475. dataLength = width * height * 4;
  34476. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34477. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34478. }
  34479. }
  34480. else if (info.isLuminance) {
  34481. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34482. var unpaddedRowSize = width;
  34483. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34484. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34485. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34486. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34487. }
  34488. else {
  34489. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34490. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34491. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  34492. }
  34493. dataOffset += dataLength;
  34494. width *= 0.5;
  34495. height *= 0.5;
  34496. width = Math.max(1.0, width);
  34497. height = Math.max(1.0, height);
  34498. }
  34499. }
  34500. };
  34501. return DDSTools;
  34502. })();
  34503. Internals.DDSTools = DDSTools;
  34504. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34505. })(BABYLON || (BABYLON = {}));
  34506. var BABYLON;
  34507. (function (BABYLON) {
  34508. var CannonJSPlugin = (function () {
  34509. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  34510. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  34511. if (iterations === void 0) { iterations = 10; }
  34512. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  34513. this.name = "CannonJSPlugin";
  34514. this._physicsMaterials = [];
  34515. this._fixedTimeStep = 1 / 60;
  34516. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34517. this._currentCollisionGroup = 2;
  34518. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  34519. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  34520. this._tmpPosition = BABYLON.Vector3.Zero();
  34521. this._tmpQuaternion = new BABYLON.Quaternion();
  34522. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  34523. this._tmpDeltaRotation = new BABYLON.Quaternion();
  34524. this._tmpUnityRotation = new BABYLON.Quaternion();
  34525. if (!this.isSupported()) {
  34526. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  34527. return;
  34528. }
  34529. this.world = new CANNON.World();
  34530. this.world.broadphase = new CANNON.NaiveBroadphase();
  34531. this.world.solver.iterations = iterations;
  34532. }
  34533. CannonJSPlugin.prototype.setGravity = function (gravity) {
  34534. this.world.gravity.copy(gravity);
  34535. };
  34536. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  34537. this._fixedTimeStep = timeStep;
  34538. };
  34539. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  34540. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  34541. };
  34542. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  34543. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34544. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34545. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34546. };
  34547. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  34548. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34549. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34550. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34551. };
  34552. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  34553. //parent-child relationship. Does this impostor has a parent impostor?
  34554. if (impostor.parent) {
  34555. if (impostor.physicsBody) {
  34556. this.removePhysicsBody(impostor);
  34557. //TODO is that needed?
  34558. impostor.forceUpdate();
  34559. }
  34560. return;
  34561. }
  34562. //should a new body be created for this impostor?
  34563. if (impostor.isBodyInitRequired()) {
  34564. var shape = this._createShape(impostor);
  34565. //unregister events, if body is being changed
  34566. var oldBody = impostor.physicsBody;
  34567. if (oldBody) {
  34568. this.removePhysicsBody(impostor);
  34569. }
  34570. //create the body and material
  34571. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  34572. var bodyCreationObject = {
  34573. mass: impostor.getParam("mass"),
  34574. material: material
  34575. };
  34576. // A simple extend, in case native options were used.
  34577. var nativeOptions = impostor.getParam("nativeOptions");
  34578. for (var key in nativeOptions) {
  34579. if (nativeOptions.hasOwnProperty(key)) {
  34580. bodyCreationObject[key] = nativeOptions[key];
  34581. }
  34582. }
  34583. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  34584. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  34585. this.world.addEventListener("preStep", impostor.beforeStep);
  34586. this.world.addEventListener("postStep", impostor.afterStep);
  34587. impostor.physicsBody.addShape(shape);
  34588. this.world.add(impostor.physicsBody);
  34589. //try to keep the body moving in the right direction by taking old properties.
  34590. //Should be tested!
  34591. if (oldBody) {
  34592. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  34593. impostor.physicsBody[param].copy(oldBody[param]);
  34594. });
  34595. }
  34596. this._processChildMeshes(impostor);
  34597. }
  34598. //now update the body's transformation
  34599. this._updatePhysicsBodyTransformation(impostor);
  34600. };
  34601. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  34602. var _this = this;
  34603. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  34604. if (meshChildren.length) {
  34605. var processMesh = function (localPosition, mesh) {
  34606. var childImpostor = mesh.getPhysicsImpostor();
  34607. if (childImpostor) {
  34608. var parent = childImpostor.parent;
  34609. if (parent !== mainImpostor) {
  34610. var localPosition = mesh.position;
  34611. if (childImpostor.physicsBody) {
  34612. _this.removePhysicsBody(childImpostor);
  34613. childImpostor.physicsBody = null;
  34614. }
  34615. childImpostor.parent = mainImpostor;
  34616. childImpostor.resetUpdateFlags();
  34617. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  34618. //Add the mass of the children.
  34619. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  34620. }
  34621. }
  34622. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  34623. };
  34624. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  34625. }
  34626. };
  34627. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  34628. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  34629. this.world.removeEventListener("preStep", impostor.beforeStep);
  34630. this.world.removeEventListener("postStep", impostor.afterStep);
  34631. this.world.remove(impostor.physicsBody);
  34632. };
  34633. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  34634. var mainBody = impostorJoint.mainImpostor.physicsBody;
  34635. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  34636. if (!mainBody || !connectedBody) {
  34637. return;
  34638. }
  34639. var constraint;
  34640. var jointData = impostorJoint.joint.jointData;
  34641. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34642. var constraintData = {
  34643. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  34644. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  34645. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  34646. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  34647. maxForce: jointData.nativeParams.maxForce,
  34648. collideConnected: !!jointData.collision
  34649. };
  34650. //Not needed, Cannon has a collideConnected flag
  34651. /*if (!jointData.collision) {
  34652. //add 1st body to a collision group of its own, if it is not in 1
  34653. if (mainBody.collisionFilterGroup === 1) {
  34654. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  34655. this._currentCollisionGroup <<= 1;
  34656. }
  34657. if (connectedBody.collisionFilterGroup === 1) {
  34658. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  34659. this._currentCollisionGroup <<= 1;
  34660. }
  34661. //add their mask to the collisionFilterMask of each other:
  34662. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  34663. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  34664. }*/
  34665. switch (impostorJoint.joint.type) {
  34666. case BABYLON.PhysicsJoint.HingeJoint:
  34667. case BABYLON.PhysicsJoint.Hinge2Joint:
  34668. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  34669. break;
  34670. case BABYLON.PhysicsJoint.DistanceJoint:
  34671. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  34672. break;
  34673. case BABYLON.PhysicsJoint.SpringJoint:
  34674. var springData = jointData;
  34675. constraint = new CANNON.Spring(mainBody, connectedBody, {
  34676. restLength: springData.length,
  34677. stiffness: springData.stiffness,
  34678. damping: springData.damping,
  34679. localAnchorA: constraintData.pivotA,
  34680. localAnchorB: constraintData.pivotB
  34681. });
  34682. break;
  34683. case BABYLON.PhysicsJoint.PointToPointJoint:
  34684. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  34685. default:
  34686. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  34687. break;
  34688. }
  34689. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  34690. constraint.collideConnected = !!jointData.collision;
  34691. impostorJoint.joint.physicsJoint = constraint;
  34692. //don't add spring as constraint, as it is not one.
  34693. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  34694. this.world.addConstraint(constraint);
  34695. }
  34696. else {
  34697. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  34698. constraint.applyForce();
  34699. });
  34700. }
  34701. };
  34702. CannonJSPlugin.prototype.removeJoint = function (joint) {
  34703. //TODO
  34704. };
  34705. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  34706. var index;
  34707. var mat;
  34708. for (index = 0; index < this._physicsMaterials.length; index++) {
  34709. mat = this._physicsMaterials[index];
  34710. if (mat.friction === friction && mat.restitution === restitution) {
  34711. return mat;
  34712. }
  34713. }
  34714. var currentMat = new CANNON.Material("mat");
  34715. currentMat.friction = friction;
  34716. currentMat.restitution = restitution;
  34717. this._physicsMaterials.push(currentMat);
  34718. return currentMat;
  34719. };
  34720. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  34721. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  34722. };
  34723. CannonJSPlugin.prototype._createShape = function (impostor) {
  34724. var object = impostor.object;
  34725. var returnValue;
  34726. var extendSize = impostor.getObjectExtendSize();
  34727. switch (impostor.type) {
  34728. case BABYLON.PhysicsEngine.SphereImpostor:
  34729. var radiusX = extendSize.x;
  34730. var radiusY = extendSize.y;
  34731. var radiusZ = extendSize.z;
  34732. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  34733. break;
  34734. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  34735. case BABYLON.PhysicsImpostor.CylinderImpostor:
  34736. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  34737. break;
  34738. case BABYLON.PhysicsImpostor.BoxImpostor:
  34739. var box = extendSize.scale(0.5);
  34740. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  34741. break;
  34742. case BABYLON.PhysicsImpostor.PlaneImpostor:
  34743. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  34744. returnValue = new CANNON.Plane();
  34745. break;
  34746. case BABYLON.PhysicsImpostor.MeshImpostor:
  34747. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  34748. var rawFaces = object.getIndices ? object.getIndices() : [];
  34749. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  34750. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  34751. break;
  34752. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  34753. returnValue = this._createHeightmap(object);
  34754. break;
  34755. case BABYLON.PhysicsImpostor.ParticleImpostor:
  34756. returnValue = new CANNON.Particle();
  34757. break;
  34758. }
  34759. return returnValue;
  34760. };
  34761. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  34762. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34763. var matrix = [];
  34764. //For now pointDepth will not be used and will be automatically calculated.
  34765. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  34766. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  34767. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  34768. var elementSize = dim * 2 / arraySize;
  34769. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  34770. for (var i = 0; i < pos.length; i = i + 3) {
  34771. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  34772. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  34773. var y = pos[i + 1] + minY;
  34774. if (!matrix[x]) {
  34775. matrix[x] = [];
  34776. }
  34777. if (!matrix[x][z]) {
  34778. matrix[x][z] = y;
  34779. }
  34780. matrix[x][z] = Math.max(y, matrix[x][z]);
  34781. }
  34782. for (var x = 0; x <= arraySize; ++x) {
  34783. if (!matrix[x]) {
  34784. var loc = 1;
  34785. while (!matrix[(x + loc) % arraySize]) {
  34786. loc++;
  34787. }
  34788. matrix[x] = matrix[(x + loc) % arraySize].slice();
  34789. }
  34790. for (var z = 0; z <= arraySize; ++z) {
  34791. if (!matrix[x][z]) {
  34792. var loc = 1;
  34793. var newValue;
  34794. while (newValue === undefined) {
  34795. newValue = matrix[x][(z + loc++) % arraySize];
  34796. }
  34797. matrix[x][z] = newValue;
  34798. }
  34799. }
  34800. }
  34801. var shape = new CANNON.Heightfield(matrix, {
  34802. elementSize: elementSize
  34803. });
  34804. //For future reference, needed for body transformation
  34805. shape.minY = minY;
  34806. return shape;
  34807. };
  34808. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  34809. var object = impostor.object;
  34810. //make sure it is updated...
  34811. object.computeWorldMatrix && object.computeWorldMatrix(true);
  34812. // The delta between the mesh position and the mesh bounding box center
  34813. var center = impostor.getObjectCenter();
  34814. var extendSize = impostor.getObjectExtendSize();
  34815. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  34816. this._tmpPosition.copyFrom(center);
  34817. var quaternion = object.rotationQuaternion;
  34818. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  34819. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  34820. //-90 DEG in X, precalculated
  34821. quaternion = quaternion.multiply(this._minus90X);
  34822. //Invert! (Precalculated, 90 deg in X)
  34823. //No need to clone. this will never change.
  34824. impostor.setDeltaRotation(this._plus90X);
  34825. }
  34826. //If it is a heightfield, if should be centered.
  34827. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  34828. var mesh = object;
  34829. //calculate the correct body position:
  34830. var rotationQuaternion = mesh.rotationQuaternion;
  34831. mesh.rotationQuaternion = this._tmpUnityRotation;
  34832. mesh.computeWorldMatrix(true);
  34833. //get original center with no rotation
  34834. var c = center.clone();
  34835. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  34836. //rotation is back
  34837. mesh.rotationQuaternion = rotationQuaternion;
  34838. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  34839. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  34840. mesh.setPivotMatrix(p);
  34841. mesh.computeWorldMatrix(true);
  34842. //calculate the translation
  34843. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  34844. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  34845. //add it inverted to the delta
  34846. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  34847. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  34848. mesh.setPivotMatrix(oldPivot);
  34849. mesh.computeWorldMatrix(true);
  34850. }
  34851. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  34852. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  34853. this._tmpPosition.copyFrom(object.position);
  34854. }
  34855. impostor.setDeltaPosition(this._tmpDeltaPosition);
  34856. //Now update the impostor object
  34857. impostor.physicsBody.position.copy(this._tmpPosition);
  34858. impostor.physicsBody.quaternion.copy(quaternion);
  34859. };
  34860. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  34861. impostor.object.position.copyFrom(impostor.physicsBody.position);
  34862. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  34863. };
  34864. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  34865. impostor.physicsBody.position.copy(newPosition);
  34866. impostor.physicsBody.quaternion.copy(newRotation);
  34867. };
  34868. CannonJSPlugin.prototype.isSupported = function () {
  34869. return window.CANNON !== undefined;
  34870. };
  34871. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  34872. impostor.physicsBody.velocity.copy(velocity);
  34873. };
  34874. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  34875. impostor.physicsBody.angularVelocity.copy(velocity);
  34876. };
  34877. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  34878. var v = impostor.physicsBody.velocity;
  34879. if (!v)
  34880. return null;
  34881. return new BABYLON.Vector3(v.x, v.y, v.z);
  34882. };
  34883. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  34884. var v = impostor.physicsBody.angularVelocity;
  34885. if (!v)
  34886. return null;
  34887. return new BABYLON.Vector3(v.x, v.y, v.z);
  34888. };
  34889. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  34890. impostor.physicsBody.mass = mass;
  34891. impostor.physicsBody.updateMassProperties();
  34892. };
  34893. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  34894. impostor.physicsBody.sleep();
  34895. };
  34896. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  34897. impostor.physicsBody.wakeUp();
  34898. };
  34899. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  34900. joint.physicsJoint.distance = maxDistance;
  34901. };
  34902. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  34903. if (!motorIndex) {
  34904. joint.physicsJoint.enableMotor();
  34905. }
  34906. };
  34907. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  34908. if (!motorIndex) {
  34909. joint.physicsJoint.disableMotor();
  34910. }
  34911. };
  34912. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  34913. if (!motorIndex) {
  34914. joint.physicsJoint.enableMotor();
  34915. joint.physicsJoint.setMotorSpeed(speed);
  34916. if (maxForce) {
  34917. this.setLimit(joint, maxForce);
  34918. }
  34919. }
  34920. };
  34921. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  34922. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  34923. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  34924. };
  34925. CannonJSPlugin.prototype.dispose = function () {
  34926. //nothing to do, actually.
  34927. };
  34928. return CannonJSPlugin;
  34929. })();
  34930. BABYLON.CannonJSPlugin = CannonJSPlugin;
  34931. })(BABYLON || (BABYLON = {}));
  34932. var BABYLON;
  34933. (function (BABYLON) {
  34934. var OimoJSPlugin = (function () {
  34935. function OimoJSPlugin(iterations) {
  34936. this.name = "OimoJSPlugin";
  34937. this._tmpImpostorsArray = [];
  34938. this._tmpPositionVector = BABYLON.Vector3.Zero();
  34939. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  34940. this.world.clear();
  34941. //making sure no stats are calculated
  34942. this.world.isNoStat = true;
  34943. }
  34944. OimoJSPlugin.prototype.setGravity = function (gravity) {
  34945. this.world.gravity.copy(gravity);
  34946. };
  34947. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  34948. this.world.timeStep = timeStep;
  34949. };
  34950. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  34951. var _this = this;
  34952. impostors.forEach(function (impostor) {
  34953. impostor.beforeStep();
  34954. });
  34955. this.world.step();
  34956. impostors.forEach(function (impostor) {
  34957. impostor.afterStep();
  34958. //update the ordered impostors array
  34959. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  34960. });
  34961. //check for collisions
  34962. var contact = this.world.contacts;
  34963. while (contact !== null) {
  34964. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  34965. contact = contact.next;
  34966. continue;
  34967. }
  34968. //is this body colliding with any other? get the impostor
  34969. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  34970. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  34971. if (!mainImpostor || !collidingImpostor) {
  34972. contact = contact.next;
  34973. continue;
  34974. }
  34975. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  34976. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  34977. contact = contact.next;
  34978. }
  34979. };
  34980. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  34981. var mass = impostor.physicsBody.massInfo.mass;
  34982. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  34983. };
  34984. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  34985. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  34986. this.applyImpulse(impostor, force, contactPoint);
  34987. };
  34988. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  34989. var _this = this;
  34990. //parent-child relationship. Does this impostor has a parent impostor?
  34991. if (impostor.parent) {
  34992. if (impostor.physicsBody) {
  34993. this.removePhysicsBody(impostor);
  34994. //TODO is that needed?
  34995. impostor.forceUpdate();
  34996. }
  34997. return;
  34998. }
  34999. if (impostor.isBodyInitRequired()) {
  35000. var bodyConfig = {
  35001. name: impostor.uniqueId,
  35002. //Oimo must have mass, also for static objects.
  35003. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  35004. size: [],
  35005. type: [],
  35006. pos: [],
  35007. rot: [],
  35008. move: impostor.getParam("mass") !== 0,
  35009. //Supporting older versions of Oimo
  35010. world: this.world
  35011. };
  35012. var impostors = [impostor];
  35013. function addToArray(parent) {
  35014. if (!parent.getChildMeshes)
  35015. return;
  35016. parent.getChildMeshes().forEach(function (m) {
  35017. if (m.physicsImpostor) {
  35018. impostors.push(m.physicsImpostor);
  35019. m.physicsImpostor._init();
  35020. }
  35021. });
  35022. }
  35023. addToArray(impostor.object);
  35024. function checkWithEpsilon(value) {
  35025. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  35026. }
  35027. impostors.forEach(function (i) {
  35028. //get the correct bounding box
  35029. var oldQuaternion = i.object.rotationQuaternion;
  35030. var rot = new OIMO.Euler().setFromQuaternion({
  35031. x: impostor.object.rotationQuaternion.x,
  35032. y: impostor.object.rotationQuaternion.y,
  35033. z: impostor.object.rotationQuaternion.z,
  35034. s: impostor.object.rotationQuaternion.w });
  35035. var extendSize = i.getObjectExtendSize();
  35036. if (i === impostor) {
  35037. var center = impostor.getObjectCenter();
  35038. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  35039. //Can also use Array.prototype.push.apply
  35040. bodyConfig.pos.push(center.x);
  35041. bodyConfig.pos.push(center.y);
  35042. bodyConfig.pos.push(center.z);
  35043. //tmp solution
  35044. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  35045. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  35046. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  35047. }
  35048. else {
  35049. bodyConfig.pos.push(i.object.position.x);
  35050. bodyConfig.pos.push(i.object.position.y);
  35051. bodyConfig.pos.push(i.object.position.z);
  35052. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  35053. bodyConfig.rot.push(0);
  35054. bodyConfig.rot.push(0);
  35055. bodyConfig.rot.push(0);
  35056. }
  35057. // register mesh
  35058. switch (i.type) {
  35059. case BABYLON.PhysicsImpostor.ParticleImpostor:
  35060. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  35061. case BABYLON.PhysicsImpostor.SphereImpostor:
  35062. var radiusX = extendSize.x;
  35063. var radiusY = extendSize.y;
  35064. var radiusZ = extendSize.z;
  35065. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  35066. bodyConfig.type.push('sphere');
  35067. //due to the way oimo works with compounds, add 3 times
  35068. bodyConfig.size.push(size);
  35069. bodyConfig.size.push(size);
  35070. bodyConfig.size.push(size);
  35071. break;
  35072. case BABYLON.PhysicsImpostor.CylinderImpostor:
  35073. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  35074. var sizeY = checkWithEpsilon(extendSize.y);
  35075. bodyConfig.type.push('cylinder');
  35076. bodyConfig.size.push(sizeX);
  35077. bodyConfig.size.push(sizeY);
  35078. //due to the way oimo works with compounds, add one more value.
  35079. bodyConfig.size.push(sizeY);
  35080. break;
  35081. case BABYLON.PhysicsImpostor.PlaneImpostor:
  35082. case BABYLON.PhysicsImpostor.BoxImpostor:
  35083. default:
  35084. var sizeX = checkWithEpsilon(extendSize.x);
  35085. var sizeY = checkWithEpsilon(extendSize.y);
  35086. var sizeZ = checkWithEpsilon(extendSize.z);
  35087. bodyConfig.type.push('box');
  35088. bodyConfig.size.push(sizeX);
  35089. bodyConfig.size.push(sizeY);
  35090. bodyConfig.size.push(sizeZ);
  35091. break;
  35092. }
  35093. //actually not needed, but hey...
  35094. i.object.rotationQuaternion = oldQuaternion;
  35095. });
  35096. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  35097. }
  35098. else {
  35099. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  35100. }
  35101. impostor.setDeltaPosition(this._tmpPositionVector);
  35102. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  35103. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  35104. };
  35105. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  35106. //impostor.physicsBody.dispose();
  35107. //Same as : (older oimo versions)
  35108. this.world.removeRigidBody(impostor.physicsBody);
  35109. };
  35110. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  35111. var mainBody = impostorJoint.mainImpostor.physicsBody;
  35112. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  35113. if (!mainBody || !connectedBody) {
  35114. return;
  35115. }
  35116. var jointData = impostorJoint.joint.jointData;
  35117. var options = jointData.nativeParams || {};
  35118. var type;
  35119. var nativeJointData = {
  35120. body1: mainBody,
  35121. body2: connectedBody,
  35122. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  35123. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  35124. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  35125. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  35126. min: options.min,
  35127. max: options.max,
  35128. collision: options.collision || jointData.collision,
  35129. spring: options.spring,
  35130. //supporting older version of Oimo
  35131. world: this.world
  35132. };
  35133. switch (impostorJoint.joint.type) {
  35134. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  35135. type = "jointBall";
  35136. break;
  35137. case BABYLON.PhysicsJoint.SpringJoint:
  35138. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  35139. var springData = jointData;
  35140. nativeJointData.min = springData.length || nativeJointData.min;
  35141. //Max should also be set, just make sure it is at least min
  35142. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  35143. case BABYLON.PhysicsJoint.DistanceJoint:
  35144. type = "jointDistance";
  35145. nativeJointData.max = jointData.maxDistance;
  35146. break;
  35147. case BABYLON.PhysicsJoint.PrismaticJoint:
  35148. type = "jointPrisme";
  35149. break;
  35150. case BABYLON.PhysicsJoint.SliderJoint:
  35151. type = "jointSlide";
  35152. break;
  35153. case BABYLON.PhysicsJoint.WheelJoint:
  35154. type = "jointWheel";
  35155. break;
  35156. case BABYLON.PhysicsJoint.HingeJoint:
  35157. default:
  35158. type = "jointHinge";
  35159. break;
  35160. }
  35161. nativeJointData.type = type;
  35162. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  35163. };
  35164. OimoJSPlugin.prototype.removeJoint = function (joint) {
  35165. joint.joint.physicsJoint.dispose();
  35166. };
  35167. OimoJSPlugin.prototype.isSupported = function () {
  35168. return OIMO !== undefined;
  35169. };
  35170. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  35171. if (!impostor.physicsBody.sleeping) {
  35172. //TODO check that
  35173. if (impostor.physicsBody.shapes.next) {
  35174. var parentShape = this._getLastShape(impostor.physicsBody);
  35175. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  35176. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  35177. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  35178. }
  35179. else {
  35180. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  35181. }
  35182. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  35183. }
  35184. };
  35185. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  35186. var body = impostor.physicsBody;
  35187. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  35188. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  35189. body.syncShapes();
  35190. body.awake();
  35191. };
  35192. OimoJSPlugin.prototype._getLastShape = function (body) {
  35193. var lastShape = body.shapes;
  35194. while (lastShape.next) {
  35195. lastShape = lastShape.next;
  35196. }
  35197. return lastShape;
  35198. };
  35199. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  35200. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  35201. };
  35202. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  35203. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  35204. };
  35205. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  35206. var v = impostor.physicsBody.linearVelocity;
  35207. if (!v)
  35208. return null;
  35209. return new BABYLON.Vector3(v.x, v.y, v.z);
  35210. };
  35211. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  35212. var v = impostor.physicsBody.angularVelocity;
  35213. if (!v)
  35214. return null;
  35215. return new BABYLON.Vector3(v.x, v.y, v.z);
  35216. };
  35217. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  35218. var staticBody = mass === 0;
  35219. //this will actually set the body's density and not its mass.
  35220. //But this is how oimo treats the mass variable.
  35221. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  35222. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  35223. };
  35224. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  35225. impostor.physicsBody.sleep();
  35226. };
  35227. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  35228. impostor.physicsBody.awake();
  35229. };
  35230. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  35231. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  35232. if (minDistance !== void 0) {
  35233. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  35234. }
  35235. };
  35236. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  35237. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  35238. if (motor) {
  35239. motor.setMotor(speed, maxForce);
  35240. }
  35241. };
  35242. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  35243. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  35244. if (motor) {
  35245. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  35246. }
  35247. };
  35248. OimoJSPlugin.prototype.dispose = function () {
  35249. this.world.clear();
  35250. };
  35251. return OimoJSPlugin;
  35252. })();
  35253. BABYLON.OimoJSPlugin = OimoJSPlugin;
  35254. })(BABYLON || (BABYLON = {}));
  35255. var BABYLON;
  35256. (function (BABYLON) {
  35257. var DisplayPassPostProcess = (function (_super) {
  35258. __extends(DisplayPassPostProcess, _super);
  35259. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35260. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  35261. }
  35262. return DisplayPassPostProcess;
  35263. })(BABYLON.PostProcess);
  35264. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  35265. })(BABYLON || (BABYLON = {}));
  35266. var BABYLON;
  35267. (function (BABYLON) {
  35268. var SimplificationSettings = (function () {
  35269. function SimplificationSettings(quality, distance, optimizeMesh) {
  35270. this.quality = quality;
  35271. this.distance = distance;
  35272. this.optimizeMesh = optimizeMesh;
  35273. }
  35274. return SimplificationSettings;
  35275. })();
  35276. BABYLON.SimplificationSettings = SimplificationSettings;
  35277. var SimplificationQueue = (function () {
  35278. function SimplificationQueue() {
  35279. this.running = false;
  35280. this._simplificationArray = [];
  35281. }
  35282. SimplificationQueue.prototype.addTask = function (task) {
  35283. this._simplificationArray.push(task);
  35284. };
  35285. SimplificationQueue.prototype.executeNext = function () {
  35286. var task = this._simplificationArray.pop();
  35287. if (task) {
  35288. this.running = true;
  35289. this.runSimplification(task);
  35290. }
  35291. else {
  35292. this.running = false;
  35293. }
  35294. };
  35295. SimplificationQueue.prototype.runSimplification = function (task) {
  35296. var _this = this;
  35297. if (task.parallelProcessing) {
  35298. //parallel simplifier
  35299. task.settings.forEach(function (setting) {
  35300. var simplifier = _this.getSimplifier(task);
  35301. simplifier.simplify(setting, function (newMesh) {
  35302. task.mesh.addLODLevel(setting.distance, newMesh);
  35303. newMesh.isVisible = true;
  35304. //check if it is the last
  35305. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  35306. //all done, run the success callback.
  35307. task.successCallback();
  35308. }
  35309. _this.executeNext();
  35310. });
  35311. });
  35312. }
  35313. else {
  35314. //single simplifier.
  35315. var simplifier = this.getSimplifier(task);
  35316. var runDecimation = function (setting, callback) {
  35317. simplifier.simplify(setting, function (newMesh) {
  35318. task.mesh.addLODLevel(setting.distance, newMesh);
  35319. newMesh.isVisible = true;
  35320. //run the next quality level
  35321. callback();
  35322. });
  35323. };
  35324. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  35325. runDecimation(task.settings[loop.index], function () {
  35326. loop.executeNext();
  35327. });
  35328. }, function () {
  35329. //execution ended, run the success callback.
  35330. if (task.successCallback) {
  35331. task.successCallback();
  35332. }
  35333. _this.executeNext();
  35334. });
  35335. }
  35336. };
  35337. SimplificationQueue.prototype.getSimplifier = function (task) {
  35338. switch (task.simplificationType) {
  35339. case SimplificationType.QUADRATIC:
  35340. default:
  35341. return new QuadraticErrorSimplification(task.mesh);
  35342. }
  35343. };
  35344. return SimplificationQueue;
  35345. })();
  35346. BABYLON.SimplificationQueue = SimplificationQueue;
  35347. /**
  35348. * The implemented types of simplification.
  35349. * At the moment only Quadratic Error Decimation is implemented.
  35350. */
  35351. (function (SimplificationType) {
  35352. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  35353. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  35354. var SimplificationType = BABYLON.SimplificationType;
  35355. var DecimationTriangle = (function () {
  35356. function DecimationTriangle(vertices) {
  35357. this.vertices = vertices;
  35358. this.error = new Array(4);
  35359. this.deleted = false;
  35360. this.isDirty = false;
  35361. this.deletePending = false;
  35362. this.borderFactor = 0;
  35363. }
  35364. return DecimationTriangle;
  35365. })();
  35366. BABYLON.DecimationTriangle = DecimationTriangle;
  35367. var DecimationVertex = (function () {
  35368. function DecimationVertex(position, id) {
  35369. this.position = position;
  35370. this.id = id;
  35371. this.isBorder = true;
  35372. this.q = new QuadraticMatrix();
  35373. this.triangleCount = 0;
  35374. this.triangleStart = 0;
  35375. this.originalOffsets = [];
  35376. }
  35377. DecimationVertex.prototype.updatePosition = function (newPosition) {
  35378. this.position.copyFrom(newPosition);
  35379. };
  35380. return DecimationVertex;
  35381. })();
  35382. BABYLON.DecimationVertex = DecimationVertex;
  35383. var QuadraticMatrix = (function () {
  35384. function QuadraticMatrix(data) {
  35385. this.data = new Array(10);
  35386. for (var i = 0; i < 10; ++i) {
  35387. if (data && data[i]) {
  35388. this.data[i] = data[i];
  35389. }
  35390. else {
  35391. this.data[i] = 0;
  35392. }
  35393. }
  35394. }
  35395. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  35396. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  35397. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  35398. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  35399. return det;
  35400. };
  35401. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  35402. for (var i = 0; i < 10; ++i) {
  35403. this.data[i] += matrix.data[i];
  35404. }
  35405. };
  35406. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  35407. for (var i = 0; i < 10; ++i) {
  35408. this.data[i] += data[i];
  35409. }
  35410. };
  35411. QuadraticMatrix.prototype.add = function (matrix) {
  35412. var m = new QuadraticMatrix();
  35413. for (var i = 0; i < 10; ++i) {
  35414. m.data[i] = this.data[i] + matrix.data[i];
  35415. }
  35416. return m;
  35417. };
  35418. QuadraticMatrix.FromData = function (a, b, c, d) {
  35419. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  35420. };
  35421. //returning an array to avoid garbage collection
  35422. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  35423. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  35424. };
  35425. return QuadraticMatrix;
  35426. })();
  35427. BABYLON.QuadraticMatrix = QuadraticMatrix;
  35428. var Reference = (function () {
  35429. function Reference(vertexId, triangleId) {
  35430. this.vertexId = vertexId;
  35431. this.triangleId = triangleId;
  35432. }
  35433. return Reference;
  35434. })();
  35435. BABYLON.Reference = Reference;
  35436. /**
  35437. * An implementation of the Quadratic Error simplification algorithm.
  35438. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  35439. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  35440. * @author RaananW
  35441. */
  35442. var QuadraticErrorSimplification = (function () {
  35443. function QuadraticErrorSimplification(_mesh) {
  35444. this._mesh = _mesh;
  35445. this.initialized = false;
  35446. this.syncIterations = 5000;
  35447. this.aggressiveness = 7;
  35448. this.decimationIterations = 100;
  35449. this.boundingBoxEpsilon = BABYLON.Epsilon;
  35450. }
  35451. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  35452. var _this = this;
  35453. this.initDecimatedMesh();
  35454. //iterating through the submeshes array, one after the other.
  35455. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  35456. _this.initWithMesh(loop.index, function () {
  35457. _this.runDecimation(settings, loop.index, function () {
  35458. loop.executeNext();
  35459. });
  35460. }, settings.optimizeMesh);
  35461. }, function () {
  35462. setTimeout(function () {
  35463. successCallback(_this._reconstructedMesh);
  35464. }, 0);
  35465. });
  35466. };
  35467. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  35468. var _this = this;
  35469. var gCount = 0;
  35470. triangle.vertices.forEach(function (vertex) {
  35471. var count = 0;
  35472. var vPos = vertex.position;
  35473. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  35474. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  35475. ++count;
  35476. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  35477. ++count;
  35478. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  35479. ++count;
  35480. if (count > 1) {
  35481. ++gCount;
  35482. }
  35483. ;
  35484. });
  35485. if (gCount > 1) {
  35486. console.log(triangle, gCount);
  35487. }
  35488. return gCount > 1;
  35489. };
  35490. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  35491. var _this = this;
  35492. var targetCount = ~~(this.triangles.length * settings.quality);
  35493. var deletedTriangles = 0;
  35494. var triangleCount = this.triangles.length;
  35495. var iterationFunction = function (iteration, callback) {
  35496. setTimeout(function () {
  35497. if (iteration % 5 === 0) {
  35498. _this.updateMesh(iteration === 0);
  35499. }
  35500. for (var i = 0; i < _this.triangles.length; ++i) {
  35501. _this.triangles[i].isDirty = false;
  35502. }
  35503. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  35504. var trianglesIterator = function (i) {
  35505. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  35506. var t = _this.triangles[tIdx];
  35507. if (!t)
  35508. return;
  35509. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  35510. return;
  35511. }
  35512. for (var j = 0; j < 3; ++j) {
  35513. if (t.error[j] < threshold) {
  35514. var deleted0 = [];
  35515. var deleted1 = [];
  35516. var v0 = t.vertices[j];
  35517. var v1 = t.vertices[(j + 1) % 3];
  35518. if (v0.isBorder || v1.isBorder)
  35519. continue;
  35520. var p = BABYLON.Vector3.Zero();
  35521. var n = BABYLON.Vector3.Zero();
  35522. var uv = BABYLON.Vector2.Zero();
  35523. var color = new BABYLON.Color4(0, 0, 0, 1);
  35524. _this.calculateError(v0, v1, p, n, uv, color);
  35525. var delTr = [];
  35526. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  35527. continue;
  35528. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  35529. continue;
  35530. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  35531. continue;
  35532. var uniqueArray = [];
  35533. delTr.forEach(function (deletedT) {
  35534. if (uniqueArray.indexOf(deletedT) === -1) {
  35535. deletedT.deletePending = true;
  35536. uniqueArray.push(deletedT);
  35537. }
  35538. });
  35539. if (uniqueArray.length % 2 !== 0) {
  35540. continue;
  35541. }
  35542. v0.q = v1.q.add(v0.q);
  35543. v0.updatePosition(p);
  35544. var tStart = _this.references.length;
  35545. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  35546. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  35547. var tCount = _this.references.length - tStart;
  35548. if (tCount <= v0.triangleCount) {
  35549. if (tCount) {
  35550. for (var c = 0; c < tCount; c++) {
  35551. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  35552. }
  35553. }
  35554. }
  35555. else {
  35556. v0.triangleStart = tStart;
  35557. }
  35558. v0.triangleCount = tCount;
  35559. break;
  35560. }
  35561. }
  35562. };
  35563. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  35564. }, 0);
  35565. };
  35566. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  35567. if (triangleCount - deletedTriangles <= targetCount)
  35568. loop.breakLoop();
  35569. else {
  35570. iterationFunction(loop.index, function () {
  35571. loop.executeNext();
  35572. });
  35573. }
  35574. }, function () {
  35575. setTimeout(function () {
  35576. //reconstruct this part of the mesh
  35577. _this.reconstructMesh(submeshIndex);
  35578. successCallback();
  35579. }, 0);
  35580. });
  35581. };
  35582. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  35583. var _this = this;
  35584. this.vertices = [];
  35585. this.triangles = [];
  35586. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35587. var indices = this._mesh.getIndices();
  35588. var submesh = this._mesh.subMeshes[submeshIndex];
  35589. var findInVertices = function (positionToSearch) {
  35590. if (optimizeMesh) {
  35591. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  35592. if (_this.vertices[ii].position.equals(positionToSearch)) {
  35593. return _this.vertices[ii];
  35594. }
  35595. }
  35596. }
  35597. return null;
  35598. };
  35599. var vertexReferences = [];
  35600. var vertexInit = function (i) {
  35601. var offset = i + submesh.verticesStart;
  35602. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  35603. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  35604. vertex.originalOffsets.push(offset);
  35605. if (vertex.id === _this.vertices.length) {
  35606. _this.vertices.push(vertex);
  35607. }
  35608. vertexReferences.push(vertex.id);
  35609. };
  35610. //var totalVertices = mesh.getTotalVertices();
  35611. var totalVertices = submesh.verticesCount;
  35612. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  35613. var indicesInit = function (i) {
  35614. var offset = (submesh.indexStart / 3) + i;
  35615. var pos = (offset * 3);
  35616. var i0 = indices[pos + 0];
  35617. var i1 = indices[pos + 1];
  35618. var i2 = indices[pos + 2];
  35619. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  35620. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  35621. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  35622. var triangle = new DecimationTriangle([v0, v1, v2]);
  35623. triangle.originalOffset = pos;
  35624. _this.triangles.push(triangle);
  35625. };
  35626. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  35627. _this.init(callback);
  35628. });
  35629. });
  35630. };
  35631. QuadraticErrorSimplification.prototype.init = function (callback) {
  35632. var _this = this;
  35633. var triangleInit1 = function (i) {
  35634. var t = _this.triangles[i];
  35635. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  35636. for (var j = 0; j < 3; j++) {
  35637. 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))));
  35638. }
  35639. };
  35640. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  35641. var triangleInit2 = function (i) {
  35642. var t = _this.triangles[i];
  35643. for (var j = 0; j < 3; ++j) {
  35644. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  35645. }
  35646. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35647. };
  35648. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  35649. _this.initialized = true;
  35650. callback();
  35651. });
  35652. });
  35653. };
  35654. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  35655. var newTriangles = [];
  35656. var i;
  35657. for (i = 0; i < this.vertices.length; ++i) {
  35658. this.vertices[i].triangleCount = 0;
  35659. }
  35660. var t;
  35661. var j;
  35662. for (i = 0; i < this.triangles.length; ++i) {
  35663. if (!this.triangles[i].deleted) {
  35664. t = this.triangles[i];
  35665. for (j = 0; j < 3; ++j) {
  35666. t.vertices[j].triangleCount = 1;
  35667. }
  35668. newTriangles.push(t);
  35669. }
  35670. }
  35671. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  35672. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  35673. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  35674. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  35675. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35676. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35677. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35678. var vertexCount = 0;
  35679. for (i = 0; i < this.vertices.length; ++i) {
  35680. var vertex = this.vertices[i];
  35681. vertex.id = vertexCount;
  35682. if (vertex.triangleCount) {
  35683. vertex.originalOffsets.forEach(function (originalOffset) {
  35684. newPositionData.push(vertex.position.x);
  35685. newPositionData.push(vertex.position.y);
  35686. newPositionData.push(vertex.position.z);
  35687. newNormalData.push(normalData[originalOffset * 3]);
  35688. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  35689. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  35690. if (uvs && uvs.length) {
  35691. newUVsData.push(uvs[(originalOffset * 2)]);
  35692. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  35693. }
  35694. else if (colorsData && colorsData.length) {
  35695. newColorsData.push(colorsData[(originalOffset * 4)]);
  35696. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  35697. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  35698. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  35699. }
  35700. ++vertexCount;
  35701. });
  35702. }
  35703. }
  35704. var startingIndex = this._reconstructedMesh.getTotalIndices();
  35705. var startingVertex = this._reconstructedMesh.getTotalVertices();
  35706. var submeshesArray = this._reconstructedMesh.subMeshes;
  35707. this._reconstructedMesh.subMeshes = [];
  35708. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  35709. var originalIndices = this._mesh.getIndices();
  35710. for (i = 0; i < newTriangles.length; ++i) {
  35711. t = newTriangles[i]; //now get the new referencing point for each vertex
  35712. [0, 1, 2].forEach(function (idx) {
  35713. var id = originalIndices[t.originalOffset + idx];
  35714. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  35715. if (offset < 0)
  35716. offset = 0;
  35717. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  35718. });
  35719. }
  35720. //overwriting the old vertex buffers and indices.
  35721. this._reconstructedMesh.setIndices(newIndicesArray);
  35722. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  35723. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  35724. if (newUVsData.length > 0)
  35725. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  35726. if (newColorsData.length > 0)
  35727. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  35728. //create submesh
  35729. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  35730. if (submeshIndex > 0) {
  35731. this._reconstructedMesh.subMeshes = [];
  35732. submeshesArray.forEach(function (submesh) {
  35733. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  35734. });
  35735. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  35736. }
  35737. };
  35738. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  35739. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  35740. this._reconstructedMesh.material = this._mesh.material;
  35741. this._reconstructedMesh.parent = this._mesh.parent;
  35742. this._reconstructedMesh.isVisible = false;
  35743. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  35744. };
  35745. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  35746. for (var i = 0; i < vertex1.triangleCount; ++i) {
  35747. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  35748. if (t.deleted)
  35749. continue;
  35750. var s = this.references[vertex1.triangleStart + i].vertexId;
  35751. var v1 = t.vertices[(s + 1) % 3];
  35752. var v2 = t.vertices[(s + 2) % 3];
  35753. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  35754. deletedArray[i] = true;
  35755. delTr.push(t);
  35756. continue;
  35757. }
  35758. var d1 = v1.position.subtract(point);
  35759. d1 = d1.normalize();
  35760. var d2 = v2.position.subtract(point);
  35761. d2 = d2.normalize();
  35762. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  35763. return true;
  35764. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  35765. deletedArray[i] = false;
  35766. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  35767. return true;
  35768. }
  35769. return false;
  35770. };
  35771. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  35772. var newDeleted = deletedTriangles;
  35773. for (var i = 0; i < vertex.triangleCount; ++i) {
  35774. var ref = this.references[vertex.triangleStart + i];
  35775. var t = this.triangles[ref.triangleId];
  35776. if (t.deleted)
  35777. continue;
  35778. if (deletedArray[i] && t.deletePending) {
  35779. t.deleted = true;
  35780. newDeleted++;
  35781. continue;
  35782. }
  35783. t.vertices[ref.vertexId] = origVertex;
  35784. t.isDirty = true;
  35785. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  35786. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  35787. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  35788. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35789. this.references.push(ref);
  35790. }
  35791. return newDeleted;
  35792. };
  35793. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  35794. for (var i = 0; i < this.vertices.length; ++i) {
  35795. var vCount = [];
  35796. var vId = [];
  35797. var v = this.vertices[i];
  35798. var j;
  35799. for (j = 0; j < v.triangleCount; ++j) {
  35800. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  35801. for (var ii = 0; ii < 3; ii++) {
  35802. var ofs = 0;
  35803. var vv = triangle.vertices[ii];
  35804. while (ofs < vCount.length) {
  35805. if (vId[ofs] === vv.id)
  35806. break;
  35807. ++ofs;
  35808. }
  35809. if (ofs === vCount.length) {
  35810. vCount.push(1);
  35811. vId.push(vv.id);
  35812. }
  35813. else {
  35814. vCount[ofs]++;
  35815. }
  35816. }
  35817. }
  35818. for (j = 0; j < vCount.length; ++j) {
  35819. if (vCount[j] === 1) {
  35820. this.vertices[vId[j]].isBorder = true;
  35821. }
  35822. else {
  35823. this.vertices[vId[j]].isBorder = false;
  35824. }
  35825. }
  35826. }
  35827. };
  35828. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  35829. if (identifyBorders === void 0) { identifyBorders = false; }
  35830. var i;
  35831. if (!identifyBorders) {
  35832. var newTrianglesVector = [];
  35833. for (i = 0; i < this.triangles.length; ++i) {
  35834. if (!this.triangles[i].deleted) {
  35835. newTrianglesVector.push(this.triangles[i]);
  35836. }
  35837. }
  35838. this.triangles = newTrianglesVector;
  35839. }
  35840. for (i = 0; i < this.vertices.length; ++i) {
  35841. this.vertices[i].triangleCount = 0;
  35842. this.vertices[i].triangleStart = 0;
  35843. }
  35844. var t;
  35845. var j;
  35846. var v;
  35847. for (i = 0; i < this.triangles.length; ++i) {
  35848. t = this.triangles[i];
  35849. for (j = 0; j < 3; ++j) {
  35850. v = t.vertices[j];
  35851. v.triangleCount++;
  35852. }
  35853. }
  35854. var tStart = 0;
  35855. for (i = 0; i < this.vertices.length; ++i) {
  35856. this.vertices[i].triangleStart = tStart;
  35857. tStart += this.vertices[i].triangleCount;
  35858. this.vertices[i].triangleCount = 0;
  35859. }
  35860. var newReferences = new Array(this.triangles.length * 3);
  35861. for (i = 0; i < this.triangles.length; ++i) {
  35862. t = this.triangles[i];
  35863. for (j = 0; j < 3; ++j) {
  35864. v = t.vertices[j];
  35865. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  35866. v.triangleCount++;
  35867. }
  35868. }
  35869. this.references = newReferences;
  35870. if (identifyBorders) {
  35871. this.identifyBorder();
  35872. }
  35873. };
  35874. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  35875. var x = point.x;
  35876. var y = point.y;
  35877. var z = point.z;
  35878. 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
  35879. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  35880. };
  35881. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  35882. var q = vertex1.q.add(vertex2.q);
  35883. var border = vertex1.isBorder && vertex2.isBorder;
  35884. var error = 0;
  35885. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  35886. if (qDet !== 0 && !border) {
  35887. if (!pointResult) {
  35888. pointResult = BABYLON.Vector3.Zero();
  35889. }
  35890. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  35891. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  35892. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  35893. error = this.vertexError(q, pointResult);
  35894. }
  35895. else {
  35896. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  35897. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  35898. var error1 = this.vertexError(q, vertex1.position);
  35899. var error2 = this.vertexError(q, vertex2.position);
  35900. var error3 = this.vertexError(q, p3);
  35901. error = Math.min(error1, error2, error3);
  35902. if (error === error1) {
  35903. if (pointResult) {
  35904. pointResult.copyFrom(vertex1.position);
  35905. }
  35906. }
  35907. else if (error === error2) {
  35908. if (pointResult) {
  35909. pointResult.copyFrom(vertex2.position);
  35910. }
  35911. }
  35912. else {
  35913. if (pointResult) {
  35914. pointResult.copyFrom(p3);
  35915. }
  35916. }
  35917. }
  35918. return error;
  35919. };
  35920. return QuadraticErrorSimplification;
  35921. })();
  35922. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  35923. })(BABYLON || (BABYLON = {}));
  35924. var BABYLON;
  35925. (function (BABYLON) {
  35926. var serializedGeometries = [];
  35927. var serializeGeometry = function (geometry, serializationGeometries) {
  35928. if (serializedGeometries[geometry.id]) {
  35929. return;
  35930. }
  35931. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  35932. serializationGeometries.boxes.push(geometry.serialize());
  35933. }
  35934. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  35935. serializationGeometries.spheres.push(geometry.serialize());
  35936. }
  35937. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  35938. serializationGeometries.cylinders.push(geometry.serialize());
  35939. }
  35940. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  35941. serializationGeometries.toruses.push(geometry.serialize());
  35942. }
  35943. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  35944. serializationGeometries.grounds.push(geometry.serialize());
  35945. }
  35946. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  35947. serializationGeometries.planes.push(geometry.serialize());
  35948. }
  35949. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  35950. serializationGeometries.torusKnots.push(geometry.serialize());
  35951. }
  35952. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  35953. throw new Error("Unknown primitive type");
  35954. }
  35955. else {
  35956. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  35957. }
  35958. serializedGeometries[geometry.id] = true;
  35959. };
  35960. var serializeMesh = function (mesh, serializationScene) {
  35961. var serializationObject = {};
  35962. serializationObject.name = mesh.name;
  35963. serializationObject.id = mesh.id;
  35964. if (BABYLON.Tags.HasTags(mesh)) {
  35965. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  35966. }
  35967. serializationObject.position = mesh.position.asArray();
  35968. if (mesh.rotationQuaternion) {
  35969. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  35970. }
  35971. else if (mesh.rotation) {
  35972. serializationObject.rotation = mesh.rotation.asArray();
  35973. }
  35974. serializationObject.scaling = mesh.scaling.asArray();
  35975. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  35976. serializationObject.isEnabled = mesh.isEnabled();
  35977. serializationObject.isVisible = mesh.isVisible;
  35978. serializationObject.infiniteDistance = mesh.infiniteDistance;
  35979. serializationObject.pickable = mesh.isPickable;
  35980. serializationObject.receiveShadows = mesh.receiveShadows;
  35981. serializationObject.billboardMode = mesh.billboardMode;
  35982. serializationObject.visibility = mesh.visibility;
  35983. serializationObject.checkCollisions = mesh.checkCollisions;
  35984. // Parent
  35985. if (mesh.parent) {
  35986. serializationObject.parentId = mesh.parent.id;
  35987. }
  35988. // Geometry
  35989. var geometry = mesh._geometry;
  35990. if (geometry) {
  35991. var geometryId = geometry.id;
  35992. serializationObject.geometryId = geometryId;
  35993. if (!mesh.getScene().getGeometryByID(geometryId)) {
  35994. // 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
  35995. serializeGeometry(geometry, serializationScene.geometries);
  35996. }
  35997. // SubMeshes
  35998. serializationObject.subMeshes = [];
  35999. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36000. var subMesh = mesh.subMeshes[subIndex];
  36001. serializationObject.subMeshes.push({
  36002. materialIndex: subMesh.materialIndex,
  36003. verticesStart: subMesh.verticesStart,
  36004. verticesCount: subMesh.verticesCount,
  36005. indexStart: subMesh.indexStart,
  36006. indexCount: subMesh.indexCount
  36007. });
  36008. }
  36009. }
  36010. // Material
  36011. if (mesh.material) {
  36012. serializationObject.materialId = mesh.material.id;
  36013. }
  36014. else {
  36015. mesh.material = null;
  36016. }
  36017. // Skeleton
  36018. if (mesh.skeleton) {
  36019. serializationObject.skeletonId = mesh.skeleton.id;
  36020. }
  36021. // Physics
  36022. //TODO implement correct serialization for physics impostors.
  36023. if (mesh.getPhysicsImpostor()) {
  36024. serializationObject.physicsMass = mesh.getPhysicsMass();
  36025. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  36026. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  36027. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  36028. }
  36029. // Instances
  36030. serializationObject.instances = [];
  36031. for (var index = 0; index < mesh.instances.length; index++) {
  36032. var instance = mesh.instances[index];
  36033. var serializationInstance = {
  36034. name: instance.name,
  36035. position: instance.position.asArray(),
  36036. scaling: instance.scaling.asArray()
  36037. };
  36038. if (instance.rotationQuaternion) {
  36039. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  36040. }
  36041. else if (instance.rotation) {
  36042. serializationInstance.rotation = instance.rotation.asArray();
  36043. }
  36044. serializationObject.instances.push(serializationInstance);
  36045. // Animations
  36046. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  36047. serializationInstance.ranges = instance.serializeAnimationRanges();
  36048. }
  36049. // Animations
  36050. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  36051. serializationObject.ranges = mesh.serializeAnimationRanges();
  36052. // Layer mask
  36053. serializationObject.layerMask = mesh.layerMask;
  36054. return serializationObject;
  36055. };
  36056. var finalizeSingleMesh = function (mesh, serializationObject) {
  36057. //only works if the mesh is already loaded
  36058. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  36059. //serialize material
  36060. if (mesh.material) {
  36061. if (mesh.material instanceof BABYLON.StandardMaterial) {
  36062. serializationObject.materials = serializationObject.materials || [];
  36063. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  36064. serializationObject.materials.push(mesh.material.serialize());
  36065. }
  36066. }
  36067. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  36068. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  36069. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  36070. serializationObject.multiMaterials.push(mesh.material.serialize());
  36071. }
  36072. }
  36073. }
  36074. //serialize geometry
  36075. var geometry = mesh._geometry;
  36076. if (geometry) {
  36077. if (!serializationObject.geometries) {
  36078. serializationObject.geometries = {};
  36079. serializationObject.geometries.boxes = [];
  36080. serializationObject.geometries.spheres = [];
  36081. serializationObject.geometries.cylinders = [];
  36082. serializationObject.geometries.toruses = [];
  36083. serializationObject.geometries.grounds = [];
  36084. serializationObject.geometries.planes = [];
  36085. serializationObject.geometries.torusKnots = [];
  36086. serializationObject.geometries.vertexData = [];
  36087. }
  36088. serializeGeometry(geometry, serializationObject.geometries);
  36089. }
  36090. // Skeletons
  36091. if (mesh.skeleton) {
  36092. serializationObject.skeletons = serializationObject.skeletons || [];
  36093. serializationObject.skeletons.push(mesh.skeleton.serialize());
  36094. }
  36095. //serialize the actual mesh
  36096. serializationObject.meshes = serializationObject.meshes || [];
  36097. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36098. }
  36099. };
  36100. var SceneSerializer = (function () {
  36101. function SceneSerializer() {
  36102. }
  36103. SceneSerializer.ClearCache = function () {
  36104. serializedGeometries = [];
  36105. };
  36106. SceneSerializer.Serialize = function (scene) {
  36107. var serializationObject = {};
  36108. // Scene
  36109. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  36110. serializationObject.autoClear = scene.autoClear;
  36111. serializationObject.clearColor = scene.clearColor.asArray();
  36112. serializationObject.ambientColor = scene.ambientColor.asArray();
  36113. serializationObject.gravity = scene.gravity.asArray();
  36114. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  36115. serializationObject.workerCollisions = scene.workerCollisions;
  36116. // Fog
  36117. if (scene.fogMode && scene.fogMode !== 0) {
  36118. serializationObject.fogMode = scene.fogMode;
  36119. serializationObject.fogColor = scene.fogColor.asArray();
  36120. serializationObject.fogStart = scene.fogStart;
  36121. serializationObject.fogEnd = scene.fogEnd;
  36122. serializationObject.fogDensity = scene.fogDensity;
  36123. }
  36124. //Physics
  36125. if (scene.isPhysicsEnabled()) {
  36126. serializationObject.physicsEnabled = true;
  36127. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  36128. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  36129. }
  36130. // Lights
  36131. serializationObject.lights = [];
  36132. var index;
  36133. var light;
  36134. for (index = 0; index < scene.lights.length; index++) {
  36135. light = scene.lights[index];
  36136. serializationObject.lights.push(light.serialize());
  36137. }
  36138. // Cameras
  36139. serializationObject.cameras = [];
  36140. for (index = 0; index < scene.cameras.length; index++) {
  36141. var camera = scene.cameras[index];
  36142. serializationObject.cameras.push(camera.serialize());
  36143. }
  36144. if (scene.activeCamera) {
  36145. serializationObject.activeCameraID = scene.activeCamera.id;
  36146. }
  36147. // Animations
  36148. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  36149. // Materials
  36150. serializationObject.materials = [];
  36151. serializationObject.multiMaterials = [];
  36152. var material;
  36153. for (index = 0; index < scene.materials.length; index++) {
  36154. material = scene.materials[index];
  36155. serializationObject.materials.push(material.serialize());
  36156. }
  36157. // MultiMaterials
  36158. serializationObject.multiMaterials = [];
  36159. for (index = 0; index < scene.multiMaterials.length; index++) {
  36160. var multiMaterial = scene.multiMaterials[index];
  36161. serializationObject.multiMaterials.push(multiMaterial.serialize());
  36162. }
  36163. // Skeletons
  36164. serializationObject.skeletons = [];
  36165. for (index = 0; index < scene.skeletons.length; index++) {
  36166. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  36167. }
  36168. // Geometries
  36169. serializationObject.geometries = {};
  36170. serializationObject.geometries.boxes = [];
  36171. serializationObject.geometries.spheres = [];
  36172. serializationObject.geometries.cylinders = [];
  36173. serializationObject.geometries.toruses = [];
  36174. serializationObject.geometries.grounds = [];
  36175. serializationObject.geometries.planes = [];
  36176. serializationObject.geometries.torusKnots = [];
  36177. serializationObject.geometries.vertexData = [];
  36178. serializedGeometries = [];
  36179. var geometries = scene.getGeometries();
  36180. for (index = 0; index < geometries.length; index++) {
  36181. var geometry = geometries[index];
  36182. if (geometry.isReady()) {
  36183. serializeGeometry(geometry, serializationObject.geometries);
  36184. }
  36185. }
  36186. // Meshes
  36187. serializationObject.meshes = [];
  36188. for (index = 0; index < scene.meshes.length; index++) {
  36189. var abstractMesh = scene.meshes[index];
  36190. if (abstractMesh instanceof BABYLON.Mesh) {
  36191. var mesh = abstractMesh;
  36192. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  36193. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36194. }
  36195. }
  36196. }
  36197. // Particles Systems
  36198. serializationObject.particleSystems = [];
  36199. for (index = 0; index < scene.particleSystems.length; index++) {
  36200. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  36201. }
  36202. // Lens flares
  36203. serializationObject.lensFlareSystems = [];
  36204. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  36205. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  36206. }
  36207. // Shadows
  36208. serializationObject.shadowGenerators = [];
  36209. for (index = 0; index < scene.lights.length; index++) {
  36210. light = scene.lights[index];
  36211. if (light.getShadowGenerator()) {
  36212. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  36213. }
  36214. }
  36215. return serializationObject;
  36216. };
  36217. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  36218. if (withParents === void 0) { withParents = false; }
  36219. if (withChildren === void 0) { withChildren = false; }
  36220. var serializationObject = {};
  36221. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  36222. if (withParents || withChildren) {
  36223. //deliberate for loop! not for each, appended should be processed as well.
  36224. for (var i = 0; i < toSerialize.length; ++i) {
  36225. if (withChildren) {
  36226. toSerialize[i].getDescendants().forEach(function (node) {
  36227. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  36228. toSerialize.push(node);
  36229. }
  36230. });
  36231. }
  36232. //make sure the array doesn't contain the object already
  36233. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  36234. toSerialize.push(toSerialize[i].parent);
  36235. }
  36236. }
  36237. }
  36238. toSerialize.forEach(function (mesh) {
  36239. finalizeSingleMesh(mesh, serializationObject);
  36240. });
  36241. return serializationObject;
  36242. };
  36243. return SceneSerializer;
  36244. })();
  36245. BABYLON.SceneSerializer = SceneSerializer;
  36246. })(BABYLON || (BABYLON = {}));
  36247. var BABYLON;
  36248. (function (BABYLON) {
  36249. // Unique ID when we import meshes from Babylon to CSG
  36250. var currentCSGMeshId = 0;
  36251. // # class Vertex
  36252. // Represents a vertex of a polygon. Use your own vertex class instead of this
  36253. // one to provide additional features like texture coordinates and vertex
  36254. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  36255. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  36256. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  36257. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  36258. // is not used anywhere else.
  36259. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  36260. var Vertex = (function () {
  36261. function Vertex(pos, normal, uv) {
  36262. this.pos = pos;
  36263. this.normal = normal;
  36264. this.uv = uv;
  36265. }
  36266. Vertex.prototype.clone = function () {
  36267. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  36268. };
  36269. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  36270. // orientation of a polygon is flipped.
  36271. Vertex.prototype.flip = function () {
  36272. this.normal = this.normal.scale(-1);
  36273. };
  36274. // Create a new vertex between this vertex and `other` by linearly
  36275. // interpolating all properties using a parameter of `t`. Subclasses should
  36276. // override this to interpolate additional properties.
  36277. Vertex.prototype.interpolate = function (other, t) {
  36278. 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));
  36279. };
  36280. return Vertex;
  36281. })();
  36282. // # class Plane
  36283. // Represents a plane in 3D space.
  36284. var Plane = (function () {
  36285. function Plane(normal, w) {
  36286. this.normal = normal;
  36287. this.w = w;
  36288. }
  36289. Plane.FromPoints = function (a, b, c) {
  36290. var v0 = c.subtract(a);
  36291. var v1 = b.subtract(a);
  36292. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  36293. return null;
  36294. }
  36295. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  36296. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  36297. };
  36298. Plane.prototype.clone = function () {
  36299. return new Plane(this.normal.clone(), this.w);
  36300. };
  36301. Plane.prototype.flip = function () {
  36302. this.normal.scaleInPlace(-1);
  36303. this.w = -this.w;
  36304. };
  36305. // Split `polygon` by this plane if needed, then put the polygon or polygon
  36306. // fragments in the appropriate lists. Coplanar polygons go into either
  36307. // `coplanarFront` or `coplanarBack` depending on their orientation with
  36308. // respect to this plane. Polygons in front or in back of this plane go into
  36309. // either `front` or `back`.
  36310. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  36311. var COPLANAR = 0;
  36312. var FRONT = 1;
  36313. var BACK = 2;
  36314. var SPANNING = 3;
  36315. // Classify each point as well as the entire polygon into one of the above
  36316. // four classes.
  36317. var polygonType = 0;
  36318. var types = [];
  36319. var i;
  36320. var t;
  36321. for (i = 0; i < polygon.vertices.length; i++) {
  36322. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  36323. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  36324. polygonType |= type;
  36325. types.push(type);
  36326. }
  36327. // Put the polygon in the correct list, splitting it when necessary.
  36328. switch (polygonType) {
  36329. case COPLANAR:
  36330. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  36331. break;
  36332. case FRONT:
  36333. front.push(polygon);
  36334. break;
  36335. case BACK:
  36336. back.push(polygon);
  36337. break;
  36338. case SPANNING:
  36339. var f = [], b = [];
  36340. for (i = 0; i < polygon.vertices.length; i++) {
  36341. var j = (i + 1) % polygon.vertices.length;
  36342. var ti = types[i], tj = types[j];
  36343. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  36344. if (ti !== BACK)
  36345. f.push(vi);
  36346. if (ti !== FRONT)
  36347. b.push(ti !== BACK ? vi.clone() : vi);
  36348. if ((ti | tj) === SPANNING) {
  36349. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  36350. var v = vi.interpolate(vj, t);
  36351. f.push(v);
  36352. b.push(v.clone());
  36353. }
  36354. }
  36355. var poly;
  36356. if (f.length >= 3) {
  36357. poly = new Polygon(f, polygon.shared);
  36358. if (poly.plane)
  36359. front.push(poly);
  36360. }
  36361. if (b.length >= 3) {
  36362. poly = new Polygon(b, polygon.shared);
  36363. if (poly.plane)
  36364. back.push(poly);
  36365. }
  36366. break;
  36367. }
  36368. };
  36369. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  36370. // point is on the plane.
  36371. Plane.EPSILON = 1e-5;
  36372. return Plane;
  36373. })();
  36374. // # class Polygon
  36375. // Represents a convex polygon. The vertices used to initialize a polygon must
  36376. // be coplanar and form a convex loop.
  36377. //
  36378. // Each convex polygon has a `shared` property, which is shared between all
  36379. // polygons that are clones of each other or were split from the same polygon.
  36380. // This can be used to define per-polygon properties (such as surface color).
  36381. var Polygon = (function () {
  36382. function Polygon(vertices, shared) {
  36383. this.vertices = vertices;
  36384. this.shared = shared;
  36385. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  36386. }
  36387. Polygon.prototype.clone = function () {
  36388. var vertices = this.vertices.map(function (v) { return v.clone(); });
  36389. return new Polygon(vertices, this.shared);
  36390. };
  36391. Polygon.prototype.flip = function () {
  36392. this.vertices.reverse().map(function (v) { v.flip(); });
  36393. this.plane.flip();
  36394. };
  36395. return Polygon;
  36396. })();
  36397. // # class Node
  36398. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  36399. // by picking a polygon to split along. That polygon (and all other coplanar
  36400. // polygons) are added directly to that node and the other polygons are added to
  36401. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  36402. // no distinction between internal and leaf nodes.
  36403. var Node = (function () {
  36404. function Node(polygons) {
  36405. this.plane = null;
  36406. this.front = null;
  36407. this.back = null;
  36408. this.polygons = [];
  36409. if (polygons) {
  36410. this.build(polygons);
  36411. }
  36412. }
  36413. Node.prototype.clone = function () {
  36414. var node = new Node();
  36415. node.plane = this.plane && this.plane.clone();
  36416. node.front = this.front && this.front.clone();
  36417. node.back = this.back && this.back.clone();
  36418. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  36419. return node;
  36420. };
  36421. // Convert solid space to empty space and empty space to solid space.
  36422. Node.prototype.invert = function () {
  36423. for (var i = 0; i < this.polygons.length; i++) {
  36424. this.polygons[i].flip();
  36425. }
  36426. if (this.plane) {
  36427. this.plane.flip();
  36428. }
  36429. if (this.front) {
  36430. this.front.invert();
  36431. }
  36432. if (this.back) {
  36433. this.back.invert();
  36434. }
  36435. var temp = this.front;
  36436. this.front = this.back;
  36437. this.back = temp;
  36438. };
  36439. // Recursively remove all polygons in `polygons` that are inside this BSP
  36440. // tree.
  36441. Node.prototype.clipPolygons = function (polygons) {
  36442. if (!this.plane)
  36443. return polygons.slice();
  36444. var front = [], back = [];
  36445. for (var i = 0; i < polygons.length; i++) {
  36446. this.plane.splitPolygon(polygons[i], front, back, front, back);
  36447. }
  36448. if (this.front) {
  36449. front = this.front.clipPolygons(front);
  36450. }
  36451. if (this.back) {
  36452. back = this.back.clipPolygons(back);
  36453. }
  36454. else {
  36455. back = [];
  36456. }
  36457. return front.concat(back);
  36458. };
  36459. // Remove all polygons in this BSP tree that are inside the other BSP tree
  36460. // `bsp`.
  36461. Node.prototype.clipTo = function (bsp) {
  36462. this.polygons = bsp.clipPolygons(this.polygons);
  36463. if (this.front)
  36464. this.front.clipTo(bsp);
  36465. if (this.back)
  36466. this.back.clipTo(bsp);
  36467. };
  36468. // Return a list of all polygons in this BSP tree.
  36469. Node.prototype.allPolygons = function () {
  36470. var polygons = this.polygons.slice();
  36471. if (this.front)
  36472. polygons = polygons.concat(this.front.allPolygons());
  36473. if (this.back)
  36474. polygons = polygons.concat(this.back.allPolygons());
  36475. return polygons;
  36476. };
  36477. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  36478. // new polygons are filtered down to the bottom of the tree and become new
  36479. // nodes there. Each set of polygons is partitioned using the first polygon
  36480. // (no heuristic is used to pick a good split).
  36481. Node.prototype.build = function (polygons) {
  36482. if (!polygons.length)
  36483. return;
  36484. if (!this.plane)
  36485. this.plane = polygons[0].plane.clone();
  36486. var front = [], back = [];
  36487. for (var i = 0; i < polygons.length; i++) {
  36488. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  36489. }
  36490. if (front.length) {
  36491. if (!this.front)
  36492. this.front = new Node();
  36493. this.front.build(front);
  36494. }
  36495. if (back.length) {
  36496. if (!this.back)
  36497. this.back = new Node();
  36498. this.back.build(back);
  36499. }
  36500. };
  36501. return Node;
  36502. })();
  36503. var CSG = (function () {
  36504. function CSG() {
  36505. this.polygons = new Array();
  36506. }
  36507. // Convert BABYLON.Mesh to BABYLON.CSG
  36508. CSG.FromMesh = function (mesh) {
  36509. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  36510. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  36511. if (mesh instanceof BABYLON.Mesh) {
  36512. mesh.computeWorldMatrix(true);
  36513. matrix = mesh.getWorldMatrix();
  36514. meshPosition = mesh.position.clone();
  36515. meshRotation = mesh.rotation.clone();
  36516. if (mesh.rotationQuaternion) {
  36517. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  36518. }
  36519. meshScaling = mesh.scaling.clone();
  36520. }
  36521. else {
  36522. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  36523. }
  36524. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36525. var subMeshes = mesh.subMeshes;
  36526. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  36527. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  36528. vertices = [];
  36529. for (var j = 0; j < 3; j++) {
  36530. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  36531. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  36532. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  36533. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  36534. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  36535. vertex = new Vertex(position, normal, uv);
  36536. vertices.push(vertex);
  36537. }
  36538. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  36539. // To handle the case of degenerated triangle
  36540. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  36541. if (polygon.plane)
  36542. polygons.push(polygon);
  36543. }
  36544. }
  36545. var csg = CSG.FromPolygons(polygons);
  36546. csg.matrix = matrix;
  36547. csg.position = meshPosition;
  36548. csg.rotation = meshRotation;
  36549. csg.scaling = meshScaling;
  36550. csg.rotationQuaternion = meshRotationQuaternion;
  36551. currentCSGMeshId++;
  36552. return csg;
  36553. };
  36554. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  36555. CSG.FromPolygons = function (polygons) {
  36556. var csg = new CSG();
  36557. csg.polygons = polygons;
  36558. return csg;
  36559. };
  36560. CSG.prototype.clone = function () {
  36561. var csg = new CSG();
  36562. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  36563. csg.copyTransformAttributes(this);
  36564. return csg;
  36565. };
  36566. CSG.prototype.toPolygons = function () {
  36567. return this.polygons;
  36568. };
  36569. CSG.prototype.union = function (csg) {
  36570. var a = new Node(this.clone().polygons);
  36571. var b = new Node(csg.clone().polygons);
  36572. a.clipTo(b);
  36573. b.clipTo(a);
  36574. b.invert();
  36575. b.clipTo(a);
  36576. b.invert();
  36577. a.build(b.allPolygons());
  36578. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36579. };
  36580. CSG.prototype.unionInPlace = function (csg) {
  36581. var a = new Node(this.polygons);
  36582. var b = new Node(csg.polygons);
  36583. a.clipTo(b);
  36584. b.clipTo(a);
  36585. b.invert();
  36586. b.clipTo(a);
  36587. b.invert();
  36588. a.build(b.allPolygons());
  36589. this.polygons = a.allPolygons();
  36590. };
  36591. CSG.prototype.subtract = function (csg) {
  36592. var a = new Node(this.clone().polygons);
  36593. var b = new Node(csg.clone().polygons);
  36594. a.invert();
  36595. a.clipTo(b);
  36596. b.clipTo(a);
  36597. b.invert();
  36598. b.clipTo(a);
  36599. b.invert();
  36600. a.build(b.allPolygons());
  36601. a.invert();
  36602. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36603. };
  36604. CSG.prototype.subtractInPlace = function (csg) {
  36605. var a = new Node(this.polygons);
  36606. var b = new Node(csg.polygons);
  36607. a.invert();
  36608. a.clipTo(b);
  36609. b.clipTo(a);
  36610. b.invert();
  36611. b.clipTo(a);
  36612. b.invert();
  36613. a.build(b.allPolygons());
  36614. a.invert();
  36615. this.polygons = a.allPolygons();
  36616. };
  36617. CSG.prototype.intersect = function (csg) {
  36618. var a = new Node(this.clone().polygons);
  36619. var b = new Node(csg.clone().polygons);
  36620. a.invert();
  36621. b.clipTo(a);
  36622. b.invert();
  36623. a.clipTo(b);
  36624. b.clipTo(a);
  36625. a.build(b.allPolygons());
  36626. a.invert();
  36627. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36628. };
  36629. CSG.prototype.intersectInPlace = function (csg) {
  36630. var a = new Node(this.polygons);
  36631. var b = new Node(csg.polygons);
  36632. a.invert();
  36633. b.clipTo(a);
  36634. b.invert();
  36635. a.clipTo(b);
  36636. b.clipTo(a);
  36637. a.build(b.allPolygons());
  36638. a.invert();
  36639. this.polygons = a.allPolygons();
  36640. };
  36641. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  36642. // not modified.
  36643. CSG.prototype.inverse = function () {
  36644. var csg = this.clone();
  36645. csg.inverseInPlace();
  36646. return csg;
  36647. };
  36648. CSG.prototype.inverseInPlace = function () {
  36649. this.polygons.map(function (p) { p.flip(); });
  36650. };
  36651. // This is used to keep meshes transformations so they can be restored
  36652. // when we build back a Babylon Mesh
  36653. // NB : All CSG operations are performed in world coordinates
  36654. CSG.prototype.copyTransformAttributes = function (csg) {
  36655. this.matrix = csg.matrix;
  36656. this.position = csg.position;
  36657. this.rotation = csg.rotation;
  36658. this.scaling = csg.scaling;
  36659. this.rotationQuaternion = csg.rotationQuaternion;
  36660. return this;
  36661. };
  36662. // Build Raw mesh from CSG
  36663. // Coordinates here are in world space
  36664. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  36665. var matrix = this.matrix.clone();
  36666. matrix.invert();
  36667. 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;
  36668. if (keepSubMeshes) {
  36669. // Sort Polygons, since subMeshes are indices range
  36670. polygons.sort(function (a, b) {
  36671. if (a.shared.meshId === b.shared.meshId) {
  36672. return a.shared.subMeshId - b.shared.subMeshId;
  36673. }
  36674. else {
  36675. return a.shared.meshId - b.shared.meshId;
  36676. }
  36677. });
  36678. }
  36679. for (var i = 0, il = polygons.length; i < il; i++) {
  36680. polygon = polygons[i];
  36681. // Building SubMeshes
  36682. if (!subMesh_dict[polygon.shared.meshId]) {
  36683. subMesh_dict[polygon.shared.meshId] = {};
  36684. }
  36685. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  36686. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  36687. indexStart: +Infinity,
  36688. indexEnd: -Infinity,
  36689. materialIndex: polygon.shared.materialIndex
  36690. };
  36691. }
  36692. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  36693. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  36694. polygonIndices[0] = 0;
  36695. polygonIndices[1] = j - 1;
  36696. polygonIndices[2] = j;
  36697. for (var k = 0; k < 3; k++) {
  36698. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  36699. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  36700. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  36701. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  36702. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  36703. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  36704. // Check if 2 points can be merged
  36705. if (!(typeof vertex_idx !== 'undefined' &&
  36706. normals[vertex_idx * 3] === localNormal.x &&
  36707. normals[vertex_idx * 3 + 1] === localNormal.y &&
  36708. normals[vertex_idx * 3 + 2] === localNormal.z &&
  36709. uvs[vertex_idx * 2] === uv.x &&
  36710. uvs[vertex_idx * 2 + 1] === uv.y)) {
  36711. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  36712. uvs.push(uv.x, uv.y);
  36713. normals.push(normal.x, normal.y, normal.z);
  36714. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  36715. }
  36716. indices.push(vertex_idx);
  36717. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  36718. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  36719. currentIndex++;
  36720. }
  36721. }
  36722. }
  36723. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  36724. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  36725. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  36726. mesh.setIndices(indices);
  36727. if (keepSubMeshes) {
  36728. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  36729. var materialIndexOffset = 0, materialMaxIndex;
  36730. mesh.subMeshes = new Array();
  36731. for (var m in subMesh_dict) {
  36732. materialMaxIndex = -1;
  36733. for (var sm in subMesh_dict[m]) {
  36734. subMesh_obj = subMesh_dict[m][sm];
  36735. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  36736. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  36737. }
  36738. materialIndexOffset += ++materialMaxIndex;
  36739. }
  36740. }
  36741. return mesh;
  36742. };
  36743. // Build Mesh from CSG taking material and transforms into account
  36744. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  36745. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  36746. mesh.material = material;
  36747. mesh.position.copyFrom(this.position);
  36748. mesh.rotation.copyFrom(this.rotation);
  36749. if (this.rotationQuaternion) {
  36750. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  36751. }
  36752. mesh.scaling.copyFrom(this.scaling);
  36753. mesh.computeWorldMatrix(true);
  36754. return mesh;
  36755. };
  36756. return CSG;
  36757. })();
  36758. BABYLON.CSG = CSG;
  36759. })(BABYLON || (BABYLON = {}));
  36760. var BABYLON;
  36761. (function (BABYLON) {
  36762. var VRDistortionCorrectionPostProcess = (function (_super) {
  36763. __extends(VRDistortionCorrectionPostProcess, _super);
  36764. //ANY
  36765. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  36766. var _this = this;
  36767. _super.call(this, name, "vrDistortionCorrection", [
  36768. 'LensCenter',
  36769. 'Scale',
  36770. 'ScaleIn',
  36771. 'HmdWarpParam'
  36772. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  36773. this._isRightEye = isRightEye;
  36774. this._distortionFactors = vrMetrics.distortionK;
  36775. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  36776. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  36777. this.onSizeChanged = function () {
  36778. _this.aspectRatio = _this.width * .5 / _this.height;
  36779. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  36780. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  36781. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  36782. };
  36783. this.onApply = function (effect) {
  36784. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  36785. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  36786. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  36787. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  36788. };
  36789. }
  36790. return VRDistortionCorrectionPostProcess;
  36791. })(BABYLON.PostProcess);
  36792. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  36793. })(BABYLON || (BABYLON = {}));
  36794. // Mainly based on these 2 articles :
  36795. // 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
  36796. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  36797. var BABYLON;
  36798. (function (BABYLON) {
  36799. (function (JoystickAxis) {
  36800. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  36801. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  36802. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  36803. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  36804. var JoystickAxis = BABYLON.JoystickAxis;
  36805. var VirtualJoystick = (function () {
  36806. function VirtualJoystick(leftJoystick) {
  36807. var _this = this;
  36808. if (leftJoystick) {
  36809. this._leftJoystick = true;
  36810. }
  36811. else {
  36812. this._leftJoystick = false;
  36813. }
  36814. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  36815. VirtualJoystick._globalJoystickIndex++;
  36816. // By default left & right arrow keys are moving the X
  36817. // and up & down keys are moving the Y
  36818. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  36819. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  36820. this.reverseLeftRight = false;
  36821. this.reverseUpDown = false;
  36822. // collections of pointers
  36823. this._touches = new BABYLON.SmartCollection();
  36824. this.deltaPosition = BABYLON.Vector3.Zero();
  36825. this._joystickSensibility = 25;
  36826. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36827. this._rotationSpeed = 25;
  36828. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  36829. this._rotateOnAxisRelativeToMesh = false;
  36830. this._onResize = function (evt) {
  36831. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36832. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36833. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  36834. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  36835. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  36836. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  36837. };
  36838. // injecting a canvas element on top of the canvas 3D game
  36839. if (!VirtualJoystick.vjCanvas) {
  36840. window.addEventListener("resize", this._onResize, false);
  36841. VirtualJoystick.vjCanvas = document.createElement("canvas");
  36842. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36843. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36844. VirtualJoystick.vjCanvas.width = window.innerWidth;
  36845. VirtualJoystick.vjCanvas.height = window.innerHeight;
  36846. VirtualJoystick.vjCanvas.style.width = "100%";
  36847. VirtualJoystick.vjCanvas.style.height = "100%";
  36848. VirtualJoystick.vjCanvas.style.position = "absolute";
  36849. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  36850. VirtualJoystick.vjCanvas.style.top = "0px";
  36851. VirtualJoystick.vjCanvas.style.left = "0px";
  36852. VirtualJoystick.vjCanvas.style.zIndex = "5";
  36853. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  36854. // Support for jQuery PEP polyfill
  36855. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  36856. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  36857. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  36858. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  36859. document.body.appendChild(VirtualJoystick.vjCanvas);
  36860. }
  36861. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  36862. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  36863. this.pressed = false;
  36864. // default joystick color
  36865. this._joystickColor = "cyan";
  36866. this._joystickPointerID = -1;
  36867. // current joystick position
  36868. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  36869. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  36870. // origin joystick position
  36871. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  36872. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  36873. this._onPointerDownHandlerRef = function (evt) {
  36874. _this._onPointerDown(evt);
  36875. };
  36876. this._onPointerMoveHandlerRef = function (evt) {
  36877. _this._onPointerMove(evt);
  36878. };
  36879. this._onPointerOutHandlerRef = function (evt) {
  36880. _this._onPointerUp(evt);
  36881. };
  36882. this._onPointerUpHandlerRef = function (evt) {
  36883. _this._onPointerUp(evt);
  36884. };
  36885. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  36886. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  36887. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  36888. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  36889. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  36890. evt.preventDefault(); // Disables system menu
  36891. }, false);
  36892. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  36893. }
  36894. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  36895. this._joystickSensibility = newJoystickSensibility;
  36896. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36897. };
  36898. VirtualJoystick.prototype._onPointerDown = function (e) {
  36899. var positionOnScreenCondition;
  36900. e.preventDefault();
  36901. if (this._leftJoystick === true) {
  36902. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  36903. }
  36904. else {
  36905. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  36906. }
  36907. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  36908. // First contact will be dedicated to the virtual joystick
  36909. this._joystickPointerID = e.pointerId;
  36910. this._joystickPointerStartPos.x = e.clientX;
  36911. this._joystickPointerStartPos.y = e.clientY;
  36912. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  36913. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  36914. this._deltaJoystickVector.x = 0;
  36915. this._deltaJoystickVector.y = 0;
  36916. this.pressed = true;
  36917. this._touches.add(e.pointerId.toString(), e);
  36918. }
  36919. else {
  36920. // You can only trigger the action buttons with a joystick declared
  36921. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  36922. this._action();
  36923. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  36924. }
  36925. }
  36926. };
  36927. VirtualJoystick.prototype._onPointerMove = function (e) {
  36928. // If the current pointer is the one associated to the joystick (first touch contact)
  36929. if (this._joystickPointerID == e.pointerId) {
  36930. this._joystickPointerPos.x = e.clientX;
  36931. this._joystickPointerPos.y = e.clientY;
  36932. this._deltaJoystickVector = this._joystickPointerPos.clone();
  36933. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  36934. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  36935. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  36936. switch (this._axisTargetedByLeftAndRight) {
  36937. case JoystickAxis.X:
  36938. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  36939. break;
  36940. case JoystickAxis.Y:
  36941. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  36942. break;
  36943. case JoystickAxis.Z:
  36944. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  36945. break;
  36946. }
  36947. var directionUpDown = this.reverseUpDown ? 1 : -1;
  36948. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  36949. switch (this._axisTargetedByUpAndDown) {
  36950. case JoystickAxis.X:
  36951. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  36952. break;
  36953. case JoystickAxis.Y:
  36954. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  36955. break;
  36956. case JoystickAxis.Z:
  36957. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  36958. break;
  36959. }
  36960. }
  36961. else {
  36962. if (this._touches.item(e.pointerId.toString())) {
  36963. this._touches.item(e.pointerId.toString()).x = e.clientX;
  36964. this._touches.item(e.pointerId.toString()).y = e.clientY;
  36965. }
  36966. }
  36967. };
  36968. VirtualJoystick.prototype._onPointerUp = function (e) {
  36969. if (this._joystickPointerID == e.pointerId) {
  36970. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  36971. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  36972. this._joystickPointerID = -1;
  36973. this.pressed = false;
  36974. }
  36975. else {
  36976. var touch = this._touches.item(e.pointerId.toString());
  36977. if (touch) {
  36978. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  36979. }
  36980. }
  36981. this._deltaJoystickVector.x = 0;
  36982. this._deltaJoystickVector.y = 0;
  36983. this._touches.remove(e.pointerId.toString());
  36984. };
  36985. /**
  36986. * Change the color of the virtual joystick
  36987. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  36988. */
  36989. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  36990. this._joystickColor = newColor;
  36991. };
  36992. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  36993. this._action = action;
  36994. };
  36995. // Define which axis you'd like to control for left & right
  36996. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  36997. switch (axis) {
  36998. case JoystickAxis.X:
  36999. case JoystickAxis.Y:
  37000. case JoystickAxis.Z:
  37001. this._axisTargetedByLeftAndRight = axis;
  37002. break;
  37003. default:
  37004. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  37005. break;
  37006. }
  37007. };
  37008. // Define which axis you'd like to control for up & down
  37009. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  37010. switch (axis) {
  37011. case JoystickAxis.X:
  37012. case JoystickAxis.Y:
  37013. case JoystickAxis.Z:
  37014. this._axisTargetedByUpAndDown = axis;
  37015. break;
  37016. default:
  37017. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  37018. break;
  37019. }
  37020. };
  37021. VirtualJoystick.prototype._clearCanvas = function () {
  37022. if (this._leftJoystick) {
  37023. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  37024. }
  37025. else {
  37026. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  37027. }
  37028. };
  37029. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  37030. var _this = this;
  37031. if (this.pressed) {
  37032. this._touches.forEach(function (touch) {
  37033. if (touch.pointerId === _this._joystickPointerID) {
  37034. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  37035. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  37036. VirtualJoystick.vjCanvasContext.beginPath();
  37037. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  37038. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37039. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  37040. VirtualJoystick.vjCanvasContext.stroke();
  37041. VirtualJoystick.vjCanvasContext.closePath();
  37042. VirtualJoystick.vjCanvasContext.beginPath();
  37043. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37044. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  37045. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  37046. VirtualJoystick.vjCanvasContext.stroke();
  37047. VirtualJoystick.vjCanvasContext.closePath();
  37048. VirtualJoystick.vjCanvasContext.beginPath();
  37049. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37050. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  37051. VirtualJoystick.vjCanvasContext.stroke();
  37052. VirtualJoystick.vjCanvasContext.closePath();
  37053. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  37054. }
  37055. else {
  37056. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  37057. VirtualJoystick.vjCanvasContext.beginPath();
  37058. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  37059. VirtualJoystick.vjCanvasContext.beginPath();
  37060. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  37061. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  37062. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  37063. VirtualJoystick.vjCanvasContext.stroke();
  37064. VirtualJoystick.vjCanvasContext.closePath();
  37065. touch.prevX = touch.x;
  37066. touch.prevY = touch.y;
  37067. }
  37068. ;
  37069. });
  37070. }
  37071. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  37072. };
  37073. VirtualJoystick.prototype.releaseCanvas = function () {
  37074. if (VirtualJoystick.vjCanvas) {
  37075. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  37076. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  37077. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  37078. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  37079. window.removeEventListener("resize", this._onResize);
  37080. document.body.removeChild(VirtualJoystick.vjCanvas);
  37081. VirtualJoystick.vjCanvas = null;
  37082. }
  37083. };
  37084. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  37085. VirtualJoystick._globalJoystickIndex = 0;
  37086. return VirtualJoystick;
  37087. })();
  37088. BABYLON.VirtualJoystick = VirtualJoystick;
  37089. })(BABYLON || (BABYLON = {}));
  37090. var BABYLON;
  37091. (function (BABYLON) {
  37092. // We're mainly based on the logic defined into the FreeCamera code
  37093. var VirtualJoysticksCamera = (function (_super) {
  37094. __extends(VirtualJoysticksCamera, _super);
  37095. function VirtualJoysticksCamera(name, position, scene) {
  37096. _super.call(this, name, position, scene);
  37097. this.inputs.addVirtualJoystick();
  37098. }
  37099. return VirtualJoysticksCamera;
  37100. })(BABYLON.FreeCamera);
  37101. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  37102. })(BABYLON || (BABYLON = {}));
  37103. var BABYLON;
  37104. (function (BABYLON) {
  37105. var AnaglyphPostProcess = (function (_super) {
  37106. __extends(AnaglyphPostProcess, _super);
  37107. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37108. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  37109. }
  37110. return AnaglyphPostProcess;
  37111. })(BABYLON.PostProcess);
  37112. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  37113. })(BABYLON || (BABYLON = {}));
  37114. var BABYLON;
  37115. (function (BABYLON) {
  37116. var OutlineRenderer = (function () {
  37117. function OutlineRenderer(scene) {
  37118. this._scene = scene;
  37119. }
  37120. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  37121. var _this = this;
  37122. if (useOverlay === void 0) { useOverlay = false; }
  37123. var scene = this._scene;
  37124. var engine = this._scene.getEngine();
  37125. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37126. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  37127. return;
  37128. }
  37129. var mesh = subMesh.getRenderingMesh();
  37130. var material = subMesh.getMaterial();
  37131. engine.enableEffect(this._effect);
  37132. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  37133. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  37134. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  37135. // Bones
  37136. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37137. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37138. }
  37139. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  37140. // Alpha test
  37141. if (material && material.needAlphaTesting()) {
  37142. var alphaTexture = material.getAlphaTestTexture();
  37143. this._effect.setTexture("diffuseSampler", alphaTexture);
  37144. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37145. }
  37146. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  37147. };
  37148. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  37149. var defines = [];
  37150. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  37151. var mesh = subMesh.getMesh();
  37152. var material = subMesh.getMaterial();
  37153. // Alpha test
  37154. if (material && material.needAlphaTesting()) {
  37155. defines.push("#define ALPHATEST");
  37156. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37157. attribs.push(BABYLON.VertexBuffer.UVKind);
  37158. defines.push("#define UV1");
  37159. }
  37160. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37161. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37162. defines.push("#define UV2");
  37163. }
  37164. }
  37165. // Bones
  37166. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37167. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37168. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37169. if (mesh.numBoneInfluencers > 4) {
  37170. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37171. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37172. }
  37173. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37174. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37175. }
  37176. else {
  37177. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37178. }
  37179. // Instances
  37180. if (useInstances) {
  37181. defines.push("#define INSTANCES");
  37182. attribs.push("world0");
  37183. attribs.push("world1");
  37184. attribs.push("world2");
  37185. attribs.push("world3");
  37186. }
  37187. // Get correct effect
  37188. var join = defines.join("\n");
  37189. if (this._cachedDefines !== join) {
  37190. this._cachedDefines = join;
  37191. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  37192. }
  37193. return this._effect.isReady();
  37194. };
  37195. return OutlineRenderer;
  37196. })();
  37197. BABYLON.OutlineRenderer = OutlineRenderer;
  37198. })(BABYLON || (BABYLON = {}));
  37199. var BABYLON;
  37200. (function (BABYLON) {
  37201. var MeshAssetTask = (function () {
  37202. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  37203. this.name = name;
  37204. this.meshesNames = meshesNames;
  37205. this.rootUrl = rootUrl;
  37206. this.sceneFilename = sceneFilename;
  37207. this.isCompleted = false;
  37208. }
  37209. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37210. var _this = this;
  37211. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  37212. _this.loadedMeshes = meshes;
  37213. _this.loadedParticleSystems = particleSystems;
  37214. _this.loadedSkeletons = skeletons;
  37215. _this.isCompleted = true;
  37216. if (_this.onSuccess) {
  37217. _this.onSuccess(_this);
  37218. }
  37219. onSuccess();
  37220. }, null, function () {
  37221. if (_this.onError) {
  37222. _this.onError(_this);
  37223. }
  37224. onError();
  37225. });
  37226. };
  37227. return MeshAssetTask;
  37228. })();
  37229. BABYLON.MeshAssetTask = MeshAssetTask;
  37230. var TextFileAssetTask = (function () {
  37231. function TextFileAssetTask(name, url) {
  37232. this.name = name;
  37233. this.url = url;
  37234. this.isCompleted = false;
  37235. }
  37236. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37237. var _this = this;
  37238. BABYLON.Tools.LoadFile(this.url, function (data) {
  37239. _this.text = data;
  37240. _this.isCompleted = true;
  37241. if (_this.onSuccess) {
  37242. _this.onSuccess(_this);
  37243. }
  37244. onSuccess();
  37245. }, null, scene.database, false, function () {
  37246. if (_this.onError) {
  37247. _this.onError(_this);
  37248. }
  37249. onError();
  37250. });
  37251. };
  37252. return TextFileAssetTask;
  37253. })();
  37254. BABYLON.TextFileAssetTask = TextFileAssetTask;
  37255. var BinaryFileAssetTask = (function () {
  37256. function BinaryFileAssetTask(name, url) {
  37257. this.name = name;
  37258. this.url = url;
  37259. this.isCompleted = false;
  37260. }
  37261. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37262. var _this = this;
  37263. BABYLON.Tools.LoadFile(this.url, function (data) {
  37264. _this.data = data;
  37265. _this.isCompleted = true;
  37266. if (_this.onSuccess) {
  37267. _this.onSuccess(_this);
  37268. }
  37269. onSuccess();
  37270. }, null, scene.database, true, function () {
  37271. if (_this.onError) {
  37272. _this.onError(_this);
  37273. }
  37274. onError();
  37275. });
  37276. };
  37277. return BinaryFileAssetTask;
  37278. })();
  37279. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  37280. var ImageAssetTask = (function () {
  37281. function ImageAssetTask(name, url) {
  37282. this.name = name;
  37283. this.url = url;
  37284. this.isCompleted = false;
  37285. }
  37286. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37287. var _this = this;
  37288. var img = new Image();
  37289. img.onload = function () {
  37290. _this.image = img;
  37291. _this.isCompleted = true;
  37292. if (_this.onSuccess) {
  37293. _this.onSuccess(_this);
  37294. }
  37295. onSuccess();
  37296. };
  37297. img.onerror = function () {
  37298. if (_this.onError) {
  37299. _this.onError(_this);
  37300. }
  37301. onError();
  37302. };
  37303. img.src = this.url;
  37304. };
  37305. return ImageAssetTask;
  37306. })();
  37307. BABYLON.ImageAssetTask = ImageAssetTask;
  37308. var TextureAssetTask = (function () {
  37309. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  37310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37311. this.name = name;
  37312. this.url = url;
  37313. this.noMipmap = noMipmap;
  37314. this.invertY = invertY;
  37315. this.samplingMode = samplingMode;
  37316. this.isCompleted = false;
  37317. }
  37318. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37319. var _this = this;
  37320. var onload = function () {
  37321. _this.isCompleted = true;
  37322. if (_this.onSuccess) {
  37323. _this.onSuccess(_this);
  37324. }
  37325. onSuccess();
  37326. };
  37327. var onerror = function () {
  37328. if (_this.onError) {
  37329. _this.onError(_this);
  37330. }
  37331. onError();
  37332. };
  37333. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  37334. };
  37335. return TextureAssetTask;
  37336. })();
  37337. BABYLON.TextureAssetTask = TextureAssetTask;
  37338. var AssetsManager = (function () {
  37339. function AssetsManager(scene) {
  37340. this._tasks = new Array();
  37341. this._waitingTasksCount = 0;
  37342. this.useDefaultLoadingScreen = true;
  37343. this._scene = scene;
  37344. }
  37345. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  37346. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  37347. this._tasks.push(task);
  37348. return task;
  37349. };
  37350. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  37351. var task = new TextFileAssetTask(taskName, url);
  37352. this._tasks.push(task);
  37353. return task;
  37354. };
  37355. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  37356. var task = new BinaryFileAssetTask(taskName, url);
  37357. this._tasks.push(task);
  37358. return task;
  37359. };
  37360. AssetsManager.prototype.addImageTask = function (taskName, url) {
  37361. var task = new ImageAssetTask(taskName, url);
  37362. this._tasks.push(task);
  37363. return task;
  37364. };
  37365. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  37366. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37367. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  37368. this._tasks.push(task);
  37369. return task;
  37370. };
  37371. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  37372. this._waitingTasksCount--;
  37373. if (this._waitingTasksCount === 0) {
  37374. if (this.onFinish) {
  37375. this.onFinish(this._tasks);
  37376. }
  37377. this._scene.getEngine().hideLoadingUI();
  37378. }
  37379. };
  37380. AssetsManager.prototype._runTask = function (task) {
  37381. var _this = this;
  37382. task.run(this._scene, function () {
  37383. if (_this.onTaskSuccess) {
  37384. _this.onTaskSuccess(task);
  37385. }
  37386. _this._decreaseWaitingTasksCount();
  37387. }, function () {
  37388. if (_this.onTaskError) {
  37389. _this.onTaskError(task);
  37390. }
  37391. _this._decreaseWaitingTasksCount();
  37392. });
  37393. };
  37394. AssetsManager.prototype.reset = function () {
  37395. this._tasks = new Array();
  37396. return this;
  37397. };
  37398. AssetsManager.prototype.load = function () {
  37399. this._waitingTasksCount = this._tasks.length;
  37400. if (this._waitingTasksCount === 0) {
  37401. if (this.onFinish) {
  37402. this.onFinish(this._tasks);
  37403. }
  37404. return this;
  37405. }
  37406. if (this.useDefaultLoadingScreen) {
  37407. this._scene.getEngine().displayLoadingUI();
  37408. }
  37409. for (var index = 0; index < this._tasks.length; index++) {
  37410. var task = this._tasks[index];
  37411. this._runTask(task);
  37412. }
  37413. return this;
  37414. };
  37415. return AssetsManager;
  37416. })();
  37417. BABYLON.AssetsManager = AssetsManager;
  37418. })(BABYLON || (BABYLON = {}));
  37419. var BABYLON;
  37420. (function (BABYLON) {
  37421. var VRCameraMetrics = (function () {
  37422. function VRCameraMetrics() {
  37423. this.compensateDistortion = true;
  37424. }
  37425. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  37426. get: function () {
  37427. return this.hResolution / (2 * this.vResolution);
  37428. },
  37429. enumerable: true,
  37430. configurable: true
  37431. });
  37432. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  37433. get: function () {
  37434. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  37435. },
  37436. enumerable: true,
  37437. configurable: true
  37438. });
  37439. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  37440. get: function () {
  37441. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37442. var h = (4 * meters) / this.hScreenSize;
  37443. return BABYLON.Matrix.Translation(h, 0, 0);
  37444. },
  37445. enumerable: true,
  37446. configurable: true
  37447. });
  37448. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  37449. get: function () {
  37450. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37451. var h = (4 * meters) / this.hScreenSize;
  37452. return BABYLON.Matrix.Translation(-h, 0, 0);
  37453. },
  37454. enumerable: true,
  37455. configurable: true
  37456. });
  37457. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  37458. get: function () {
  37459. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  37460. },
  37461. enumerable: true,
  37462. configurable: true
  37463. });
  37464. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  37465. get: function () {
  37466. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  37467. },
  37468. enumerable: true,
  37469. configurable: true
  37470. });
  37471. VRCameraMetrics.GetDefault = function () {
  37472. var result = new VRCameraMetrics();
  37473. result.hResolution = 1280;
  37474. result.vResolution = 800;
  37475. result.hScreenSize = 0.149759993;
  37476. result.vScreenSize = 0.0935999975;
  37477. result.vScreenCenter = 0.0467999987,
  37478. result.eyeToScreenDistance = 0.0410000011;
  37479. result.lensSeparationDistance = 0.0635000020;
  37480. result.interpupillaryDistance = 0.0640000030;
  37481. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  37482. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  37483. result.postProcessScaleFactor = 1.714605507808412;
  37484. result.lensCenterOffset = 0.151976421;
  37485. return result;
  37486. };
  37487. return VRCameraMetrics;
  37488. })();
  37489. BABYLON.VRCameraMetrics = VRCameraMetrics;
  37490. })(BABYLON || (BABYLON = {}));
  37491. var BABYLON;
  37492. (function (BABYLON) {
  37493. var VRDeviceOrientationFreeCamera = (function (_super) {
  37494. __extends(VRDeviceOrientationFreeCamera, _super);
  37495. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  37496. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37497. _super.call(this, name, position, scene);
  37498. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37499. metrics.compensateDistortion = compensateDistortion;
  37500. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37501. this.inputs.addVRDeviceOrientation();
  37502. }
  37503. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  37504. return "VRDeviceOrientationFreeCamera";
  37505. };
  37506. return VRDeviceOrientationFreeCamera;
  37507. })(BABYLON.FreeCamera);
  37508. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  37509. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  37510. __extends(VRDeviceOrientationArcRotateCamera, _super);
  37511. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  37512. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37513. _super.call(this, name, alpha, beta, radius, target, scene);
  37514. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37515. metrics.compensateDistortion = compensateDistortion;
  37516. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37517. this.inputs.addVRDeviceOrientation();
  37518. }
  37519. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  37520. return "VRDeviceOrientationArcRotateCamera";
  37521. };
  37522. return VRDeviceOrientationArcRotateCamera;
  37523. })(BABYLON.ArcRotateCamera);
  37524. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  37525. })(BABYLON || (BABYLON = {}));
  37526. var BABYLON;
  37527. (function (BABYLON) {
  37528. var WebVRFreeCamera = (function (_super) {
  37529. __extends(WebVRFreeCamera, _super);
  37530. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  37531. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37532. _super.call(this, name, position, scene);
  37533. this._hmdDevice = null;
  37534. this._sensorDevice = null;
  37535. this._cacheState = null;
  37536. this._cacheQuaternion = new BABYLON.Quaternion();
  37537. this._cacheRotation = BABYLON.Vector3.Zero();
  37538. this._vrEnabled = false;
  37539. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37540. metrics.compensateDistortion = compensateDistortion;
  37541. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37542. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  37543. }
  37544. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  37545. var size = devices.length;
  37546. var i = 0;
  37547. // Reset devices.
  37548. this._sensorDevice = null;
  37549. this._hmdDevice = null;
  37550. // Search for a HmdDevice.
  37551. while (i < size && this._hmdDevice === null) {
  37552. if (devices[i] instanceof HMDVRDevice) {
  37553. this._hmdDevice = devices[i];
  37554. }
  37555. i++;
  37556. }
  37557. i = 0;
  37558. while (i < size && this._sensorDevice === null) {
  37559. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  37560. this._sensorDevice = devices[i];
  37561. }
  37562. i++;
  37563. }
  37564. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  37565. };
  37566. WebVRFreeCamera.prototype._checkInputs = function () {
  37567. if (this._vrEnabled) {
  37568. this._cacheState = this._sensorDevice.getState();
  37569. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  37570. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  37571. this.rotation.x = -this._cacheRotation.x;
  37572. this.rotation.y = -this._cacheRotation.y;
  37573. this.rotation.z = this._cacheRotation.z;
  37574. }
  37575. _super.prototype._checkInputs.call(this);
  37576. };
  37577. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37578. _super.prototype.attachControl.call(this, element, noPreventDefault);
  37579. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37580. if (navigator.getVRDevices) {
  37581. navigator.getVRDevices().then(this._getWebVRDevices);
  37582. }
  37583. else if (navigator.mozGetVRDevices) {
  37584. navigator.mozGetVRDevices(this._getWebVRDevices);
  37585. }
  37586. };
  37587. WebVRFreeCamera.prototype.detachControl = function (element) {
  37588. _super.prototype.detachControl.call(this, element);
  37589. this._vrEnabled = false;
  37590. };
  37591. WebVRFreeCamera.prototype.getTypeName = function () {
  37592. return "WebVRFreeCamera";
  37593. };
  37594. return WebVRFreeCamera;
  37595. })(BABYLON.FreeCamera);
  37596. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  37597. })(BABYLON || (BABYLON = {}));
  37598. var BABYLON;
  37599. (function (BABYLON) {
  37600. // Standard optimizations
  37601. var SceneOptimization = (function () {
  37602. function SceneOptimization(priority) {
  37603. if (priority === void 0) { priority = 0; }
  37604. this.priority = priority;
  37605. this.apply = function (scene) {
  37606. return true; // Return true if everything that can be done was applied
  37607. };
  37608. }
  37609. return SceneOptimization;
  37610. })();
  37611. BABYLON.SceneOptimization = SceneOptimization;
  37612. var TextureOptimization = (function (_super) {
  37613. __extends(TextureOptimization, _super);
  37614. function TextureOptimization(priority, maximumSize) {
  37615. var _this = this;
  37616. if (priority === void 0) { priority = 0; }
  37617. if (maximumSize === void 0) { maximumSize = 1024; }
  37618. _super.call(this, priority);
  37619. this.priority = priority;
  37620. this.maximumSize = maximumSize;
  37621. this.apply = function (scene) {
  37622. var allDone = true;
  37623. for (var index = 0; index < scene.textures.length; index++) {
  37624. var texture = scene.textures[index];
  37625. if (!texture.canRescale) {
  37626. continue;
  37627. }
  37628. var currentSize = texture.getSize();
  37629. var maxDimension = Math.max(currentSize.width, currentSize.height);
  37630. if (maxDimension > _this.maximumSize) {
  37631. texture.scale(0.5);
  37632. allDone = false;
  37633. }
  37634. }
  37635. return allDone;
  37636. };
  37637. }
  37638. return TextureOptimization;
  37639. })(SceneOptimization);
  37640. BABYLON.TextureOptimization = TextureOptimization;
  37641. var HardwareScalingOptimization = (function (_super) {
  37642. __extends(HardwareScalingOptimization, _super);
  37643. function HardwareScalingOptimization(priority, maximumScale) {
  37644. var _this = this;
  37645. if (priority === void 0) { priority = 0; }
  37646. if (maximumScale === void 0) { maximumScale = 2; }
  37647. _super.call(this, priority);
  37648. this.priority = priority;
  37649. this.maximumScale = maximumScale;
  37650. this._currentScale = 1;
  37651. this.apply = function (scene) {
  37652. _this._currentScale++;
  37653. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  37654. return _this._currentScale >= _this.maximumScale;
  37655. };
  37656. }
  37657. return HardwareScalingOptimization;
  37658. })(SceneOptimization);
  37659. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  37660. var ShadowsOptimization = (function (_super) {
  37661. __extends(ShadowsOptimization, _super);
  37662. function ShadowsOptimization() {
  37663. _super.apply(this, arguments);
  37664. this.apply = function (scene) {
  37665. scene.shadowsEnabled = false;
  37666. return true;
  37667. };
  37668. }
  37669. return ShadowsOptimization;
  37670. })(SceneOptimization);
  37671. BABYLON.ShadowsOptimization = ShadowsOptimization;
  37672. var PostProcessesOptimization = (function (_super) {
  37673. __extends(PostProcessesOptimization, _super);
  37674. function PostProcessesOptimization() {
  37675. _super.apply(this, arguments);
  37676. this.apply = function (scene) {
  37677. scene.postProcessesEnabled = false;
  37678. return true;
  37679. };
  37680. }
  37681. return PostProcessesOptimization;
  37682. })(SceneOptimization);
  37683. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  37684. var LensFlaresOptimization = (function (_super) {
  37685. __extends(LensFlaresOptimization, _super);
  37686. function LensFlaresOptimization() {
  37687. _super.apply(this, arguments);
  37688. this.apply = function (scene) {
  37689. scene.lensFlaresEnabled = false;
  37690. return true;
  37691. };
  37692. }
  37693. return LensFlaresOptimization;
  37694. })(SceneOptimization);
  37695. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  37696. var ParticlesOptimization = (function (_super) {
  37697. __extends(ParticlesOptimization, _super);
  37698. function ParticlesOptimization() {
  37699. _super.apply(this, arguments);
  37700. this.apply = function (scene) {
  37701. scene.particlesEnabled = false;
  37702. return true;
  37703. };
  37704. }
  37705. return ParticlesOptimization;
  37706. })(SceneOptimization);
  37707. BABYLON.ParticlesOptimization = ParticlesOptimization;
  37708. var RenderTargetsOptimization = (function (_super) {
  37709. __extends(RenderTargetsOptimization, _super);
  37710. function RenderTargetsOptimization() {
  37711. _super.apply(this, arguments);
  37712. this.apply = function (scene) {
  37713. scene.renderTargetsEnabled = false;
  37714. return true;
  37715. };
  37716. }
  37717. return RenderTargetsOptimization;
  37718. })(SceneOptimization);
  37719. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  37720. var MergeMeshesOptimization = (function (_super) {
  37721. __extends(MergeMeshesOptimization, _super);
  37722. function MergeMeshesOptimization() {
  37723. var _this = this;
  37724. _super.apply(this, arguments);
  37725. this._canBeMerged = function (abstractMesh) {
  37726. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  37727. return false;
  37728. }
  37729. var mesh = abstractMesh;
  37730. if (!mesh.isVisible || !mesh.isEnabled()) {
  37731. return false;
  37732. }
  37733. if (mesh.instances.length > 0) {
  37734. return false;
  37735. }
  37736. if (mesh.skeleton || mesh.hasLODLevels) {
  37737. return false;
  37738. }
  37739. if (mesh.parent) {
  37740. return false;
  37741. }
  37742. return true;
  37743. };
  37744. this.apply = function (scene, updateSelectionTree) {
  37745. var globalPool = scene.meshes.slice(0);
  37746. var globalLength = globalPool.length;
  37747. for (var index = 0; index < globalLength; index++) {
  37748. var currentPool = new Array();
  37749. var current = globalPool[index];
  37750. // Checks
  37751. if (!_this._canBeMerged(current)) {
  37752. continue;
  37753. }
  37754. currentPool.push(current);
  37755. // Find compatible meshes
  37756. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  37757. var otherMesh = globalPool[subIndex];
  37758. if (!_this._canBeMerged(otherMesh)) {
  37759. continue;
  37760. }
  37761. if (otherMesh.material !== current.material) {
  37762. continue;
  37763. }
  37764. if (otherMesh.checkCollisions !== current.checkCollisions) {
  37765. continue;
  37766. }
  37767. currentPool.push(otherMesh);
  37768. globalLength--;
  37769. globalPool.splice(subIndex, 1);
  37770. subIndex--;
  37771. }
  37772. if (currentPool.length < 2) {
  37773. continue;
  37774. }
  37775. // Merge meshes
  37776. BABYLON.Mesh.MergeMeshes(currentPool);
  37777. }
  37778. if (updateSelectionTree != undefined) {
  37779. if (updateSelectionTree) {
  37780. scene.createOrUpdateSelectionOctree();
  37781. }
  37782. }
  37783. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  37784. scene.createOrUpdateSelectionOctree();
  37785. }
  37786. return true;
  37787. };
  37788. }
  37789. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  37790. get: function () {
  37791. return MergeMeshesOptimization._UpdateSelectionTree;
  37792. },
  37793. set: function (value) {
  37794. MergeMeshesOptimization._UpdateSelectionTree = value;
  37795. },
  37796. enumerable: true,
  37797. configurable: true
  37798. });
  37799. MergeMeshesOptimization._UpdateSelectionTree = false;
  37800. return MergeMeshesOptimization;
  37801. })(SceneOptimization);
  37802. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  37803. // Options
  37804. var SceneOptimizerOptions = (function () {
  37805. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  37806. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  37807. if (trackerDuration === void 0) { trackerDuration = 2000; }
  37808. this.targetFrameRate = targetFrameRate;
  37809. this.trackerDuration = trackerDuration;
  37810. this.optimizations = new Array();
  37811. }
  37812. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  37813. var result = new SceneOptimizerOptions(targetFrameRate);
  37814. var priority = 0;
  37815. result.optimizations.push(new MergeMeshesOptimization(priority));
  37816. result.optimizations.push(new ShadowsOptimization(priority));
  37817. result.optimizations.push(new LensFlaresOptimization(priority));
  37818. // Next priority
  37819. priority++;
  37820. result.optimizations.push(new PostProcessesOptimization(priority));
  37821. result.optimizations.push(new ParticlesOptimization(priority));
  37822. // Next priority
  37823. priority++;
  37824. result.optimizations.push(new TextureOptimization(priority, 1024));
  37825. return result;
  37826. };
  37827. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  37828. var result = new SceneOptimizerOptions(targetFrameRate);
  37829. var priority = 0;
  37830. result.optimizations.push(new MergeMeshesOptimization(priority));
  37831. result.optimizations.push(new ShadowsOptimization(priority));
  37832. result.optimizations.push(new LensFlaresOptimization(priority));
  37833. // Next priority
  37834. priority++;
  37835. result.optimizations.push(new PostProcessesOptimization(priority));
  37836. result.optimizations.push(new ParticlesOptimization(priority));
  37837. // Next priority
  37838. priority++;
  37839. result.optimizations.push(new TextureOptimization(priority, 512));
  37840. // Next priority
  37841. priority++;
  37842. result.optimizations.push(new RenderTargetsOptimization(priority));
  37843. // Next priority
  37844. priority++;
  37845. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  37846. return result;
  37847. };
  37848. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  37849. var result = new SceneOptimizerOptions(targetFrameRate);
  37850. var priority = 0;
  37851. result.optimizations.push(new MergeMeshesOptimization(priority));
  37852. result.optimizations.push(new ShadowsOptimization(priority));
  37853. result.optimizations.push(new LensFlaresOptimization(priority));
  37854. // Next priority
  37855. priority++;
  37856. result.optimizations.push(new PostProcessesOptimization(priority));
  37857. result.optimizations.push(new ParticlesOptimization(priority));
  37858. // Next priority
  37859. priority++;
  37860. result.optimizations.push(new TextureOptimization(priority, 256));
  37861. // Next priority
  37862. priority++;
  37863. result.optimizations.push(new RenderTargetsOptimization(priority));
  37864. // Next priority
  37865. priority++;
  37866. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  37867. return result;
  37868. };
  37869. return SceneOptimizerOptions;
  37870. })();
  37871. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  37872. // Scene optimizer tool
  37873. var SceneOptimizer = (function () {
  37874. function SceneOptimizer() {
  37875. }
  37876. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  37877. // TODO: add an epsilon
  37878. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  37879. if (onSuccess) {
  37880. onSuccess();
  37881. }
  37882. return;
  37883. }
  37884. // Apply current level of optimizations
  37885. var allDone = true;
  37886. var noOptimizationApplied = true;
  37887. for (var index = 0; index < options.optimizations.length; index++) {
  37888. var optimization = options.optimizations[index];
  37889. if (optimization.priority === currentPriorityLevel) {
  37890. noOptimizationApplied = false;
  37891. allDone = allDone && optimization.apply(scene);
  37892. }
  37893. }
  37894. // If no optimization was applied, this is a failure :(
  37895. if (noOptimizationApplied) {
  37896. if (onFailure) {
  37897. onFailure();
  37898. }
  37899. return;
  37900. }
  37901. // If all optimizations were done, move to next level
  37902. if (allDone) {
  37903. currentPriorityLevel++;
  37904. }
  37905. // Let's the system running for a specific amount of time before checking FPS
  37906. scene.executeWhenReady(function () {
  37907. setTimeout(function () {
  37908. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  37909. }, options.trackerDuration);
  37910. });
  37911. };
  37912. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  37913. if (!options) {
  37914. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  37915. }
  37916. // Let's the system running for a specific amount of time before checking FPS
  37917. scene.executeWhenReady(function () {
  37918. setTimeout(function () {
  37919. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  37920. }, options.trackerDuration);
  37921. });
  37922. };
  37923. return SceneOptimizer;
  37924. })();
  37925. BABYLON.SceneOptimizer = SceneOptimizer;
  37926. })(BABYLON || (BABYLON = {}));
  37927. var BABYLON;
  37928. (function (BABYLON) {
  37929. var Internals;
  37930. (function (Internals) {
  37931. var MeshLODLevel = (function () {
  37932. function MeshLODLevel(distance, mesh) {
  37933. this.distance = distance;
  37934. this.mesh = mesh;
  37935. }
  37936. return MeshLODLevel;
  37937. })();
  37938. Internals.MeshLODLevel = MeshLODLevel;
  37939. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37940. })(BABYLON || (BABYLON = {}));
  37941. var BABYLON;
  37942. (function (BABYLON) {
  37943. var RawTexture = (function (_super) {
  37944. __extends(RawTexture, _super);
  37945. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  37946. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37947. if (invertY === void 0) { invertY = false; }
  37948. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37949. _super.call(this, null, scene, !generateMipMaps, invertY);
  37950. this.format = format;
  37951. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  37952. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37953. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37954. }
  37955. RawTexture.prototype.update = function (data) {
  37956. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  37957. };
  37958. // Statics
  37959. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37960. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37961. if (invertY === void 0) { invertY = false; }
  37962. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37963. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  37964. };
  37965. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37966. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37967. if (invertY === void 0) { invertY = false; }
  37968. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37969. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  37970. };
  37971. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37972. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37973. if (invertY === void 0) { invertY = false; }
  37974. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37975. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  37976. };
  37977. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37978. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37979. if (invertY === void 0) { invertY = false; }
  37980. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37981. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  37982. };
  37983. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37984. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37985. if (invertY === void 0) { invertY = false; }
  37986. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37987. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  37988. };
  37989. return RawTexture;
  37990. })(BABYLON.Texture);
  37991. BABYLON.RawTexture = RawTexture;
  37992. })(BABYLON || (BABYLON = {}));
  37993. var BABYLON;
  37994. (function (BABYLON) {
  37995. var IndexedVector2 = (function (_super) {
  37996. __extends(IndexedVector2, _super);
  37997. function IndexedVector2(original, index) {
  37998. _super.call(this, original.x, original.y);
  37999. this.index = index;
  38000. }
  38001. return IndexedVector2;
  38002. })(BABYLON.Vector2);
  38003. var PolygonPoints = (function () {
  38004. function PolygonPoints() {
  38005. this.elements = new Array();
  38006. }
  38007. PolygonPoints.prototype.add = function (originalPoints) {
  38008. var _this = this;
  38009. var result = new Array();
  38010. originalPoints.forEach(function (point) {
  38011. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  38012. var newPoint = new IndexedVector2(point, _this.elements.length);
  38013. result.push(newPoint);
  38014. _this.elements.push(newPoint);
  38015. }
  38016. });
  38017. return result;
  38018. };
  38019. PolygonPoints.prototype.computeBounds = function () {
  38020. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  38021. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  38022. this.elements.forEach(function (point) {
  38023. // x
  38024. if (point.x < lmin.x) {
  38025. lmin.x = point.x;
  38026. }
  38027. else if (point.x > lmax.x) {
  38028. lmax.x = point.x;
  38029. }
  38030. // y
  38031. if (point.y < lmin.y) {
  38032. lmin.y = point.y;
  38033. }
  38034. else if (point.y > lmax.y) {
  38035. lmax.y = point.y;
  38036. }
  38037. });
  38038. return {
  38039. min: lmin,
  38040. max: lmax,
  38041. width: lmax.x - lmin.x,
  38042. height: lmax.y - lmin.y
  38043. };
  38044. };
  38045. return PolygonPoints;
  38046. })();
  38047. var Polygon = (function () {
  38048. function Polygon() {
  38049. }
  38050. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  38051. return [
  38052. new BABYLON.Vector2(xmin, ymin),
  38053. new BABYLON.Vector2(xmax, ymin),
  38054. new BABYLON.Vector2(xmax, ymax),
  38055. new BABYLON.Vector2(xmin, ymax)
  38056. ];
  38057. };
  38058. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  38059. if (cx === void 0) { cx = 0; }
  38060. if (cy === void 0) { cy = 0; }
  38061. if (numberOfSides === void 0) { numberOfSides = 32; }
  38062. var result = new Array();
  38063. var angle = 0;
  38064. var increment = (Math.PI * 2) / numberOfSides;
  38065. for (var i = 0; i < numberOfSides; i++) {
  38066. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  38067. angle -= increment;
  38068. }
  38069. return result;
  38070. };
  38071. Polygon.Parse = function (input) {
  38072. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  38073. var i, result = [];
  38074. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  38075. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  38076. }
  38077. return result;
  38078. };
  38079. Polygon.StartingAt = function (x, y) {
  38080. return BABYLON.Path2.StartingAt(x, y);
  38081. };
  38082. return Polygon;
  38083. })();
  38084. BABYLON.Polygon = Polygon;
  38085. var PolygonMeshBuilder = (function () {
  38086. function PolygonMeshBuilder(name, contours, scene) {
  38087. this._points = new PolygonPoints();
  38088. this._outlinepoints = new PolygonPoints();
  38089. this._holes = [];
  38090. if (!("poly2tri" in window)) {
  38091. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  38092. }
  38093. this._name = name;
  38094. this._scene = scene;
  38095. var points;
  38096. if (contours instanceof BABYLON.Path2) {
  38097. points = contours.getPoints();
  38098. }
  38099. else {
  38100. points = contours;
  38101. }
  38102. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  38103. this._outlinepoints.add(points);
  38104. }
  38105. PolygonMeshBuilder.prototype.addHole = function (hole) {
  38106. this._swctx.addHole(this._points.add(hole));
  38107. var holepoints = new PolygonPoints();
  38108. holepoints.add(hole);
  38109. this._holes.push(holepoints);
  38110. return this;
  38111. };
  38112. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  38113. var _this = this;
  38114. if (updatable === void 0) { updatable = false; }
  38115. var result = new BABYLON.Mesh(this._name, this._scene);
  38116. var normals = [];
  38117. var positions = [];
  38118. var uvs = [];
  38119. var bounds = this._points.computeBounds();
  38120. this._points.elements.forEach(function (p) {
  38121. normals.push(0, 1.0, 0);
  38122. positions.push(p.x, 0, p.y);
  38123. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  38124. });
  38125. var indices = [];
  38126. this._swctx.triangulate();
  38127. this._swctx.getTriangles().forEach(function (triangle) {
  38128. triangle.getPoints().forEach(function (point) {
  38129. indices.push(point.index);
  38130. });
  38131. });
  38132. if (depth > 0) {
  38133. var positionscount = (positions.length / 3); //get the current pointcount
  38134. this._points.elements.forEach(function (p) {
  38135. normals.push(0, -1.0, 0);
  38136. positions.push(p.x, -depth, p.y);
  38137. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  38138. });
  38139. var p1; //we need to change order of point so the triangles are made in the rigth way.
  38140. var p2;
  38141. var poscounter = 0;
  38142. this._swctx.getTriangles().forEach(function (triangle) {
  38143. triangle.getPoints().forEach(function (point) {
  38144. switch (poscounter) {
  38145. case 0:
  38146. p1 = point;
  38147. break;
  38148. case 1:
  38149. p2 = point;
  38150. break;
  38151. case 2:
  38152. indices.push(point.index + positionscount);
  38153. indices.push(p2.index + positionscount);
  38154. indices.push(p1.index + positionscount);
  38155. poscounter = -1;
  38156. break;
  38157. }
  38158. poscounter++;
  38159. //indices.push((<IndexedVector2>point).index + positionscount);
  38160. });
  38161. });
  38162. //Add the sides
  38163. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  38164. this._holes.forEach(function (hole) {
  38165. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  38166. });
  38167. }
  38168. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  38169. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  38170. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  38171. result.setIndices(indices);
  38172. return result;
  38173. };
  38174. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  38175. var StartIndex = positions.length / 3;
  38176. var ulength = 0;
  38177. for (var i = 0; i < points.elements.length; i++) {
  38178. var p = points.elements[i];
  38179. var p1;
  38180. if ((i + 1) > points.elements.length - 1) {
  38181. p1 = points.elements[0];
  38182. }
  38183. else {
  38184. p1 = points.elements[i + 1];
  38185. }
  38186. positions.push(p.x, 0, p.y);
  38187. positions.push(p.x, -depth, p.y);
  38188. positions.push(p1.x, 0, p1.y);
  38189. positions.push(p1.x, -depth, p1.y);
  38190. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  38191. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  38192. var v3 = v2.subtract(v1);
  38193. var v4 = new BABYLON.Vector3(0, 1, 0);
  38194. var vn = BABYLON.Vector3.Cross(v3, v4);
  38195. vn = vn.normalize();
  38196. uvs.push(ulength / bounds.width, 0);
  38197. uvs.push(ulength / bounds.width, 1);
  38198. ulength += v3.length();
  38199. uvs.push((ulength / bounds.width), 0);
  38200. uvs.push((ulength / bounds.width), 1);
  38201. if (!flip) {
  38202. normals.push(-vn.x, -vn.y, -vn.z);
  38203. normals.push(-vn.x, -vn.y, -vn.z);
  38204. normals.push(-vn.x, -vn.y, -vn.z);
  38205. normals.push(-vn.x, -vn.y, -vn.z);
  38206. indices.push(StartIndex);
  38207. indices.push(StartIndex + 1);
  38208. indices.push(StartIndex + 2);
  38209. indices.push(StartIndex + 1);
  38210. indices.push(StartIndex + 3);
  38211. indices.push(StartIndex + 2);
  38212. }
  38213. else {
  38214. normals.push(vn.x, vn.y, vn.z);
  38215. normals.push(vn.x, vn.y, vn.z);
  38216. normals.push(vn.x, vn.y, vn.z);
  38217. normals.push(vn.x, vn.y, vn.z);
  38218. indices.push(StartIndex);
  38219. indices.push(StartIndex + 2);
  38220. indices.push(StartIndex + 1);
  38221. indices.push(StartIndex + 1);
  38222. indices.push(StartIndex + 2);
  38223. indices.push(StartIndex + 3);
  38224. }
  38225. StartIndex += 4;
  38226. }
  38227. ;
  38228. };
  38229. return PolygonMeshBuilder;
  38230. })();
  38231. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  38232. })(BABYLON || (BABYLON = {}));
  38233. var BABYLON;
  38234. (function (BABYLON) {
  38235. var Octree = (function () {
  38236. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  38237. if (maxDepth === void 0) { maxDepth = 2; }
  38238. this.maxDepth = maxDepth;
  38239. this.dynamicContent = new Array();
  38240. this._maxBlockCapacity = maxBlockCapacity || 64;
  38241. this._selectionContent = new BABYLON.SmartArray(1024);
  38242. this._creationFunc = creationFunc;
  38243. }
  38244. // Methods
  38245. Octree.prototype.update = function (worldMin, worldMax, entries) {
  38246. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  38247. };
  38248. Octree.prototype.addMesh = function (entry) {
  38249. for (var index = 0; index < this.blocks.length; index++) {
  38250. var block = this.blocks[index];
  38251. block.addEntry(entry);
  38252. }
  38253. };
  38254. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  38255. this._selectionContent.reset();
  38256. for (var index = 0; index < this.blocks.length; index++) {
  38257. var block = this.blocks[index];
  38258. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  38259. }
  38260. if (allowDuplicate) {
  38261. this._selectionContent.concat(this.dynamicContent);
  38262. }
  38263. else {
  38264. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38265. }
  38266. return this._selectionContent;
  38267. };
  38268. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  38269. this._selectionContent.reset();
  38270. for (var index = 0; index < this.blocks.length; index++) {
  38271. var block = this.blocks[index];
  38272. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  38273. }
  38274. if (allowDuplicate) {
  38275. this._selectionContent.concat(this.dynamicContent);
  38276. }
  38277. else {
  38278. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38279. }
  38280. return this._selectionContent;
  38281. };
  38282. Octree.prototype.intersectsRay = function (ray) {
  38283. this._selectionContent.reset();
  38284. for (var index = 0; index < this.blocks.length; index++) {
  38285. var block = this.blocks[index];
  38286. block.intersectsRay(ray, this._selectionContent);
  38287. }
  38288. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38289. return this._selectionContent;
  38290. };
  38291. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  38292. target.blocks = new Array();
  38293. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  38294. // Segmenting space
  38295. for (var x = 0; x < 2; x++) {
  38296. for (var y = 0; y < 2; y++) {
  38297. for (var z = 0; z < 2; z++) {
  38298. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  38299. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  38300. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  38301. block.addEntries(entries);
  38302. target.blocks.push(block);
  38303. }
  38304. }
  38305. }
  38306. };
  38307. Octree.CreationFuncForMeshes = function (entry, block) {
  38308. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38309. block.entries.push(entry);
  38310. }
  38311. };
  38312. Octree.CreationFuncForSubMeshes = function (entry, block) {
  38313. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38314. block.entries.push(entry);
  38315. }
  38316. };
  38317. return Octree;
  38318. })();
  38319. BABYLON.Octree = Octree;
  38320. })(BABYLON || (BABYLON = {}));
  38321. var BABYLON;
  38322. (function (BABYLON) {
  38323. var OctreeBlock = (function () {
  38324. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  38325. this.entries = new Array();
  38326. this._boundingVectors = new Array();
  38327. this._capacity = capacity;
  38328. this._depth = depth;
  38329. this._maxDepth = maxDepth;
  38330. this._creationFunc = creationFunc;
  38331. this._minPoint = minPoint;
  38332. this._maxPoint = maxPoint;
  38333. this._boundingVectors.push(minPoint.clone());
  38334. this._boundingVectors.push(maxPoint.clone());
  38335. this._boundingVectors.push(minPoint.clone());
  38336. this._boundingVectors[2].x = maxPoint.x;
  38337. this._boundingVectors.push(minPoint.clone());
  38338. this._boundingVectors[3].y = maxPoint.y;
  38339. this._boundingVectors.push(minPoint.clone());
  38340. this._boundingVectors[4].z = maxPoint.z;
  38341. this._boundingVectors.push(maxPoint.clone());
  38342. this._boundingVectors[5].z = minPoint.z;
  38343. this._boundingVectors.push(maxPoint.clone());
  38344. this._boundingVectors[6].x = minPoint.x;
  38345. this._boundingVectors.push(maxPoint.clone());
  38346. this._boundingVectors[7].y = minPoint.y;
  38347. }
  38348. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  38349. // Property
  38350. get: function () {
  38351. return this._capacity;
  38352. },
  38353. enumerable: true,
  38354. configurable: true
  38355. });
  38356. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  38357. get: function () {
  38358. return this._minPoint;
  38359. },
  38360. enumerable: true,
  38361. configurable: true
  38362. });
  38363. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  38364. get: function () {
  38365. return this._maxPoint;
  38366. },
  38367. enumerable: true,
  38368. configurable: true
  38369. });
  38370. // Methods
  38371. OctreeBlock.prototype.addEntry = function (entry) {
  38372. if (this.blocks) {
  38373. for (var index = 0; index < this.blocks.length; index++) {
  38374. var block = this.blocks[index];
  38375. block.addEntry(entry);
  38376. }
  38377. return;
  38378. }
  38379. this._creationFunc(entry, this);
  38380. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  38381. this.createInnerBlocks();
  38382. }
  38383. };
  38384. OctreeBlock.prototype.addEntries = function (entries) {
  38385. for (var index = 0; index < entries.length; index++) {
  38386. var mesh = entries[index];
  38387. this.addEntry(mesh);
  38388. }
  38389. };
  38390. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  38391. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  38392. if (this.blocks) {
  38393. for (var index = 0; index < this.blocks.length; index++) {
  38394. var block = this.blocks[index];
  38395. block.select(frustumPlanes, selection, allowDuplicate);
  38396. }
  38397. return;
  38398. }
  38399. if (allowDuplicate) {
  38400. selection.concat(this.entries);
  38401. }
  38402. else {
  38403. selection.concatWithNoDuplicate(this.entries);
  38404. }
  38405. }
  38406. };
  38407. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  38408. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  38409. if (this.blocks) {
  38410. for (var index = 0; index < this.blocks.length; index++) {
  38411. var block = this.blocks[index];
  38412. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  38413. }
  38414. return;
  38415. }
  38416. if (allowDuplicate) {
  38417. selection.concat(this.entries);
  38418. }
  38419. else {
  38420. selection.concatWithNoDuplicate(this.entries);
  38421. }
  38422. }
  38423. };
  38424. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  38425. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  38426. if (this.blocks) {
  38427. for (var index = 0; index < this.blocks.length; index++) {
  38428. var block = this.blocks[index];
  38429. block.intersectsRay(ray, selection);
  38430. }
  38431. return;
  38432. }
  38433. selection.concatWithNoDuplicate(this.entries);
  38434. }
  38435. };
  38436. OctreeBlock.prototype.createInnerBlocks = function () {
  38437. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  38438. };
  38439. return OctreeBlock;
  38440. })();
  38441. BABYLON.OctreeBlock = OctreeBlock;
  38442. })(BABYLON || (BABYLON = {}));
  38443. var BABYLON;
  38444. (function (BABYLON) {
  38445. var BlurPostProcess = (function (_super) {
  38446. __extends(BlurPostProcess, _super);
  38447. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  38448. var _this = this;
  38449. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38450. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  38451. this.direction = direction;
  38452. this.blurWidth = blurWidth;
  38453. this.onApply = function (effect) {
  38454. effect.setFloat2("screenSize", _this.width, _this.height);
  38455. effect.setVector2("direction", _this.direction);
  38456. effect.setFloat("blurWidth", _this.blurWidth);
  38457. };
  38458. }
  38459. return BlurPostProcess;
  38460. })(BABYLON.PostProcess);
  38461. BABYLON.BlurPostProcess = BlurPostProcess;
  38462. })(BABYLON || (BABYLON = {}));
  38463. var BABYLON;
  38464. (function (BABYLON) {
  38465. var RefractionPostProcess = (function (_super) {
  38466. __extends(RefractionPostProcess, _super);
  38467. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  38468. var _this = this;
  38469. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  38470. this.color = color;
  38471. this.depth = depth;
  38472. this.colorLevel = colorLevel;
  38473. this.onActivate = function (cam) {
  38474. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  38475. };
  38476. this.onApply = function (effect) {
  38477. effect.setColor3("baseColor", _this.color);
  38478. effect.setFloat("depth", _this.depth);
  38479. effect.setFloat("colorLevel", _this.colorLevel);
  38480. effect.setTexture("refractionSampler", _this._refRexture);
  38481. };
  38482. }
  38483. // Methods
  38484. RefractionPostProcess.prototype.dispose = function (camera) {
  38485. if (this._refRexture) {
  38486. this._refRexture.dispose();
  38487. }
  38488. _super.prototype.dispose.call(this, camera);
  38489. };
  38490. return RefractionPostProcess;
  38491. })(BABYLON.PostProcess);
  38492. BABYLON.RefractionPostProcess = RefractionPostProcess;
  38493. })(BABYLON || (BABYLON = {}));
  38494. var BABYLON;
  38495. (function (BABYLON) {
  38496. var BlackAndWhitePostProcess = (function (_super) {
  38497. __extends(BlackAndWhitePostProcess, _super);
  38498. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38499. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  38500. }
  38501. return BlackAndWhitePostProcess;
  38502. })(BABYLON.PostProcess);
  38503. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  38504. })(BABYLON || (BABYLON = {}));
  38505. var BABYLON;
  38506. (function (BABYLON) {
  38507. var ConvolutionPostProcess = (function (_super) {
  38508. __extends(ConvolutionPostProcess, _super);
  38509. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  38510. var _this = this;
  38511. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  38512. this.kernel = kernel;
  38513. this.onApply = function (effect) {
  38514. effect.setFloat2("screenSize", _this.width, _this.height);
  38515. effect.setArray("kernel", _this.kernel);
  38516. };
  38517. }
  38518. // Statics
  38519. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  38520. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  38521. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  38522. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  38523. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  38524. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  38525. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  38526. return ConvolutionPostProcess;
  38527. })(BABYLON.PostProcess);
  38528. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  38529. })(BABYLON || (BABYLON = {}));
  38530. var BABYLON;
  38531. (function (BABYLON) {
  38532. var FilterPostProcess = (function (_super) {
  38533. __extends(FilterPostProcess, _super);
  38534. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  38535. var _this = this;
  38536. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  38537. this.kernelMatrix = kernelMatrix;
  38538. this.onApply = function (effect) {
  38539. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  38540. };
  38541. }
  38542. return FilterPostProcess;
  38543. })(BABYLON.PostProcess);
  38544. BABYLON.FilterPostProcess = FilterPostProcess;
  38545. })(BABYLON || (BABYLON = {}));
  38546. var BABYLON;
  38547. (function (BABYLON) {
  38548. var FxaaPostProcess = (function (_super) {
  38549. __extends(FxaaPostProcess, _super);
  38550. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38551. var _this = this;
  38552. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  38553. this.onSizeChanged = function () {
  38554. _this.texelWidth = 1.0 / _this.width;
  38555. _this.texelHeight = 1.0 / _this.height;
  38556. };
  38557. this.onApply = function (effect) {
  38558. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  38559. };
  38560. }
  38561. return FxaaPostProcess;
  38562. })(BABYLON.PostProcess);
  38563. BABYLON.FxaaPostProcess = FxaaPostProcess;
  38564. })(BABYLON || (BABYLON = {}));
  38565. var BABYLON;
  38566. (function (BABYLON) {
  38567. var StereoscopicInterlacePostProcess = (function (_super) {
  38568. __extends(StereoscopicInterlacePostProcess, _super);
  38569. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  38570. var _this = this;
  38571. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  38572. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  38573. this.onSizeChanged = function () {
  38574. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  38575. };
  38576. this.onApply = function (effect) {
  38577. effect.setTextureFromPostProcess("camASampler", postProcessA);
  38578. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  38579. };
  38580. }
  38581. return StereoscopicInterlacePostProcess;
  38582. })(BABYLON.PostProcess);
  38583. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  38584. })(BABYLON || (BABYLON = {}));
  38585. var BABYLON;
  38586. (function (BABYLON) {
  38587. var LensFlare = (function () {
  38588. function LensFlare(size, position, color, imgUrl, system) {
  38589. this.size = size;
  38590. this.position = position;
  38591. this.dispose = function () {
  38592. if (this.texture) {
  38593. this.texture.dispose();
  38594. }
  38595. // Remove from scene
  38596. var index = this._system.lensFlares.indexOf(this);
  38597. this._system.lensFlares.splice(index, 1);
  38598. };
  38599. this.color = color || new BABYLON.Color3(1, 1, 1);
  38600. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  38601. this._system = system;
  38602. system.lensFlares.push(this);
  38603. }
  38604. return LensFlare;
  38605. })();
  38606. BABYLON.LensFlare = LensFlare;
  38607. })(BABYLON || (BABYLON = {}));
  38608. var BABYLON;
  38609. (function (BABYLON) {
  38610. var LensFlareSystem = (function () {
  38611. function LensFlareSystem(name, emitter, scene) {
  38612. this.name = name;
  38613. this.lensFlares = new Array();
  38614. this.borderLimit = 300;
  38615. this.layerMask = 0x0FFFFFFF;
  38616. this._vertexDeclaration = [2];
  38617. this._vertexStrideSize = 2 * 4;
  38618. this._isEnabled = true;
  38619. this._scene = scene;
  38620. this._emitter = emitter;
  38621. this.id = name;
  38622. scene.lensFlareSystems.push(this);
  38623. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  38624. // VBO
  38625. var vertices = [];
  38626. vertices.push(1, 1);
  38627. vertices.push(-1, 1);
  38628. vertices.push(-1, -1);
  38629. vertices.push(1, -1);
  38630. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  38631. // Indices
  38632. var indices = [];
  38633. indices.push(0);
  38634. indices.push(1);
  38635. indices.push(2);
  38636. indices.push(0);
  38637. indices.push(2);
  38638. indices.push(3);
  38639. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38640. // Effects
  38641. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  38642. }
  38643. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  38644. get: function () {
  38645. return this._isEnabled;
  38646. },
  38647. set: function (value) {
  38648. this._isEnabled = value;
  38649. },
  38650. enumerable: true,
  38651. configurable: true
  38652. });
  38653. LensFlareSystem.prototype.getScene = function () {
  38654. return this._scene;
  38655. };
  38656. LensFlareSystem.prototype.getEmitter = function () {
  38657. return this._emitter;
  38658. };
  38659. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  38660. this._emitter = newEmitter;
  38661. };
  38662. LensFlareSystem.prototype.getEmitterPosition = function () {
  38663. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  38664. };
  38665. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  38666. var position = this.getEmitterPosition();
  38667. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  38668. this._positionX = position.x;
  38669. this._positionY = position.y;
  38670. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  38671. if (position.z > 0) {
  38672. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  38673. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  38674. return true;
  38675. }
  38676. }
  38677. return false;
  38678. };
  38679. LensFlareSystem.prototype._isVisible = function () {
  38680. if (!this._isEnabled) {
  38681. return false;
  38682. }
  38683. var emitterPosition = this.getEmitterPosition();
  38684. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  38685. var distance = direction.length();
  38686. direction.normalize();
  38687. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  38688. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  38689. return !pickInfo.hit || pickInfo.distance > distance;
  38690. };
  38691. LensFlareSystem.prototype.render = function () {
  38692. if (!this._effect.isReady())
  38693. return false;
  38694. var engine = this._scene.getEngine();
  38695. var viewport = this._scene.activeCamera.viewport;
  38696. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  38697. // Position
  38698. if (!this.computeEffectivePosition(globalViewport)) {
  38699. return false;
  38700. }
  38701. // Visibility
  38702. if (!this._isVisible()) {
  38703. return false;
  38704. }
  38705. // Intensity
  38706. var awayX;
  38707. var awayY;
  38708. if (this._positionX < this.borderLimit + globalViewport.x) {
  38709. awayX = this.borderLimit + globalViewport.x - this._positionX;
  38710. }
  38711. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  38712. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  38713. }
  38714. else {
  38715. awayX = 0;
  38716. }
  38717. if (this._positionY < this.borderLimit + globalViewport.y) {
  38718. awayY = this.borderLimit + globalViewport.y - this._positionY;
  38719. }
  38720. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  38721. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  38722. }
  38723. else {
  38724. awayY = 0;
  38725. }
  38726. var away = (awayX > awayY) ? awayX : awayY;
  38727. if (away > this.borderLimit) {
  38728. away = this.borderLimit;
  38729. }
  38730. var intensity = 1.0 - (away / this.borderLimit);
  38731. if (intensity < 0) {
  38732. return false;
  38733. }
  38734. if (intensity > 1.0) {
  38735. intensity = 1.0;
  38736. }
  38737. // Position
  38738. var centerX = globalViewport.x + globalViewport.width / 2;
  38739. var centerY = globalViewport.y + globalViewport.height / 2;
  38740. var distX = centerX - this._positionX;
  38741. var distY = centerY - this._positionY;
  38742. // Effects
  38743. engine.enableEffect(this._effect);
  38744. engine.setState(false);
  38745. engine.setDepthBuffer(false);
  38746. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  38747. // VBOs
  38748. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  38749. // Flares
  38750. for (var index = 0; index < this.lensFlares.length; index++) {
  38751. var flare = this.lensFlares[index];
  38752. var x = centerX - (distX * flare.position);
  38753. var y = centerY - (distY * flare.position);
  38754. var cw = flare.size;
  38755. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  38756. var cx = 2 * (x / globalViewport.width) - 1.0;
  38757. var cy = 1.0 - 2 * (y / globalViewport.height);
  38758. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  38759. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  38760. // Texture
  38761. this._effect.setTexture("textureSampler", flare.texture);
  38762. // Color
  38763. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  38764. // Draw order
  38765. engine.draw(true, 0, 6);
  38766. }
  38767. engine.setDepthBuffer(true);
  38768. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38769. return true;
  38770. };
  38771. LensFlareSystem.prototype.dispose = function () {
  38772. if (this._vertexBuffer) {
  38773. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  38774. this._vertexBuffer = null;
  38775. }
  38776. if (this._indexBuffer) {
  38777. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38778. this._indexBuffer = null;
  38779. }
  38780. while (this.lensFlares.length) {
  38781. this.lensFlares[0].dispose();
  38782. }
  38783. // Remove from scene
  38784. var index = this._scene.lensFlareSystems.indexOf(this);
  38785. this._scene.lensFlareSystems.splice(index, 1);
  38786. };
  38787. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  38788. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  38789. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  38790. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  38791. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  38792. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  38793. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  38794. var parsedFlare = parsedLensFlareSystem.flares[index];
  38795. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  38796. }
  38797. return lensFlareSystem;
  38798. };
  38799. LensFlareSystem.prototype.serialize = function () {
  38800. var serializationObject = {};
  38801. serializationObject.id = this.id;
  38802. serializationObject.name = this.name;
  38803. serializationObject.emitterId = this.getEmitter().id;
  38804. serializationObject.borderLimit = this.borderLimit;
  38805. serializationObject.flares = [];
  38806. for (var index = 0; index < this.lensFlares.length; index++) {
  38807. var flare = this.lensFlares[index];
  38808. serializationObject.flares.push({
  38809. size: flare.size,
  38810. position: flare.position,
  38811. color: flare.color.asArray(),
  38812. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  38813. });
  38814. }
  38815. return serializationObject;
  38816. };
  38817. return LensFlareSystem;
  38818. })();
  38819. BABYLON.LensFlareSystem = LensFlareSystem;
  38820. })(BABYLON || (BABYLON = {}));
  38821. var BABYLON;
  38822. (function (BABYLON) {
  38823. // We're mainly based on the logic defined into the FreeCamera code
  38824. var DeviceOrientationCamera = (function (_super) {
  38825. __extends(DeviceOrientationCamera, _super);
  38826. //-- end properties for backward compatibility for inputs
  38827. function DeviceOrientationCamera(name, position, scene) {
  38828. _super.call(this, name, position, scene);
  38829. this.inputs.addDeviceOrientation();
  38830. }
  38831. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  38832. //-- Begin properties for backward compatibility for inputs
  38833. get: function () {
  38834. var gamepad = this.inputs.attached["deviceOrientation"];
  38835. if (gamepad)
  38836. return gamepad.angularSensibility;
  38837. },
  38838. set: function (value) {
  38839. var gamepad = this.inputs.attached["deviceOrientation"];
  38840. if (gamepad)
  38841. gamepad.angularSensibility = value;
  38842. },
  38843. enumerable: true,
  38844. configurable: true
  38845. });
  38846. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  38847. get: function () {
  38848. var gamepad = this.inputs.attached["deviceOrientation"];
  38849. if (gamepad)
  38850. return gamepad.moveSensibility;
  38851. },
  38852. set: function (value) {
  38853. var gamepad = this.inputs.attached["deviceOrientation"];
  38854. if (gamepad)
  38855. gamepad.moveSensibility = value;
  38856. },
  38857. enumerable: true,
  38858. configurable: true
  38859. });
  38860. DeviceOrientationCamera.prototype.getTypeName = function () {
  38861. return "DeviceOrientationCamera";
  38862. };
  38863. return DeviceOrientationCamera;
  38864. })(BABYLON.FreeCamera);
  38865. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  38866. })(BABYLON || (BABYLON = {}));
  38867. var BABYLON;
  38868. (function (BABYLON) {
  38869. // We're mainly based on the logic defined into the FreeCamera code
  38870. var UniversalCamera = (function (_super) {
  38871. __extends(UniversalCamera, _super);
  38872. //-- end properties for backward compatibility for inputs
  38873. function UniversalCamera(name, position, scene) {
  38874. _super.call(this, name, position, scene);
  38875. this.inputs.addGamepad();
  38876. }
  38877. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  38878. //-- Begin properties for backward compatibility for inputs
  38879. get: function () {
  38880. var gamepad = this.inputs.attached["gamepad"];
  38881. if (gamepad)
  38882. return gamepad.gamepadAngularSensibility;
  38883. },
  38884. set: function (value) {
  38885. var gamepad = this.inputs.attached["gamepad"];
  38886. if (gamepad)
  38887. gamepad.gamepadAngularSensibility = value;
  38888. },
  38889. enumerable: true,
  38890. configurable: true
  38891. });
  38892. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  38893. get: function () {
  38894. var gamepad = this.inputs.attached["gamepad"];
  38895. if (gamepad)
  38896. return gamepad.gamepadMoveSensibility;
  38897. },
  38898. set: function (value) {
  38899. var gamepad = this.inputs.attached["gamepad"];
  38900. if (gamepad)
  38901. gamepad.gamepadMoveSensibility = value;
  38902. },
  38903. enumerable: true,
  38904. configurable: true
  38905. });
  38906. UniversalCamera.prototype.getTypeName = function () {
  38907. return "UniversalCamera";
  38908. };
  38909. return UniversalCamera;
  38910. })(BABYLON.TouchCamera);
  38911. BABYLON.UniversalCamera = UniversalCamera;
  38912. })(BABYLON || (BABYLON = {}));
  38913. var BABYLON;
  38914. (function (BABYLON) {
  38915. var Gamepads = (function () {
  38916. function Gamepads(ongamedpadconnected) {
  38917. var _this = this;
  38918. this.babylonGamepads = [];
  38919. this.oneGamepadConnected = false;
  38920. this.isMonitoring = false;
  38921. this.gamepadEventSupported = 'GamepadEvent' in window;
  38922. this.gamepadSupportAvailable = (navigator.getGamepads ||
  38923. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  38924. this._callbackGamepadConnected = ongamedpadconnected;
  38925. if (this.gamepadSupportAvailable) {
  38926. // Checking if the gamepad connected event is supported (like in Firefox)
  38927. if (this.gamepadEventSupported) {
  38928. this._onGamepadConnectedEvent = function (evt) {
  38929. _this._onGamepadConnected(evt);
  38930. };
  38931. this._onGamepadDisonnectedEvent = function (evt) {
  38932. _this._onGamepadDisconnected(evt);
  38933. };
  38934. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  38935. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  38936. }
  38937. else {
  38938. this._startMonitoringGamepads();
  38939. }
  38940. }
  38941. }
  38942. Gamepads.prototype.dispose = function () {
  38943. if (Gamepads.gamepadDOMInfo) {
  38944. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38945. }
  38946. if (this._onGamepadConnectedEvent) {
  38947. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  38948. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  38949. this._onGamepadConnectedEvent = null;
  38950. this._onGamepadDisonnectedEvent = null;
  38951. }
  38952. };
  38953. Gamepads.prototype._onGamepadConnected = function (evt) {
  38954. var newGamepad = this._addNewGamepad(evt.gamepad);
  38955. if (this._callbackGamepadConnected)
  38956. this._callbackGamepadConnected(newGamepad);
  38957. this._startMonitoringGamepads();
  38958. };
  38959. Gamepads.prototype._addNewGamepad = function (gamepad) {
  38960. if (!this.oneGamepadConnected) {
  38961. this.oneGamepadConnected = true;
  38962. if (Gamepads.gamepadDOMInfo) {
  38963. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38964. Gamepads.gamepadDOMInfo = null;
  38965. }
  38966. }
  38967. var newGamepad;
  38968. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  38969. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  38970. }
  38971. else {
  38972. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  38973. }
  38974. this.babylonGamepads.push(newGamepad);
  38975. return newGamepad;
  38976. };
  38977. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  38978. // Remove the gamepad from the list of gamepads to monitor.
  38979. for (var i in this.babylonGamepads) {
  38980. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  38981. this.babylonGamepads.splice(+i, 1);
  38982. break;
  38983. }
  38984. }
  38985. // If no gamepads are left, stop the polling loop.
  38986. if (this.babylonGamepads.length == 0) {
  38987. this._stopMonitoringGamepads();
  38988. }
  38989. };
  38990. Gamepads.prototype._startMonitoringGamepads = function () {
  38991. if (!this.isMonitoring) {
  38992. this.isMonitoring = true;
  38993. this._checkGamepadsStatus();
  38994. }
  38995. };
  38996. Gamepads.prototype._stopMonitoringGamepads = function () {
  38997. this.isMonitoring = false;
  38998. };
  38999. Gamepads.prototype._checkGamepadsStatus = function () {
  39000. var _this = this;
  39001. // updating gamepad objects
  39002. this._updateGamepadObjects();
  39003. for (var i in this.babylonGamepads) {
  39004. this.babylonGamepads[i].update();
  39005. }
  39006. if (this.isMonitoring) {
  39007. if (window.requestAnimationFrame) {
  39008. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39009. }
  39010. else if (window.mozRequestAnimationFrame) {
  39011. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39012. }
  39013. else if (window.webkitRequestAnimationFrame) {
  39014. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39015. }
  39016. }
  39017. };
  39018. // This function is called only on Chrome, which does not yet support
  39019. // connection/disconnection events, but requires you to monitor
  39020. // an array for changes.
  39021. Gamepads.prototype._updateGamepadObjects = function () {
  39022. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  39023. for (var i = 0; i < gamepads.length; i++) {
  39024. if (gamepads[i]) {
  39025. if (!(gamepads[i].index in this.babylonGamepads)) {
  39026. var newGamepad = this._addNewGamepad(gamepads[i]);
  39027. if (this._callbackGamepadConnected) {
  39028. this._callbackGamepadConnected(newGamepad);
  39029. }
  39030. }
  39031. else {
  39032. this.babylonGamepads[i].browserGamepad = gamepads[i];
  39033. }
  39034. }
  39035. }
  39036. };
  39037. return Gamepads;
  39038. })();
  39039. BABYLON.Gamepads = Gamepads;
  39040. var StickValues = (function () {
  39041. function StickValues(x, y) {
  39042. this.x = x;
  39043. this.y = y;
  39044. }
  39045. return StickValues;
  39046. })();
  39047. BABYLON.StickValues = StickValues;
  39048. var Gamepad = (function () {
  39049. function Gamepad(id, index, browserGamepad) {
  39050. this.id = id;
  39051. this.index = index;
  39052. this.browserGamepad = browserGamepad;
  39053. if (this.browserGamepad.axes.length >= 2) {
  39054. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  39055. }
  39056. if (this.browserGamepad.axes.length >= 4) {
  39057. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  39058. }
  39059. }
  39060. Gamepad.prototype.onleftstickchanged = function (callback) {
  39061. this._onleftstickchanged = callback;
  39062. };
  39063. Gamepad.prototype.onrightstickchanged = function (callback) {
  39064. this._onrightstickchanged = callback;
  39065. };
  39066. Object.defineProperty(Gamepad.prototype, "leftStick", {
  39067. get: function () {
  39068. return this._leftStick;
  39069. },
  39070. set: function (newValues) {
  39071. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  39072. this._onleftstickchanged(newValues);
  39073. }
  39074. this._leftStick = newValues;
  39075. },
  39076. enumerable: true,
  39077. configurable: true
  39078. });
  39079. Object.defineProperty(Gamepad.prototype, "rightStick", {
  39080. get: function () {
  39081. return this._rightStick;
  39082. },
  39083. set: function (newValues) {
  39084. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  39085. this._onrightstickchanged(newValues);
  39086. }
  39087. this._rightStick = newValues;
  39088. },
  39089. enumerable: true,
  39090. configurable: true
  39091. });
  39092. Gamepad.prototype.update = function () {
  39093. if (this._leftStick) {
  39094. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  39095. }
  39096. if (this._rightStick) {
  39097. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  39098. }
  39099. };
  39100. return Gamepad;
  39101. })();
  39102. BABYLON.Gamepad = Gamepad;
  39103. var GenericPad = (function (_super) {
  39104. __extends(GenericPad, _super);
  39105. function GenericPad(id, index, gamepad) {
  39106. _super.call(this, id, index, gamepad);
  39107. this.id = id;
  39108. this.index = index;
  39109. this.gamepad = gamepad;
  39110. this._buttons = new Array(gamepad.buttons.length);
  39111. }
  39112. GenericPad.prototype.onbuttondown = function (callback) {
  39113. this._onbuttondown = callback;
  39114. };
  39115. GenericPad.prototype.onbuttonup = function (callback) {
  39116. this._onbuttonup = callback;
  39117. };
  39118. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  39119. if (newValue !== currentValue) {
  39120. if (this._onbuttondown && newValue === 1) {
  39121. this._onbuttondown(buttonIndex);
  39122. }
  39123. if (this._onbuttonup && newValue === 0) {
  39124. this._onbuttonup(buttonIndex);
  39125. }
  39126. }
  39127. return newValue;
  39128. };
  39129. GenericPad.prototype.update = function () {
  39130. _super.prototype.update.call(this);
  39131. for (var index = 0; index < this._buttons.length; index++) {
  39132. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  39133. }
  39134. };
  39135. return GenericPad;
  39136. })(Gamepad);
  39137. BABYLON.GenericPad = GenericPad;
  39138. (function (Xbox360Button) {
  39139. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  39140. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  39141. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  39142. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  39143. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  39144. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  39145. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  39146. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  39147. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  39148. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  39149. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  39150. var Xbox360Button = BABYLON.Xbox360Button;
  39151. (function (Xbox360Dpad) {
  39152. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  39153. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  39154. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  39155. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  39156. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  39157. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  39158. var Xbox360Pad = (function (_super) {
  39159. __extends(Xbox360Pad, _super);
  39160. function Xbox360Pad() {
  39161. _super.apply(this, arguments);
  39162. this._leftTrigger = 0;
  39163. this._rightTrigger = 0;
  39164. this._buttonA = 0;
  39165. this._buttonB = 0;
  39166. this._buttonX = 0;
  39167. this._buttonY = 0;
  39168. this._buttonBack = 0;
  39169. this._buttonStart = 0;
  39170. this._buttonLB = 0;
  39171. this._buttonRB = 0;
  39172. this._buttonLeftStick = 0;
  39173. this._buttonRightStick = 0;
  39174. this._dPadUp = 0;
  39175. this._dPadDown = 0;
  39176. this._dPadLeft = 0;
  39177. this._dPadRight = 0;
  39178. }
  39179. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  39180. this._onlefttriggerchanged = callback;
  39181. };
  39182. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  39183. this._onrighttriggerchanged = callback;
  39184. };
  39185. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  39186. get: function () {
  39187. return this._leftTrigger;
  39188. },
  39189. set: function (newValue) {
  39190. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  39191. this._onlefttriggerchanged(newValue);
  39192. }
  39193. this._leftTrigger = newValue;
  39194. },
  39195. enumerable: true,
  39196. configurable: true
  39197. });
  39198. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  39199. get: function () {
  39200. return this._rightTrigger;
  39201. },
  39202. set: function (newValue) {
  39203. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  39204. this._onrighttriggerchanged(newValue);
  39205. }
  39206. this._rightTrigger = newValue;
  39207. },
  39208. enumerable: true,
  39209. configurable: true
  39210. });
  39211. Xbox360Pad.prototype.onbuttondown = function (callback) {
  39212. this._onbuttondown = callback;
  39213. };
  39214. Xbox360Pad.prototype.onbuttonup = function (callback) {
  39215. this._onbuttonup = callback;
  39216. };
  39217. Xbox360Pad.prototype.ondpaddown = function (callback) {
  39218. this._ondpaddown = callback;
  39219. };
  39220. Xbox360Pad.prototype.ondpadup = function (callback) {
  39221. this._ondpadup = callback;
  39222. };
  39223. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  39224. if (newValue !== currentValue) {
  39225. if (this._onbuttondown && newValue === 1) {
  39226. this._onbuttondown(buttonType);
  39227. }
  39228. if (this._onbuttonup && newValue === 0) {
  39229. this._onbuttonup(buttonType);
  39230. }
  39231. }
  39232. return newValue;
  39233. };
  39234. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  39235. if (newValue !== currentValue) {
  39236. if (this._ondpaddown && newValue === 1) {
  39237. this._ondpaddown(buttonType);
  39238. }
  39239. if (this._ondpadup && newValue === 0) {
  39240. this._ondpadup(buttonType);
  39241. }
  39242. }
  39243. return newValue;
  39244. };
  39245. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  39246. get: function () {
  39247. return this._buttonA;
  39248. },
  39249. set: function (value) {
  39250. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  39251. },
  39252. enumerable: true,
  39253. configurable: true
  39254. });
  39255. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  39256. get: function () {
  39257. return this._buttonB;
  39258. },
  39259. set: function (value) {
  39260. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  39261. },
  39262. enumerable: true,
  39263. configurable: true
  39264. });
  39265. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  39266. get: function () {
  39267. return this._buttonX;
  39268. },
  39269. set: function (value) {
  39270. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  39271. },
  39272. enumerable: true,
  39273. configurable: true
  39274. });
  39275. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  39276. get: function () {
  39277. return this._buttonY;
  39278. },
  39279. set: function (value) {
  39280. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  39281. },
  39282. enumerable: true,
  39283. configurable: true
  39284. });
  39285. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  39286. get: function () {
  39287. return this._buttonStart;
  39288. },
  39289. set: function (value) {
  39290. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  39291. },
  39292. enumerable: true,
  39293. configurable: true
  39294. });
  39295. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  39296. get: function () {
  39297. return this._buttonBack;
  39298. },
  39299. set: function (value) {
  39300. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  39301. },
  39302. enumerable: true,
  39303. configurable: true
  39304. });
  39305. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  39306. get: function () {
  39307. return this._buttonLB;
  39308. },
  39309. set: function (value) {
  39310. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  39311. },
  39312. enumerable: true,
  39313. configurable: true
  39314. });
  39315. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  39316. get: function () {
  39317. return this._buttonRB;
  39318. },
  39319. set: function (value) {
  39320. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  39321. },
  39322. enumerable: true,
  39323. configurable: true
  39324. });
  39325. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  39326. get: function () {
  39327. return this._buttonLeftStick;
  39328. },
  39329. set: function (value) {
  39330. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  39331. },
  39332. enumerable: true,
  39333. configurable: true
  39334. });
  39335. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  39336. get: function () {
  39337. return this._buttonRightStick;
  39338. },
  39339. set: function (value) {
  39340. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  39341. },
  39342. enumerable: true,
  39343. configurable: true
  39344. });
  39345. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  39346. get: function () {
  39347. return this._dPadUp;
  39348. },
  39349. set: function (value) {
  39350. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  39351. },
  39352. enumerable: true,
  39353. configurable: true
  39354. });
  39355. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  39356. get: function () {
  39357. return this._dPadDown;
  39358. },
  39359. set: function (value) {
  39360. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  39361. },
  39362. enumerable: true,
  39363. configurable: true
  39364. });
  39365. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  39366. get: function () {
  39367. return this._dPadLeft;
  39368. },
  39369. set: function (value) {
  39370. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  39371. },
  39372. enumerable: true,
  39373. configurable: true
  39374. });
  39375. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  39376. get: function () {
  39377. return this._dPadRight;
  39378. },
  39379. set: function (value) {
  39380. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  39381. },
  39382. enumerable: true,
  39383. configurable: true
  39384. });
  39385. Xbox360Pad.prototype.update = function () {
  39386. _super.prototype.update.call(this);
  39387. this.buttonA = this.browserGamepad.buttons[0].value;
  39388. this.buttonB = this.browserGamepad.buttons[1].value;
  39389. this.buttonX = this.browserGamepad.buttons[2].value;
  39390. this.buttonY = this.browserGamepad.buttons[3].value;
  39391. this.buttonLB = this.browserGamepad.buttons[4].value;
  39392. this.buttonRB = this.browserGamepad.buttons[5].value;
  39393. this.leftTrigger = this.browserGamepad.buttons[6].value;
  39394. this.rightTrigger = this.browserGamepad.buttons[7].value;
  39395. this.buttonBack = this.browserGamepad.buttons[8].value;
  39396. this.buttonStart = this.browserGamepad.buttons[9].value;
  39397. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  39398. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  39399. this.dPadUp = this.browserGamepad.buttons[12].value;
  39400. this.dPadDown = this.browserGamepad.buttons[13].value;
  39401. this.dPadLeft = this.browserGamepad.buttons[14].value;
  39402. this.dPadRight = this.browserGamepad.buttons[15].value;
  39403. };
  39404. return Xbox360Pad;
  39405. })(Gamepad);
  39406. BABYLON.Xbox360Pad = Xbox360Pad;
  39407. })(BABYLON || (BABYLON = {}));
  39408. var BABYLON;
  39409. (function (BABYLON) {
  39410. // We're mainly based on the logic defined into the FreeCamera code
  39411. var GamepadCamera = (function (_super) {
  39412. __extends(GamepadCamera, _super);
  39413. //-- end properties for backward compatibility for inputs
  39414. function GamepadCamera(name, position, scene) {
  39415. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  39416. _super.call(this, name, position, scene);
  39417. }
  39418. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  39419. //-- Begin properties for backward compatibility for inputs
  39420. get: function () {
  39421. var gamepad = this.inputs.attached["gamepad"];
  39422. if (gamepad)
  39423. return gamepad.gamepadAngularSensibility;
  39424. },
  39425. set: function (value) {
  39426. var gamepad = this.inputs.attached["gamepad"];
  39427. if (gamepad)
  39428. gamepad.gamepadAngularSensibility = value;
  39429. },
  39430. enumerable: true,
  39431. configurable: true
  39432. });
  39433. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  39434. get: function () {
  39435. var gamepad = this.inputs.attached["gamepad"];
  39436. if (gamepad)
  39437. return gamepad.gamepadMoveSensibility;
  39438. },
  39439. set: function (value) {
  39440. var gamepad = this.inputs.attached["gamepad"];
  39441. if (gamepad)
  39442. gamepad.gamepadMoveSensibility = value;
  39443. },
  39444. enumerable: true,
  39445. configurable: true
  39446. });
  39447. GamepadCamera.prototype.getTypeName = function () {
  39448. return "GamepadCamera";
  39449. };
  39450. return GamepadCamera;
  39451. })(BABYLON.UniversalCamera);
  39452. BABYLON.GamepadCamera = GamepadCamera;
  39453. })(BABYLON || (BABYLON = {}));
  39454. var BABYLON;
  39455. (function (BABYLON) {
  39456. var Analyser = (function () {
  39457. function Analyser(scene) {
  39458. this.SMOOTHING = 0.75;
  39459. this.FFT_SIZE = 512;
  39460. this.BARGRAPHAMPLITUDE = 256;
  39461. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  39462. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  39463. this._scene = scene;
  39464. this._audioEngine = BABYLON.Engine.audioEngine;
  39465. if (this._audioEngine.canUseWebAudio) {
  39466. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  39467. this._webAudioAnalyser.minDecibels = -140;
  39468. this._webAudioAnalyser.maxDecibels = 0;
  39469. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39470. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39471. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  39472. }
  39473. }
  39474. Analyser.prototype.getFrequencyBinCount = function () {
  39475. if (this._audioEngine.canUseWebAudio) {
  39476. return this._webAudioAnalyser.frequencyBinCount;
  39477. }
  39478. else {
  39479. return 0;
  39480. }
  39481. };
  39482. Analyser.prototype.getByteFrequencyData = function () {
  39483. if (this._audioEngine.canUseWebAudio) {
  39484. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39485. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39486. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  39487. }
  39488. return this._byteFreqs;
  39489. };
  39490. Analyser.prototype.getByteTimeDomainData = function () {
  39491. if (this._audioEngine.canUseWebAudio) {
  39492. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39493. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39494. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  39495. }
  39496. return this._byteTime;
  39497. };
  39498. Analyser.prototype.getFloatFrequencyData = function () {
  39499. if (this._audioEngine.canUseWebAudio) {
  39500. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39501. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39502. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  39503. }
  39504. return this._floatFreqs;
  39505. };
  39506. Analyser.prototype.drawDebugCanvas = function () {
  39507. var _this = this;
  39508. if (this._audioEngine.canUseWebAudio) {
  39509. if (!this._debugCanvas) {
  39510. this._debugCanvas = document.createElement("canvas");
  39511. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  39512. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  39513. this._debugCanvas.style.position = "absolute";
  39514. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  39515. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  39516. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  39517. document.body.appendChild(this._debugCanvas);
  39518. this._registerFunc = function () {
  39519. _this.drawDebugCanvas();
  39520. };
  39521. this._scene.registerBeforeRender(this._registerFunc);
  39522. }
  39523. if (this._registerFunc) {
  39524. var workingArray = this.getByteFrequencyData();
  39525. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  39526. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  39527. // Draw the frequency domain chart.
  39528. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  39529. var value = workingArray[i];
  39530. var percent = value / this.BARGRAPHAMPLITUDE;
  39531. var height = this.DEBUGCANVASSIZE.height * percent;
  39532. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  39533. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  39534. var hue = i / this.getFrequencyBinCount() * 360;
  39535. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  39536. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  39537. }
  39538. }
  39539. }
  39540. };
  39541. Analyser.prototype.stopDebugCanvas = function () {
  39542. if (this._debugCanvas) {
  39543. this._scene.unregisterBeforeRender(this._registerFunc);
  39544. this._registerFunc = null;
  39545. document.body.removeChild(this._debugCanvas);
  39546. this._debugCanvas = null;
  39547. this._debugCanvasContext = null;
  39548. }
  39549. };
  39550. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  39551. if (this._audioEngine.canUseWebAudio) {
  39552. inputAudioNode.connect(this._webAudioAnalyser);
  39553. this._webAudioAnalyser.connect(outputAudioNode);
  39554. }
  39555. };
  39556. Analyser.prototype.dispose = function () {
  39557. if (this._audioEngine.canUseWebAudio) {
  39558. this._webAudioAnalyser.disconnect();
  39559. }
  39560. };
  39561. return Analyser;
  39562. })();
  39563. BABYLON.Analyser = Analyser;
  39564. })(BABYLON || (BABYLON = {}));
  39565. var BABYLON;
  39566. (function (BABYLON) {
  39567. var DepthRenderer = (function () {
  39568. function DepthRenderer(scene, type) {
  39569. var _this = this;
  39570. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  39571. this._viewMatrix = BABYLON.Matrix.Zero();
  39572. this._projectionMatrix = BABYLON.Matrix.Zero();
  39573. this._transformMatrix = BABYLON.Matrix.Zero();
  39574. this._worldViewProjection = BABYLON.Matrix.Zero();
  39575. this._scene = scene;
  39576. var engine = scene.getEngine();
  39577. // Render target
  39578. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  39579. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39580. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39581. this._depthMap.refreshRate = 1;
  39582. this._depthMap.renderParticles = false;
  39583. this._depthMap.renderList = null;
  39584. // set default depth value to 1.0 (far away)
  39585. this._depthMap.onClear = function (engine) {
  39586. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  39587. };
  39588. // Custom render function
  39589. var renderSubMesh = function (subMesh) {
  39590. var mesh = subMesh.getRenderingMesh();
  39591. var scene = _this._scene;
  39592. var engine = scene.getEngine();
  39593. // Culling
  39594. engine.setState(subMesh.getMaterial().backFaceCulling);
  39595. // Managing instances
  39596. var batch = mesh._getInstancesRenderList(subMesh._id);
  39597. if (batch.mustReturn) {
  39598. return;
  39599. }
  39600. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  39601. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  39602. engine.enableEffect(_this._effect);
  39603. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  39604. var material = subMesh.getMaterial();
  39605. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  39606. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  39607. // Alpha test
  39608. if (material && material.needAlphaTesting()) {
  39609. var alphaTexture = material.getAlphaTestTexture();
  39610. _this._effect.setTexture("diffuseSampler", alphaTexture);
  39611. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39612. }
  39613. // Bones
  39614. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39615. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39616. }
  39617. // Draw
  39618. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  39619. }
  39620. };
  39621. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  39622. var index;
  39623. for (index = 0; index < opaqueSubMeshes.length; index++) {
  39624. renderSubMesh(opaqueSubMeshes.data[index]);
  39625. }
  39626. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  39627. renderSubMesh(alphaTestSubMeshes.data[index]);
  39628. }
  39629. };
  39630. }
  39631. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  39632. var material = subMesh.getMaterial();
  39633. if (material.disableDepthWrite) {
  39634. return false;
  39635. }
  39636. var defines = [];
  39637. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39638. var mesh = subMesh.getMesh();
  39639. var scene = mesh.getScene();
  39640. // Alpha test
  39641. if (material && material.needAlphaTesting()) {
  39642. defines.push("#define ALPHATEST");
  39643. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39644. attribs.push(BABYLON.VertexBuffer.UVKind);
  39645. defines.push("#define UV1");
  39646. }
  39647. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39648. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39649. defines.push("#define UV2");
  39650. }
  39651. }
  39652. // Bones
  39653. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39654. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39655. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39656. if (mesh.numBoneInfluencers > 4) {
  39657. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39658. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39659. }
  39660. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39661. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39662. }
  39663. else {
  39664. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39665. }
  39666. // Instances
  39667. if (useInstances) {
  39668. defines.push("#define INSTANCES");
  39669. attribs.push("world0");
  39670. attribs.push("world1");
  39671. attribs.push("world2");
  39672. attribs.push("world3");
  39673. }
  39674. // Get correct effect
  39675. var join = defines.join("\n");
  39676. if (this._cachedDefines !== join) {
  39677. this._cachedDefines = join;
  39678. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  39679. }
  39680. return this._effect.isReady();
  39681. };
  39682. DepthRenderer.prototype.getDepthMap = function () {
  39683. return this._depthMap;
  39684. };
  39685. // Methods
  39686. DepthRenderer.prototype.dispose = function () {
  39687. this._depthMap.dispose();
  39688. };
  39689. return DepthRenderer;
  39690. })();
  39691. BABYLON.DepthRenderer = DepthRenderer;
  39692. })(BABYLON || (BABYLON = {}));
  39693. var BABYLON;
  39694. (function (BABYLON) {
  39695. var SSAORenderingPipeline = (function (_super) {
  39696. __extends(SSAORenderingPipeline, _super);
  39697. /**
  39698. * @constructor
  39699. * @param {string} name - The rendering pipeline name
  39700. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39701. * @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 }
  39702. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39703. */
  39704. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  39705. var _this = this;
  39706. _super.call(this, scene.getEngine(), name);
  39707. // Members
  39708. /**
  39709. * The PassPostProcess id in the pipeline that contains the original scene color
  39710. * @type {string}
  39711. */
  39712. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  39713. /**
  39714. * The SSAO PostProcess id in the pipeline
  39715. * @type {string}
  39716. */
  39717. this.SSAORenderEffect = "SSAORenderEffect";
  39718. /**
  39719. * The horizontal blur PostProcess id in the pipeline
  39720. * @type {string}
  39721. */
  39722. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  39723. /**
  39724. * The vertical blur PostProcess id in the pipeline
  39725. * @type {string}
  39726. */
  39727. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  39728. /**
  39729. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  39730. * @type {string}
  39731. */
  39732. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  39733. /**
  39734. * The output strength of the SSAO post-process. Default value is 1.0.
  39735. * @type {number}
  39736. */
  39737. this.totalStrength = 1.0;
  39738. /**
  39739. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  39740. * @type {number}
  39741. */
  39742. this.radius = 0.0001;
  39743. /**
  39744. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  39745. * Must not be equal to fallOff and superior to fallOff.
  39746. * Default value is 0.975
  39747. * @type {number}
  39748. */
  39749. this.area = 0.0075;
  39750. /**
  39751. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  39752. * Must not be equal to area and inferior to area.
  39753. * Default value is 0.0
  39754. * @type {number}
  39755. */
  39756. this.fallOff = 0.000001;
  39757. /**
  39758. * The base color of the SSAO post-process
  39759. * The final result is "base + ssao" between [0, 1]
  39760. * @type {number}
  39761. */
  39762. this.base = 0.5;
  39763. this._firstUpdate = true;
  39764. this._scene = scene;
  39765. // Set up assets
  39766. this._createRandomTexture();
  39767. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  39768. var ssaoRatio = ratio.ssaoRatio || ratio;
  39769. var combineRatio = ratio.combineRatio || ratio;
  39770. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39771. this._createSSAOPostProcess(ssaoRatio);
  39772. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39773. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39774. this._createSSAOCombinePostProcess(combineRatio);
  39775. // Set up pipeline
  39776. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  39777. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  39778. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  39779. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  39780. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  39781. // Finish
  39782. scene.postProcessRenderPipelineManager.addPipeline(this);
  39783. if (cameras)
  39784. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  39785. }
  39786. // Public Methods
  39787. /**
  39788. * Returns the horizontal blur PostProcess
  39789. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  39790. */
  39791. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  39792. return this._blurHPostProcess;
  39793. };
  39794. /**
  39795. * Returns the vertical blur PostProcess
  39796. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  39797. */
  39798. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  39799. return this._blurVPostProcess;
  39800. };
  39801. /**
  39802. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  39803. */
  39804. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  39805. if (disableDepthRender === void 0) { disableDepthRender = false; }
  39806. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  39807. this._originalColorPostProcess = undefined;
  39808. this._ssaoPostProcess = undefined;
  39809. this._blurHPostProcess = undefined;
  39810. this._blurVPostProcess = undefined;
  39811. this._ssaoCombinePostProcess = undefined;
  39812. this._randomTexture.dispose();
  39813. if (disableDepthRender)
  39814. this._scene.disableDepthRenderer();
  39815. };
  39816. // Private Methods
  39817. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  39818. var _this = this;
  39819. var numSamples = 16;
  39820. var sampleSphere = [
  39821. 0.5381, 0.1856, -0.4319,
  39822. 0.1379, 0.2486, 0.4430,
  39823. 0.3371, 0.5679, -0.0057,
  39824. -0.6999, -0.0451, -0.0019,
  39825. 0.0689, -0.1598, -0.8547,
  39826. 0.0560, 0.0069, -0.1843,
  39827. -0.0146, 0.1402, 0.0762,
  39828. 0.0100, -0.1924, -0.0344,
  39829. -0.3577, -0.5301, -0.4358,
  39830. -0.3169, 0.1063, 0.0158,
  39831. 0.0103, -0.5869, 0.0046,
  39832. -0.0897, -0.4940, 0.3287,
  39833. 0.7119, -0.0154, -0.0918,
  39834. -0.0533, 0.0596, -0.5411,
  39835. 0.0352, -0.0631, 0.5460,
  39836. -0.4776, 0.2847, -0.0271
  39837. ];
  39838. var samplesFactor = 1.0 / numSamples;
  39839. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  39840. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  39841. "area", "fallOff", "base"
  39842. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  39843. this._ssaoPostProcess.onApply = function (effect) {
  39844. if (_this._firstUpdate) {
  39845. effect.setArray3("sampleSphere", sampleSphere);
  39846. effect.setFloat("samplesFactor", samplesFactor);
  39847. effect.setFloat("randTextureTiles", 4.0);
  39848. _this._firstUpdate = false;
  39849. }
  39850. effect.setFloat("totalStrength", _this.totalStrength);
  39851. effect.setFloat("radius", _this.radius);
  39852. effect.setFloat("area", _this.area);
  39853. effect.setFloat("fallOff", _this.fallOff);
  39854. effect.setFloat("base", _this.base);
  39855. effect.setTexture("textureSampler", _this._depthTexture);
  39856. effect.setTexture("randomSampler", _this._randomTexture);
  39857. };
  39858. };
  39859. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  39860. var _this = this;
  39861. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  39862. this._ssaoCombinePostProcess.onApply = function (effect) {
  39863. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  39864. };
  39865. };
  39866. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  39867. var size = 512;
  39868. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39869. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  39870. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  39871. var context = this._randomTexture.getContext();
  39872. var rand = function (min, max) {
  39873. return Math.random() * (max - min) + min;
  39874. };
  39875. var randVector = BABYLON.Vector3.Zero();
  39876. for (var x = 0; x < size; x++) {
  39877. for (var y = 0; y < size; y++) {
  39878. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  39879. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  39880. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  39881. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  39882. context.fillRect(x, y, 1, 1);
  39883. }
  39884. }
  39885. this._randomTexture.update(false);
  39886. };
  39887. return SSAORenderingPipeline;
  39888. })(BABYLON.PostProcessRenderPipeline);
  39889. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  39890. })(BABYLON || (BABYLON = {}));
  39891. var BABYLON;
  39892. (function (BABYLON) {
  39893. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  39894. var VolumetricLightScatteringPostProcess = (function (_super) {
  39895. __extends(VolumetricLightScatteringPostProcess, _super);
  39896. /**
  39897. * @constructor
  39898. * @param {string} name - The post-process name
  39899. * @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)
  39900. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  39901. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  39902. * @param {number} samples - The post-process quality, default 100
  39903. * @param {number} samplingMode - The post-process filtering mode
  39904. * @param {BABYLON.Engine} engine - The babylon engine
  39905. * @param {boolean} reusable - If the post-process is reusable
  39906. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  39907. */
  39908. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  39909. var _this = this;
  39910. if (samples === void 0) { samples = 100; }
  39911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39912. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  39913. this._screenCoordinates = BABYLON.Vector2.Zero();
  39914. /**
  39915. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  39916. * @type {Vector3}
  39917. */
  39918. this.customMeshPosition = BABYLON.Vector3.Zero();
  39919. /**
  39920. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  39921. * @type {boolean}
  39922. */
  39923. this.useCustomMeshPosition = false;
  39924. /**
  39925. * If the post-process should inverse the light scattering direction
  39926. * @type {boolean}
  39927. */
  39928. this.invert = true;
  39929. /**
  39930. * Array containing the excluded meshes not rendered in the internal pass
  39931. */
  39932. this.excludedMeshes = new Array();
  39933. /**
  39934. * Controls the overall intensity of the post-process
  39935. * @type {number}
  39936. */
  39937. this.exposure = 0.3;
  39938. /**
  39939. * Dissipates each sample's contribution in range [0, 1]
  39940. * @type {number}
  39941. */
  39942. this.decay = 0.96815;
  39943. /**
  39944. * Controls the overall intensity of each sample
  39945. * @type {number}
  39946. */
  39947. this.weight = 0.58767;
  39948. /**
  39949. * Controls the density of each sample
  39950. * @type {number}
  39951. */
  39952. this.density = 0.926;
  39953. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  39954. var engine = scene.getEngine();
  39955. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  39956. // Configure mesh
  39957. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  39958. // Configure
  39959. this._createPass(scene, ratio.passRatio || ratio);
  39960. this.onActivate = function (camera) {
  39961. if (!_this.isSupported) {
  39962. _this.dispose(camera);
  39963. }
  39964. _this.onActivate = null;
  39965. };
  39966. this.onApply = function (effect) {
  39967. _this._updateMeshScreenCoordinates(scene);
  39968. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  39969. effect.setFloat("exposure", _this.exposure);
  39970. effect.setFloat("decay", _this.decay);
  39971. effect.setFloat("weight", _this.weight);
  39972. effect.setFloat("density", _this.density);
  39973. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  39974. };
  39975. }
  39976. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  39977. get: function () {
  39978. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  39979. return false;
  39980. },
  39981. set: function (useDiffuseColor) {
  39982. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  39983. },
  39984. enumerable: true,
  39985. configurable: true
  39986. });
  39987. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  39988. var mesh = subMesh.getMesh();
  39989. // Render this.mesh as default
  39990. if (mesh === this.mesh) {
  39991. return mesh.material.isReady(mesh);
  39992. }
  39993. var defines = [];
  39994. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39995. var material = subMesh.getMaterial();
  39996. var needUV = false;
  39997. // Alpha test
  39998. if (material) {
  39999. if (material.needAlphaTesting()) {
  40000. defines.push("#define ALPHATEST");
  40001. }
  40002. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40003. attribs.push(BABYLON.VertexBuffer.UVKind);
  40004. defines.push("#define UV1");
  40005. }
  40006. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40007. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40008. defines.push("#define UV2");
  40009. }
  40010. }
  40011. // Bones
  40012. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40013. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40014. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40015. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40016. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40017. }
  40018. else {
  40019. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40020. }
  40021. // Instances
  40022. if (useInstances) {
  40023. defines.push("#define INSTANCES");
  40024. attribs.push("world0");
  40025. attribs.push("world1");
  40026. attribs.push("world2");
  40027. attribs.push("world3");
  40028. }
  40029. // Get correct effect
  40030. var join = defines.join("\n");
  40031. if (this._cachedDefines !== join) {
  40032. this._cachedDefines = join;
  40033. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  40034. }
  40035. return this._volumetricLightScatteringPass.isReady();
  40036. };
  40037. /**
  40038. * Sets the new light position for light scattering effect
  40039. * @param {BABYLON.Vector3} The new custom light position
  40040. */
  40041. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  40042. this.customMeshPosition = position;
  40043. };
  40044. /**
  40045. * Returns the light position for light scattering effect
  40046. * @return {BABYLON.Vector3} The custom light position
  40047. */
  40048. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  40049. return this.customMeshPosition;
  40050. };
  40051. /**
  40052. * Disposes the internal assets and detaches the post-process from the camera
  40053. */
  40054. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  40055. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  40056. if (rttIndex !== -1) {
  40057. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  40058. }
  40059. this._volumetricLightScatteringRTT.dispose();
  40060. _super.prototype.dispose.call(this, camera);
  40061. };
  40062. /**
  40063. * Returns the render target texture used by the post-process
  40064. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  40065. */
  40066. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  40067. return this._volumetricLightScatteringRTT;
  40068. };
  40069. // Private methods
  40070. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  40071. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  40072. return true;
  40073. }
  40074. return false;
  40075. };
  40076. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  40077. var _this = this;
  40078. var engine = scene.getEngine();
  40079. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  40080. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40081. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40082. this._volumetricLightScatteringRTT.renderList = null;
  40083. this._volumetricLightScatteringRTT.renderParticles = false;
  40084. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  40085. // Custom render function for submeshes
  40086. var renderSubMesh = function (subMesh) {
  40087. var mesh = subMesh.getRenderingMesh();
  40088. if (_this._meshExcluded(mesh)) {
  40089. return;
  40090. }
  40091. var scene = mesh.getScene();
  40092. var engine = scene.getEngine();
  40093. // Culling
  40094. engine.setState(subMesh.getMaterial().backFaceCulling);
  40095. // Managing instances
  40096. var batch = mesh._getInstancesRenderList(subMesh._id);
  40097. if (batch.mustReturn) {
  40098. return;
  40099. }
  40100. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  40101. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  40102. var effect = _this._volumetricLightScatteringPass;
  40103. if (mesh === _this.mesh) {
  40104. effect = subMesh.getMaterial().getEffect();
  40105. }
  40106. engine.enableEffect(effect);
  40107. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  40108. if (mesh === _this.mesh) {
  40109. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  40110. }
  40111. else {
  40112. var material = subMesh.getMaterial();
  40113. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  40114. // Alpha test
  40115. if (material && material.needAlphaTesting()) {
  40116. var alphaTexture = material.getAlphaTestTexture();
  40117. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  40118. if (alphaTexture) {
  40119. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  40120. }
  40121. }
  40122. // Bones
  40123. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40124. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  40125. }
  40126. }
  40127. // Draw
  40128. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  40129. }
  40130. };
  40131. // Render target texture callbacks
  40132. var savedSceneClearColor;
  40133. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  40134. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  40135. savedSceneClearColor = scene.clearColor;
  40136. scene.clearColor = sceneClearColor;
  40137. };
  40138. this._volumetricLightScatteringRTT.onAfterRender = function () {
  40139. scene.clearColor = savedSceneClearColor;
  40140. };
  40141. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  40142. var engine = scene.getEngine();
  40143. var index;
  40144. for (index = 0; index < opaqueSubMeshes.length; index++) {
  40145. renderSubMesh(opaqueSubMeshes.data[index]);
  40146. }
  40147. engine.setAlphaTesting(true);
  40148. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  40149. renderSubMesh(alphaTestSubMeshes.data[index]);
  40150. }
  40151. engine.setAlphaTesting(false);
  40152. if (transparentSubMeshes.length) {
  40153. // Sort sub meshes
  40154. for (index = 0; index < transparentSubMeshes.length; index++) {
  40155. var submesh = transparentSubMeshes.data[index];
  40156. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  40157. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  40158. }
  40159. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  40160. sortedArray.sort(function (a, b) {
  40161. // Alpha index first
  40162. if (a._alphaIndex > b._alphaIndex) {
  40163. return 1;
  40164. }
  40165. if (a._alphaIndex < b._alphaIndex) {
  40166. return -1;
  40167. }
  40168. // Then distance to camera
  40169. if (a._distanceToCamera < b._distanceToCamera) {
  40170. return 1;
  40171. }
  40172. if (a._distanceToCamera > b._distanceToCamera) {
  40173. return -1;
  40174. }
  40175. return 0;
  40176. });
  40177. // Render sub meshes
  40178. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40179. for (index = 0; index < sortedArray.length; index++) {
  40180. renderSubMesh(sortedArray[index]);
  40181. }
  40182. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40183. }
  40184. };
  40185. };
  40186. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  40187. var transform = scene.getTransformMatrix();
  40188. var meshPosition;
  40189. if (this.useCustomMeshPosition) {
  40190. meshPosition = this.customMeshPosition;
  40191. }
  40192. else if (this.attachedNode) {
  40193. meshPosition = this.attachedNode.position;
  40194. }
  40195. else {
  40196. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  40197. }
  40198. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  40199. this._screenCoordinates.x = pos.x / this._viewPort.width;
  40200. this._screenCoordinates.y = pos.y / this._viewPort.height;
  40201. if (this.invert)
  40202. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  40203. };
  40204. // Static methods
  40205. /**
  40206. * Creates a default mesh for the Volumeric Light Scattering post-process
  40207. * @param {string} The mesh name
  40208. * @param {BABYLON.Scene} The scene where to create the mesh
  40209. * @return {BABYLON.Mesh} the default mesh
  40210. */
  40211. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  40212. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  40213. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  40214. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  40215. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  40216. mesh.material = material;
  40217. return mesh;
  40218. };
  40219. __decorate([
  40220. BABYLON.serializeAsVector3()
  40221. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  40222. __decorate([
  40223. BABYLON.serialize()
  40224. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  40225. __decorate([
  40226. BABYLON.serialize()
  40227. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  40228. __decorate([
  40229. BABYLON.serializeAsMeshReference()
  40230. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  40231. __decorate([
  40232. BABYLON.serialize()
  40233. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  40234. __decorate([
  40235. BABYLON.serialize()
  40236. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  40237. __decorate([
  40238. BABYLON.serialize()
  40239. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  40240. __decorate([
  40241. BABYLON.serialize()
  40242. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  40243. __decorate([
  40244. BABYLON.serialize()
  40245. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  40246. return VolumetricLightScatteringPostProcess;
  40247. })(BABYLON.PostProcess);
  40248. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  40249. })(BABYLON || (BABYLON = {}));
  40250. // BABYLON.JS Chromatic Aberration GLSL Shader
  40251. // Author: Olivier Guyot
  40252. // Separates very slightly R, G and B colors on the edges of the screen
  40253. // Inspired by Francois Tarlier & Martins Upitis
  40254. var BABYLON;
  40255. (function (BABYLON) {
  40256. var LensRenderingPipeline = (function (_super) {
  40257. __extends(LensRenderingPipeline, _super);
  40258. /**
  40259. * @constructor
  40260. *
  40261. * Effect parameters are as follow:
  40262. * {
  40263. * chromatic_aberration: number; // from 0 to x (1 for realism)
  40264. * edge_blur: number; // from 0 to x (1 for realism)
  40265. * distortion: number; // from 0 to x (1 for realism)
  40266. * grain_amount: number; // from 0 to 1
  40267. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  40268. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  40269. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  40270. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  40271. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  40272. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  40273. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  40274. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  40275. * }
  40276. * Note: if an effect parameter is unset, effect is disabled
  40277. *
  40278. * @param {string} name - The rendering pipeline name
  40279. * @param {object} parameters - An object containing all parameters (see above)
  40280. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40281. * @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)
  40282. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40283. */
  40284. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  40285. var _this = this;
  40286. if (ratio === void 0) { ratio = 1.0; }
  40287. _super.call(this, scene.getEngine(), name);
  40288. // Lens effects can be of the following:
  40289. // - chromatic aberration (slight shift of RGB colors)
  40290. // - blur on the edge of the lens
  40291. // - lens distortion
  40292. // - depth-of-field blur & highlights enhancing
  40293. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  40294. // - grain effect (noise or custom texture)
  40295. // Two additional texture samplers are needed:
  40296. // - depth map (for depth-of-field)
  40297. // - grain texture
  40298. /**
  40299. * The chromatic aberration PostProcess id in the pipeline
  40300. * @type {string}
  40301. */
  40302. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  40303. /**
  40304. * The highlights enhancing PostProcess id in the pipeline
  40305. * @type {string}
  40306. */
  40307. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  40308. /**
  40309. * The depth-of-field PostProcess id in the pipeline
  40310. * @type {string}
  40311. */
  40312. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  40313. this._scene = scene;
  40314. // Fetch texture samplers
  40315. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  40316. if (parameters.grain_texture) {
  40317. this._grainTexture = parameters.grain_texture;
  40318. }
  40319. else {
  40320. this._createGrainTexture();
  40321. }
  40322. // save parameters
  40323. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  40324. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  40325. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  40326. this._distortion = parameters.distortion ? parameters.distortion : 0;
  40327. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  40328. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  40329. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  40330. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  40331. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  40332. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  40333. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  40334. // Create effects
  40335. this._createChromaticAberrationPostProcess(ratio);
  40336. this._createHighlightsPostProcess(ratio);
  40337. this._createDepthOfFieldPostProcess(ratio / 4);
  40338. // Set up pipeline
  40339. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  40340. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  40341. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  40342. if (this._highlightsGain === -1) {
  40343. this._disableEffect(this.HighlightsEnhancingEffect, null);
  40344. }
  40345. // Finish
  40346. scene.postProcessRenderPipelineManager.addPipeline(this);
  40347. if (cameras) {
  40348. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40349. }
  40350. }
  40351. // public methods (self explanatory)
  40352. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  40353. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  40354. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  40355. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  40356. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  40357. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  40358. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  40359. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  40360. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  40361. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  40362. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  40363. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  40364. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  40365. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  40366. };
  40367. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  40368. this._highlightsPostProcess.updateEffect();
  40369. };
  40370. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  40371. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  40372. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  40373. this._highlightsGain = amount;
  40374. };
  40375. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  40376. if (this._highlightsGain === -1) {
  40377. this._highlightsGain = 1.0;
  40378. }
  40379. this._highlightsThreshold = amount;
  40380. };
  40381. LensRenderingPipeline.prototype.disableHighlights = function () {
  40382. this._highlightsGain = -1;
  40383. };
  40384. /**
  40385. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  40386. */
  40387. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  40388. if (disableDepthRender === void 0) { disableDepthRender = false; }
  40389. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40390. this._chromaticAberrationPostProcess = undefined;
  40391. this._highlightsPostProcess = undefined;
  40392. this._depthOfFieldPostProcess = undefined;
  40393. this._grainTexture.dispose();
  40394. if (disableDepthRender)
  40395. this._scene.disableDepthRenderer();
  40396. };
  40397. // colors shifting and distortion
  40398. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  40399. var _this = this;
  40400. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  40401. [], // samplers
  40402. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40403. this._chromaticAberrationPostProcess.onApply = function (effect) {
  40404. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  40405. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40406. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40407. };
  40408. };
  40409. // highlights enhancing
  40410. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  40411. var _this = this;
  40412. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  40413. [], // samplers
  40414. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  40415. this._highlightsPostProcess.onApply = function (effect) {
  40416. effect.setFloat('gain', _this._highlightsGain);
  40417. effect.setFloat('threshold', _this._highlightsThreshold);
  40418. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  40419. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40420. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40421. };
  40422. };
  40423. // colors shifting and distortion
  40424. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  40425. var _this = this;
  40426. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  40427. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  40428. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  40429. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40430. this._depthOfFieldPostProcess.onApply = function (effect) {
  40431. effect.setTexture("depthSampler", _this._depthTexture);
  40432. effect.setTexture("grainSampler", _this._grainTexture);
  40433. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  40434. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  40435. effect.setFloat('grain_amount', _this._grainAmount);
  40436. effect.setBool('blur_noise', _this._blurNoise);
  40437. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40438. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40439. effect.setFloat('distortion', _this._distortion);
  40440. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  40441. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  40442. effect.setFloat('aperture', _this._dofAperture);
  40443. effect.setFloat('darken', _this._dofDarken);
  40444. effect.setFloat('edge_blur', _this._edgeBlur);
  40445. effect.setBool('highlights', (_this._highlightsGain !== -1));
  40446. effect.setFloat('near', _this._scene.activeCamera.minZ);
  40447. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  40448. };
  40449. };
  40450. // creates a black and white random noise texture, 512x512
  40451. LensRenderingPipeline.prototype._createGrainTexture = function () {
  40452. var size = 512;
  40453. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40454. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  40455. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  40456. var context = this._grainTexture.getContext();
  40457. var rand = function (min, max) {
  40458. return Math.random() * (max - min) + min;
  40459. };
  40460. var value;
  40461. for (var x = 0; x < size; x++) {
  40462. for (var y = 0; y < size; y++) {
  40463. value = Math.floor(rand(0.42, 0.58) * 255);
  40464. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  40465. context.fillRect(x, y, 1, 1);
  40466. }
  40467. }
  40468. this._grainTexture.update(false);
  40469. };
  40470. return LensRenderingPipeline;
  40471. })(BABYLON.PostProcessRenderPipeline);
  40472. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  40473. })(BABYLON || (BABYLON = {}));
  40474. //
  40475. // This post-process allows the modification of rendered colors by using
  40476. // a 'look-up table' (LUT). This effect is also called Color Grading.
  40477. //
  40478. // The object needs to be provided an url to a texture containing the color
  40479. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  40480. // Use an image editing software to tweak the LUT to match your needs.
  40481. //
  40482. // For an example of a color LUT, see here:
  40483. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  40484. // For explanations on color grading, see here:
  40485. // http://udn.epicgames.com/Three/ColorGrading.html
  40486. //
  40487. var BABYLON;
  40488. (function (BABYLON) {
  40489. var ColorCorrectionPostProcess = (function (_super) {
  40490. __extends(ColorCorrectionPostProcess, _super);
  40491. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  40492. var _this = this;
  40493. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  40494. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  40495. this._colorTableTexture.anisotropicFilteringLevel = 1;
  40496. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40497. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40498. this.onApply = function (effect) {
  40499. effect.setTexture("colorTable", _this._colorTableTexture);
  40500. };
  40501. }
  40502. return ColorCorrectionPostProcess;
  40503. })(BABYLON.PostProcess);
  40504. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  40505. })(BABYLON || (BABYLON = {}));
  40506. var BABYLON;
  40507. (function (BABYLON) {
  40508. var AnaglyphFreeCamera = (function (_super) {
  40509. __extends(AnaglyphFreeCamera, _super);
  40510. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  40511. _super.call(this, name, position, scene);
  40512. this.interaxialDistance = interaxialDistance;
  40513. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40514. }
  40515. AnaglyphFreeCamera.prototype.getTypeName = function () {
  40516. return "AnaglyphFreeCamera";
  40517. };
  40518. return AnaglyphFreeCamera;
  40519. })(BABYLON.FreeCamera);
  40520. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  40521. var AnaglyphArcRotateCamera = (function (_super) {
  40522. __extends(AnaglyphArcRotateCamera, _super);
  40523. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  40524. _super.call(this, name, alpha, beta, radius, target, scene);
  40525. this.interaxialDistance = interaxialDistance;
  40526. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40527. }
  40528. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  40529. return "AnaglyphArcRotateCamera";
  40530. };
  40531. return AnaglyphArcRotateCamera;
  40532. })(BABYLON.ArcRotateCamera);
  40533. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  40534. var AnaglyphGamepadCamera = (function (_super) {
  40535. __extends(AnaglyphGamepadCamera, _super);
  40536. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  40537. _super.call(this, name, position, scene);
  40538. this.interaxialDistance = interaxialDistance;
  40539. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40540. }
  40541. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  40542. return "AnaglyphGamepadCamera";
  40543. };
  40544. return AnaglyphGamepadCamera;
  40545. })(BABYLON.GamepadCamera);
  40546. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  40547. var AnaglyphUniversalCamera = (function (_super) {
  40548. __extends(AnaglyphUniversalCamera, _super);
  40549. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  40550. _super.call(this, name, position, scene);
  40551. this.interaxialDistance = interaxialDistance;
  40552. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40553. }
  40554. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  40555. return "AnaglyphUniversalCamera";
  40556. };
  40557. return AnaglyphUniversalCamera;
  40558. })(BABYLON.UniversalCamera);
  40559. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  40560. var StereoscopicFreeCamera = (function (_super) {
  40561. __extends(StereoscopicFreeCamera, _super);
  40562. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40563. _super.call(this, name, position, scene);
  40564. this.interaxialDistance = interaxialDistance;
  40565. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40566. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40567. }
  40568. StereoscopicFreeCamera.prototype.getTypeName = function () {
  40569. return "StereoscopicFreeCamera";
  40570. };
  40571. return StereoscopicFreeCamera;
  40572. })(BABYLON.FreeCamera);
  40573. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  40574. var StereoscopicArcRotateCamera = (function (_super) {
  40575. __extends(StereoscopicArcRotateCamera, _super);
  40576. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  40577. _super.call(this, name, alpha, beta, radius, target, scene);
  40578. this.interaxialDistance = interaxialDistance;
  40579. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40580. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40581. }
  40582. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  40583. return "StereoscopicArcRotateCamera";
  40584. };
  40585. return StereoscopicArcRotateCamera;
  40586. })(BABYLON.ArcRotateCamera);
  40587. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  40588. var StereoscopicGamepadCamera = (function (_super) {
  40589. __extends(StereoscopicGamepadCamera, _super);
  40590. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40591. _super.call(this, name, position, scene);
  40592. this.interaxialDistance = interaxialDistance;
  40593. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40594. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40595. }
  40596. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  40597. return "StereoscopicGamepadCamera";
  40598. };
  40599. return StereoscopicGamepadCamera;
  40600. })(BABYLON.GamepadCamera);
  40601. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  40602. var StereoscopicUniversalCamera = (function (_super) {
  40603. __extends(StereoscopicUniversalCamera, _super);
  40604. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40605. _super.call(this, name, position, scene);
  40606. this.interaxialDistance = interaxialDistance;
  40607. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40608. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40609. }
  40610. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  40611. return "StereoscopicUniversalCamera";
  40612. };
  40613. return StereoscopicUniversalCamera;
  40614. })(BABYLON.UniversalCamera);
  40615. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  40616. })(BABYLON || (BABYLON = {}));
  40617. var BABYLON;
  40618. (function (BABYLON) {
  40619. var HDRRenderingPipeline = (function (_super) {
  40620. __extends(HDRRenderingPipeline, _super);
  40621. /**
  40622. * @constructor
  40623. * @param {string} name - The rendering pipeline name
  40624. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40625. * @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)
  40626. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  40627. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40628. */
  40629. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  40630. var _this = this;
  40631. if (originalPostProcess === void 0) { originalPostProcess = null; }
  40632. _super.call(this, scene.getEngine(), name);
  40633. /**
  40634. * Public members
  40635. */
  40636. // Gaussian Blur
  40637. /**
  40638. * Gaussian blur coefficient
  40639. * @type {number}
  40640. */
  40641. this.gaussCoeff = 0.3;
  40642. /**
  40643. * Gaussian blur mean
  40644. * @type {number}
  40645. */
  40646. this.gaussMean = 1.0;
  40647. /**
  40648. * Gaussian blur standard deviation
  40649. * @type {number}
  40650. */
  40651. this.gaussStandDev = 0.8;
  40652. /**
  40653. * Gaussian blur multiplier. Multiplies the blur effect
  40654. * @type {number}
  40655. */
  40656. this.gaussMultiplier = 4.0;
  40657. // HDR
  40658. /**
  40659. * Exposure, controls the overall intensity of the pipeline
  40660. * @type {number}
  40661. */
  40662. this.exposure = 1.0;
  40663. /**
  40664. * Minimum luminance that the post-process can output. Luminance is >= 0
  40665. * @type {number}
  40666. */
  40667. this.minimumLuminance = 1.0;
  40668. /**
  40669. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  40670. * @type {number}
  40671. */
  40672. this.maximumLuminance = 1e20;
  40673. /**
  40674. * Increase rate for luminance: eye adaptation speed to dark
  40675. * @type {number}
  40676. */
  40677. this.luminanceIncreaserate = 0.5;
  40678. /**
  40679. * Decrease rate for luminance: eye adaptation speed to bright
  40680. * @type {number}
  40681. */
  40682. this.luminanceDecreaseRate = 0.5;
  40683. // Bright pass
  40684. /**
  40685. * Minimum luminance needed to compute HDR
  40686. * @type {number}
  40687. */
  40688. this.brightThreshold = 0.8;
  40689. this._needUpdate = true;
  40690. this._scene = scene;
  40691. // Bright pass
  40692. this._createBrightPassPostProcess(scene, ratio);
  40693. // Down sample X4
  40694. this._createDownSampleX4PostProcess(scene, ratio);
  40695. // Create gaussian blur post-processes
  40696. this._createGaussianBlurPostProcess(scene, ratio);
  40697. // Texture adder
  40698. this._createTextureAdderPostProcess(scene, ratio);
  40699. // Luminance generator
  40700. this._createLuminanceGeneratorPostProcess(scene);
  40701. // HDR
  40702. this._createHDRPostProcess(scene, ratio);
  40703. // Pass postprocess
  40704. if (originalPostProcess === null) {
  40705. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40706. }
  40707. else {
  40708. this._originalPostProcess = originalPostProcess;
  40709. }
  40710. // Configure pipeline
  40711. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  40712. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  40713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  40714. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  40715. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  40716. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  40717. var addDownSamplerPostProcess = function (id) {
  40718. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  40719. };
  40720. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40721. addDownSamplerPostProcess(i);
  40722. }
  40723. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  40724. // Finish
  40725. scene.postProcessRenderPipelineManager.addPipeline(this);
  40726. if (cameras !== null) {
  40727. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40728. }
  40729. this.update();
  40730. }
  40731. /**
  40732. * Tells the pipeline to update its post-processes
  40733. */
  40734. HDRRenderingPipeline.prototype.update = function () {
  40735. this._needUpdate = true;
  40736. };
  40737. /**
  40738. * Returns the current calculated luminance
  40739. */
  40740. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  40741. return this._hdrCurrentLuminance;
  40742. };
  40743. /**
  40744. * Returns the currently drawn luminance
  40745. */
  40746. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  40747. return this._hdrOutputLuminance;
  40748. };
  40749. /**
  40750. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  40751. */
  40752. HDRRenderingPipeline.prototype.dispose = function () {
  40753. this._originalPostProcess = undefined;
  40754. this._brightPassPostProcess = undefined;
  40755. this._downSampleX4PostProcess = undefined;
  40756. this._guassianBlurHPostProcess = undefined;
  40757. this._guassianBlurVPostProcess = undefined;
  40758. this._textureAdderPostProcess = undefined;
  40759. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40760. this._downSamplePostProcesses[i] = undefined;
  40761. }
  40762. this._hdrPostProcess = undefined;
  40763. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40764. };
  40765. /**
  40766. * Creates the HDR post-process and computes the luminance adaptation
  40767. */
  40768. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  40769. var _this = this;
  40770. var hdrLastLuminance = 0.0;
  40771. this._hdrOutputLuminance = -1.0;
  40772. this._hdrCurrentLuminance = 1.0;
  40773. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  40774. this._hdrPostProcess.onApply = function (effect) {
  40775. if (_this._hdrOutputLuminance < 0.0) {
  40776. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40777. }
  40778. else {
  40779. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  40780. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  40781. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  40782. }
  40783. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  40784. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  40785. }
  40786. else {
  40787. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40788. }
  40789. }
  40790. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  40791. hdrLastLuminance += scene.getEngine().getDeltaTime();
  40792. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40793. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40794. effect.setFloat("exposure", _this.exposure);
  40795. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  40796. _this._needUpdate = false;
  40797. };
  40798. };
  40799. /**
  40800. * Texture Adder post-process
  40801. */
  40802. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  40803. var _this = this;
  40804. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  40805. this._textureAdderPostProcess.onApply = function (effect) {
  40806. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40807. };
  40808. };
  40809. /**
  40810. * Down sample X4 post-process
  40811. */
  40812. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  40813. var _this = this;
  40814. var downSampleX4Offsets = new Array(32);
  40815. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  40816. this._downSampleX4PostProcess.onApply = function (effect) {
  40817. if (_this._needUpdate) {
  40818. var id = 0;
  40819. for (var i = -2; i < 2; i++) {
  40820. for (var j = -2; j < 2; j++) {
  40821. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  40822. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  40823. id += 2;
  40824. }
  40825. }
  40826. }
  40827. effect.setArray2("dsOffsets", downSampleX4Offsets);
  40828. };
  40829. };
  40830. /**
  40831. * Bright pass post-process
  40832. */
  40833. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  40834. var _this = this;
  40835. var brightOffsets = new Array(8);
  40836. var brightPassCallback = function (effect) {
  40837. if (_this._needUpdate) {
  40838. var sU = (1.0 / _this._brightPassPostProcess.width);
  40839. var sV = (1.0 / _this._brightPassPostProcess.height);
  40840. brightOffsets[0] = -0.5 * sU;
  40841. brightOffsets[1] = 0.5 * sV;
  40842. brightOffsets[2] = 0.5 * sU;
  40843. brightOffsets[3] = 0.5 * sV;
  40844. brightOffsets[4] = -0.5 * sU;
  40845. brightOffsets[5] = -0.5 * sV;
  40846. brightOffsets[6] = 0.5 * sU;
  40847. brightOffsets[7] = -0.5 * sV;
  40848. }
  40849. effect.setArray2("dsOffsets", brightOffsets);
  40850. effect.setFloat("brightThreshold", _this.brightThreshold);
  40851. };
  40852. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  40853. this._brightPassPostProcess.onApply = brightPassCallback;
  40854. };
  40855. /**
  40856. * Luminance generator. Creates the luminance post-process and down sample post-processes
  40857. */
  40858. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  40859. var _this = this;
  40860. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  40861. var luminanceOffsets = new Array(8);
  40862. var downSampleOffsets = new Array(18);
  40863. var halfDestPixelSize;
  40864. this._downSamplePostProcesses = new Array(lumSteps);
  40865. // Utils for luminance
  40866. var luminanceUpdateSourceOffsets = function (width, height) {
  40867. var sU = (1.0 / width);
  40868. var sV = (1.0 / height);
  40869. luminanceOffsets[0] = -0.5 * sU;
  40870. luminanceOffsets[1] = 0.5 * sV;
  40871. luminanceOffsets[2] = 0.5 * sU;
  40872. luminanceOffsets[3] = 0.5 * sV;
  40873. luminanceOffsets[4] = -0.5 * sU;
  40874. luminanceOffsets[5] = -0.5 * sV;
  40875. luminanceOffsets[6] = 0.5 * sU;
  40876. luminanceOffsets[7] = -0.5 * sV;
  40877. };
  40878. var luminanceUpdateDestOffsets = function (width, height) {
  40879. var id = 0;
  40880. for (var x = -1; x < 2; x++) {
  40881. for (var y = -1; y < 2; y++) {
  40882. downSampleOffsets[id] = (x) / width;
  40883. downSampleOffsets[id + 1] = (y) / height;
  40884. id += 2;
  40885. }
  40886. }
  40887. };
  40888. // Luminance callback
  40889. var luminanceCallback = function (effect) {
  40890. if (_this._needUpdate) {
  40891. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  40892. }
  40893. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40894. effect.setArray2("lumOffsets", luminanceOffsets);
  40895. };
  40896. // Down sample callbacks
  40897. var downSampleCallback = function (indice) {
  40898. var i = indice;
  40899. return function (effect) {
  40900. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  40901. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  40902. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  40903. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  40904. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  40905. effect.setArray2("dsOffsets", downSampleOffsets);
  40906. };
  40907. };
  40908. var downSampleAfterRenderCallback = function (effect) {
  40909. // Unpack result
  40910. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  40911. 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);
  40912. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  40913. };
  40914. // Create luminance post-process
  40915. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  40916. 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);
  40917. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  40918. // Create down sample post-processes
  40919. for (var i = lumSteps - 2; i >= 0; i--) {
  40920. var length = Math.pow(3, i);
  40921. ratio = { width: length, height: length };
  40922. var defines = "#define DOWN_SAMPLE\n";
  40923. if (i === 0) {
  40924. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  40925. }
  40926. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  40927. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  40928. if (i === 0) {
  40929. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  40930. }
  40931. }
  40932. };
  40933. /**
  40934. * Gaussian blur post-processes. Horizontal and Vertical
  40935. */
  40936. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  40937. var _this = this;
  40938. var blurOffsetsW = new Array(9);
  40939. var blurOffsetsH = new Array(9);
  40940. var blurWeights = new Array(9);
  40941. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  40942. // Utils for gaussian blur
  40943. var calculateBlurOffsets = function (height) {
  40944. var lastOutputDimensions = {
  40945. width: scene.getEngine().getRenderWidth(),
  40946. height: scene.getEngine().getRenderHeight()
  40947. };
  40948. for (var i = 0; i < 9; i++) {
  40949. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  40950. if (height) {
  40951. blurOffsetsH[i] = value;
  40952. }
  40953. else {
  40954. blurOffsetsW[i] = value;
  40955. }
  40956. }
  40957. };
  40958. var calculateWeights = function () {
  40959. var x = 0.0;
  40960. for (var i = 0; i < 9; i++) {
  40961. x = (i - 4.0) / 4.0;
  40962. 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));
  40963. }
  40964. };
  40965. // Callback
  40966. var gaussianBlurCallback = function (height) {
  40967. return function (effect) {
  40968. if (_this._needUpdate) {
  40969. calculateWeights();
  40970. calculateBlurOffsets(height);
  40971. }
  40972. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  40973. effect.setArray("blurWeights", blurWeights);
  40974. effect.setFloat("multiplier", _this.gaussMultiplier);
  40975. };
  40976. };
  40977. // Create horizontal gaussian blur post-processes
  40978. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  40979. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  40980. // Create vertical gaussian blur post-process
  40981. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  40982. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  40983. };
  40984. // Luminance generator
  40985. HDRRenderingPipeline.LUM_STEPS = 6;
  40986. return HDRRenderingPipeline;
  40987. })(BABYLON.PostProcessRenderPipeline);
  40988. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  40989. })(BABYLON || (BABYLON = {}));
  40990. var BABYLON;
  40991. (function (BABYLON) {
  40992. var FaceAdjacencies = (function () {
  40993. function FaceAdjacencies() {
  40994. this.edges = new Array();
  40995. this.edgesConnectedCount = 0;
  40996. }
  40997. return FaceAdjacencies;
  40998. })();
  40999. var EdgesRenderer = (function () {
  41000. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  41001. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  41002. if (epsilon === void 0) { epsilon = 0.95; }
  41003. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  41004. this.edgesWidthScalerForOrthographic = 1000.0;
  41005. this.edgesWidthScalerForPerspective = 50.0;
  41006. this._linesPositions = new Array();
  41007. this._linesNormals = new Array();
  41008. this._linesIndices = new Array();
  41009. this._buffers = new Array();
  41010. this._checkVerticesInsteadOfIndices = false;
  41011. this._source = source;
  41012. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  41013. this._epsilon = epsilon;
  41014. this._prepareRessources();
  41015. this._generateEdgesLines();
  41016. }
  41017. EdgesRenderer.prototype._prepareRessources = function () {
  41018. if (this._lineShader) {
  41019. return;
  41020. }
  41021. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  41022. attributes: ["position", "normal"],
  41023. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  41024. });
  41025. this._lineShader.disableDepthWrite = true;
  41026. this._lineShader.backFaceCulling = false;
  41027. };
  41028. EdgesRenderer.prototype.dispose = function () {
  41029. this._vb0.dispose();
  41030. this._vb1.dispose();
  41031. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  41032. this._lineShader.dispose();
  41033. };
  41034. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  41035. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  41036. return 0;
  41037. }
  41038. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  41039. return 1;
  41040. }
  41041. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  41042. return 2;
  41043. }
  41044. return -1;
  41045. };
  41046. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  41047. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  41048. return 0;
  41049. }
  41050. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  41051. return 1;
  41052. }
  41053. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  41054. return 2;
  41055. }
  41056. return -1;
  41057. };
  41058. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  41059. var needToCreateLine;
  41060. if (edge === undefined) {
  41061. needToCreateLine = true;
  41062. }
  41063. else {
  41064. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  41065. needToCreateLine = dotProduct < this._epsilon;
  41066. }
  41067. if (needToCreateLine) {
  41068. var offset = this._linesPositions.length / 3;
  41069. var normal = p0.subtract(p1);
  41070. normal.normalize();
  41071. // Positions
  41072. this._linesPositions.push(p0.x);
  41073. this._linesPositions.push(p0.y);
  41074. this._linesPositions.push(p0.z);
  41075. this._linesPositions.push(p0.x);
  41076. this._linesPositions.push(p0.y);
  41077. this._linesPositions.push(p0.z);
  41078. this._linesPositions.push(p1.x);
  41079. this._linesPositions.push(p1.y);
  41080. this._linesPositions.push(p1.z);
  41081. this._linesPositions.push(p1.x);
  41082. this._linesPositions.push(p1.y);
  41083. this._linesPositions.push(p1.z);
  41084. // Normals
  41085. this._linesNormals.push(p1.x);
  41086. this._linesNormals.push(p1.y);
  41087. this._linesNormals.push(p1.z);
  41088. this._linesNormals.push(-1);
  41089. this._linesNormals.push(p1.x);
  41090. this._linesNormals.push(p1.y);
  41091. this._linesNormals.push(p1.z);
  41092. this._linesNormals.push(1);
  41093. this._linesNormals.push(p0.x);
  41094. this._linesNormals.push(p0.y);
  41095. this._linesNormals.push(p0.z);
  41096. this._linesNormals.push(-1);
  41097. this._linesNormals.push(p0.x);
  41098. this._linesNormals.push(p0.y);
  41099. this._linesNormals.push(p0.z);
  41100. this._linesNormals.push(1);
  41101. // Indices
  41102. this._linesIndices.push(offset);
  41103. this._linesIndices.push(offset + 1);
  41104. this._linesIndices.push(offset + 2);
  41105. this._linesIndices.push(offset);
  41106. this._linesIndices.push(offset + 2);
  41107. this._linesIndices.push(offset + 3);
  41108. }
  41109. };
  41110. EdgesRenderer.prototype._generateEdgesLines = function () {
  41111. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41112. var indices = this._source.getIndices();
  41113. // First let's find adjacencies
  41114. var adjacencies = new Array();
  41115. var faceNormals = new Array();
  41116. var index;
  41117. var faceAdjacencies;
  41118. // Prepare faces
  41119. for (index = 0; index < indices.length; index += 3) {
  41120. faceAdjacencies = new FaceAdjacencies();
  41121. var p0Index = indices[index];
  41122. var p1Index = indices[index + 1];
  41123. var p2Index = indices[index + 2];
  41124. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  41125. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  41126. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  41127. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  41128. faceNormal.normalize();
  41129. faceNormals.push(faceNormal);
  41130. adjacencies.push(faceAdjacencies);
  41131. }
  41132. // Scan
  41133. for (index = 0; index < adjacencies.length; index++) {
  41134. faceAdjacencies = adjacencies[index];
  41135. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  41136. var otherFaceAdjacencies = adjacencies[otherIndex];
  41137. if (faceAdjacencies.edgesConnectedCount === 3) {
  41138. break;
  41139. }
  41140. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  41141. continue;
  41142. }
  41143. var otherP0 = indices[otherIndex * 3];
  41144. var otherP1 = indices[otherIndex * 3 + 1];
  41145. var otherP2 = indices[otherIndex * 3 + 2];
  41146. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  41147. var otherEdgeIndex;
  41148. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  41149. continue;
  41150. }
  41151. switch (edgeIndex) {
  41152. case 0:
  41153. if (this._checkVerticesInsteadOfIndices) {
  41154. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41155. }
  41156. else {
  41157. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  41158. }
  41159. break;
  41160. case 1:
  41161. if (this._checkVerticesInsteadOfIndices) {
  41162. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41163. }
  41164. else {
  41165. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  41166. }
  41167. break;
  41168. case 2:
  41169. if (this._checkVerticesInsteadOfIndices) {
  41170. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41171. }
  41172. else {
  41173. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  41174. }
  41175. break;
  41176. }
  41177. if (otherEdgeIndex === -1) {
  41178. continue;
  41179. }
  41180. faceAdjacencies.edges[edgeIndex] = otherIndex;
  41181. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  41182. faceAdjacencies.edgesConnectedCount++;
  41183. otherFaceAdjacencies.edgesConnectedCount++;
  41184. if (faceAdjacencies.edgesConnectedCount === 3) {
  41185. break;
  41186. }
  41187. }
  41188. }
  41189. }
  41190. // Create lines
  41191. for (index = 0; index < adjacencies.length; index++) {
  41192. // 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
  41193. var current = adjacencies[index];
  41194. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  41195. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  41196. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  41197. }
  41198. // Merge into a single mesh
  41199. var engine = this._source.getScene().getEngine();
  41200. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  41201. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  41202. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  41203. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  41204. this._ib = engine.createIndexBuffer(this._linesIndices);
  41205. this._indicesCount = this._linesIndices.length;
  41206. };
  41207. EdgesRenderer.prototype.render = function () {
  41208. if (!this._lineShader.isReady()) {
  41209. return;
  41210. }
  41211. var scene = this._source.getScene();
  41212. var engine = scene.getEngine();
  41213. this._lineShader._preBind();
  41214. // VBOs
  41215. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  41216. scene.resetCachedMaterial();
  41217. this._lineShader.setColor4("color", this._source.edgesColor);
  41218. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  41219. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  41220. }
  41221. else {
  41222. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  41223. }
  41224. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  41225. this._lineShader.bind(this._source.getWorldMatrix());
  41226. // Draw order
  41227. engine.draw(true, 0, this._indicesCount);
  41228. this._lineShader.unbind();
  41229. engine.setDepthWrite(true);
  41230. };
  41231. return EdgesRenderer;
  41232. })();
  41233. BABYLON.EdgesRenderer = EdgesRenderer;
  41234. })(BABYLON || (BABYLON = {}));
  41235. var BABYLON;
  41236. (function (BABYLON) {
  41237. (function (TonemappingOperator) {
  41238. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  41239. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  41240. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  41241. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  41242. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  41243. var TonemappingOperator = BABYLON.TonemappingOperator;
  41244. ;
  41245. var TonemapPostProcess = (function (_super) {
  41246. __extends(TonemapPostProcess, _super);
  41247. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  41248. var _this = this;
  41249. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41250. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41251. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  41252. this._operator = _operator;
  41253. this.exposureAdjustment = exposureAdjustment;
  41254. var defines = "#define ";
  41255. if (this._operator === TonemappingOperator.Hable)
  41256. defines += "HABLE_TONEMAPPING";
  41257. else if (this._operator === TonemappingOperator.Reinhard)
  41258. defines += "REINHARD_TONEMAPPING";
  41259. else if (this._operator === TonemappingOperator.HejiDawson)
  41260. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  41261. else if (this._operator === TonemappingOperator.Photographic)
  41262. defines += "PHOTOGRAPHIC_TONEMAPPING";
  41263. //sadly a second call to create the effect.
  41264. this.updateEffect(defines);
  41265. this.onApply = function (effect) {
  41266. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  41267. };
  41268. }
  41269. return TonemapPostProcess;
  41270. })(BABYLON.PostProcess);
  41271. BABYLON.TonemapPostProcess = TonemapPostProcess;
  41272. })(BABYLON || (BABYLON = {}));
  41273. var BABYLON;
  41274. (function (BABYLON) {
  41275. var ReflectionProbe = (function () {
  41276. function ReflectionProbe(name, size, scene, generateMipMaps) {
  41277. var _this = this;
  41278. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41279. this.name = name;
  41280. this._viewMatrix = BABYLON.Matrix.Identity();
  41281. this._target = BABYLON.Vector3.Zero();
  41282. this._add = BABYLON.Vector3.Zero();
  41283. this.position = BABYLON.Vector3.Zero();
  41284. this._scene = scene;
  41285. this._scene.reflectionProbes.push(this);
  41286. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  41287. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  41288. switch (faceIndex) {
  41289. case 0:
  41290. _this._add.copyFromFloats(1, 0, 0);
  41291. break;
  41292. case 1:
  41293. _this._add.copyFromFloats(-1, 0, 0);
  41294. break;
  41295. case 2:
  41296. _this._add.copyFromFloats(0, -1, 0);
  41297. break;
  41298. case 3:
  41299. _this._add.copyFromFloats(0, 1, 0);
  41300. break;
  41301. case 4:
  41302. _this._add.copyFromFloats(0, 0, 1);
  41303. break;
  41304. case 5:
  41305. _this._add.copyFromFloats(0, 0, -1);
  41306. break;
  41307. }
  41308. if (_this._attachedMesh) {
  41309. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  41310. }
  41311. _this.position.addToRef(_this._add, _this._target);
  41312. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  41313. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  41314. };
  41315. this._renderTargetTexture.onAfterUnbind = function () {
  41316. scene.updateTransformMatrix(true);
  41317. };
  41318. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  41319. }
  41320. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  41321. get: function () {
  41322. return this._renderTargetTexture.refreshRate;
  41323. },
  41324. set: function (value) {
  41325. this._renderTargetTexture.refreshRate = value;
  41326. },
  41327. enumerable: true,
  41328. configurable: true
  41329. });
  41330. ReflectionProbe.prototype.getScene = function () {
  41331. return this._scene;
  41332. };
  41333. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  41334. get: function () {
  41335. return this._renderTargetTexture;
  41336. },
  41337. enumerable: true,
  41338. configurable: true
  41339. });
  41340. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  41341. get: function () {
  41342. return this._renderTargetTexture.renderList;
  41343. },
  41344. enumerable: true,
  41345. configurable: true
  41346. });
  41347. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  41348. this._attachedMesh = mesh;
  41349. };
  41350. ReflectionProbe.prototype.dispose = function () {
  41351. var index = this._scene.reflectionProbes.indexOf(this);
  41352. if (index !== -1) {
  41353. // Remove from the scene if found
  41354. this._scene.reflectionProbes.splice(index, 1);
  41355. }
  41356. if (this._renderTargetTexture) {
  41357. this._renderTargetTexture.dispose();
  41358. this._renderTargetTexture = null;
  41359. }
  41360. };
  41361. return ReflectionProbe;
  41362. })();
  41363. BABYLON.ReflectionProbe = ReflectionProbe;
  41364. })(BABYLON || (BABYLON = {}));
  41365. var BABYLON;
  41366. (function (BABYLON) {
  41367. var SolidParticle = (function () {
  41368. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  41369. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  41370. this.position = BABYLON.Vector3.Zero(); // position
  41371. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41372. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  41373. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  41374. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41375. this.alive = true; // alive
  41376. this.idx = particleIndex;
  41377. this._pos = positionIndex;
  41378. this._model = model;
  41379. this.shapeId = shapeId;
  41380. this.idxInShape = idxInShape;
  41381. }
  41382. Object.defineProperty(SolidParticle.prototype, "scale", {
  41383. //legacy support, changed scale to scaling
  41384. get: function () {
  41385. return this.scaling;
  41386. },
  41387. set: function (scale) {
  41388. this.scaling = scale;
  41389. },
  41390. enumerable: true,
  41391. configurable: true
  41392. });
  41393. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41394. //legacy support, changed quaternion to rotationQuaternion
  41395. get: function () {
  41396. return this.rotationQuaternion;
  41397. },
  41398. set: function (q) {
  41399. this.rotationQuaternion = q;
  41400. },
  41401. enumerable: true,
  41402. configurable: true
  41403. });
  41404. return SolidParticle;
  41405. })();
  41406. BABYLON.SolidParticle = SolidParticle;
  41407. var ModelShape = (function () {
  41408. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41409. this.shapeID = id;
  41410. this._shape = shape;
  41411. this._shapeUV = shapeUV;
  41412. this._positionFunction = posFunction;
  41413. this._vertexFunction = vtxFunction;
  41414. }
  41415. return ModelShape;
  41416. })();
  41417. BABYLON.ModelShape = ModelShape;
  41418. })(BABYLON || (BABYLON = {}));
  41419. var BABYLON;
  41420. (function (BABYLON) {
  41421. /**
  41422. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  41423. */
  41424. var SolidParticleSystem = (function () {
  41425. /**
  41426. * Creates a SPS (Solid Particle System) object.
  41427. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41428. * `scene` (Scene) is the scene in which the SPS is added.
  41429. * `updatableè (default true) : if the SPS must be updatable or immutable.
  41430. * `isPickable` (default false) : if the solid particles must be pickable.
  41431. */
  41432. function SolidParticleSystem(name, scene, options) {
  41433. // public members
  41434. /**
  41435. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41436. * Example : var p = SPS.particles[i];
  41437. */
  41438. this.particles = new Array();
  41439. /**
  41440. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41441. */
  41442. this.nbParticles = 0;
  41443. /**
  41444. * If the particles must ever face the camera (default false). Useful for planar particles.
  41445. */
  41446. this.billboard = false;
  41447. /**
  41448. * This a counter ofr your own usage. It's not set by any SPS functions.
  41449. */
  41450. this.counter = 0;
  41451. /**
  41452. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41453. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  41454. */
  41455. this.vars = {};
  41456. this._positions = new Array();
  41457. this._indices = new Array();
  41458. this._normals = new Array();
  41459. this._colors = new Array();
  41460. this._uvs = new Array();
  41461. this._index = 0; // indices index
  41462. this._updatable = true;
  41463. this._pickable = false;
  41464. this._isVisibilityBoxLocked = false;
  41465. this._alwaysVisible = false;
  41466. this._shapeCounter = 0;
  41467. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  41468. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41469. this._computeParticleColor = true;
  41470. this._computeParticleTexture = true;
  41471. this._computeParticleRotation = true;
  41472. this._computeParticleVertex = false;
  41473. this._computeBoundingBox = false;
  41474. this._cam_axisZ = BABYLON.Vector3.Zero();
  41475. this._cam_axisY = BABYLON.Vector3.Zero();
  41476. this._cam_axisX = BABYLON.Vector3.Zero();
  41477. this._axisX = BABYLON.Axis.X;
  41478. this._axisY = BABYLON.Axis.Y;
  41479. this._axisZ = BABYLON.Axis.Z;
  41480. this._fakeCamPos = BABYLON.Vector3.Zero();
  41481. this._rotMatrix = new BABYLON.Matrix();
  41482. this._invertMatrix = new BABYLON.Matrix();
  41483. this._rotated = BABYLON.Vector3.Zero();
  41484. this._quaternion = new BABYLON.Quaternion();
  41485. this._vertex = BABYLON.Vector3.Zero();
  41486. this._normal = BABYLON.Vector3.Zero();
  41487. this._yaw = 0.0;
  41488. this._pitch = 0.0;
  41489. this._roll = 0.0;
  41490. this._halfroll = 0.0;
  41491. this._halfpitch = 0.0;
  41492. this._halfyaw = 0.0;
  41493. this._sinRoll = 0.0;
  41494. this._cosRoll = 0.0;
  41495. this._sinPitch = 0.0;
  41496. this._cosPitch = 0.0;
  41497. this._sinYaw = 0.0;
  41498. this._cosYaw = 0.0;
  41499. this._w = 0.0;
  41500. this._minimum = BABYLON.Tmp.Vector3[0];
  41501. this._maximum = BABYLON.Tmp.Vector3[1];
  41502. this.name = name;
  41503. this._scene = scene;
  41504. this._camera = scene.activeCamera;
  41505. this._pickable = options ? options.isPickable : false;
  41506. if (options && options.updatable) {
  41507. this._updatable = options.updatable;
  41508. }
  41509. else {
  41510. this._updatable = true;
  41511. }
  41512. if (this._pickable) {
  41513. this.pickedParticles = [];
  41514. }
  41515. }
  41516. /**
  41517. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41518. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41519. */
  41520. SolidParticleSystem.prototype.buildMesh = function () {
  41521. if (this.nbParticles === 0) {
  41522. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41523. this.addShape(triangle, 1);
  41524. triangle.dispose();
  41525. }
  41526. this._positions32 = new Float32Array(this._positions);
  41527. this._uvs32 = new Float32Array(this._uvs);
  41528. this._colors32 = new Float32Array(this._colors);
  41529. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41530. this._normals32 = new Float32Array(this._normals);
  41531. this._fixedNormal32 = new Float32Array(this._normals);
  41532. var vertexData = new BABYLON.VertexData();
  41533. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41534. vertexData.indices = this._indices;
  41535. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41536. if (this._uvs32) {
  41537. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41538. ;
  41539. }
  41540. if (this._colors32) {
  41541. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41542. }
  41543. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41544. vertexData.applyToMesh(mesh, this._updatable);
  41545. this.mesh = mesh;
  41546. this.mesh.isPickable = this._pickable;
  41547. // free memory
  41548. this._positions = null;
  41549. this._normals = null;
  41550. this._uvs = null;
  41551. this._colors = null;
  41552. if (!this._updatable) {
  41553. this.particles.length = 0;
  41554. }
  41555. return mesh;
  41556. };
  41557. /**
  41558. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41559. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41560. * Thus the particles generated from `digest()` have their property `position` set yet.
  41561. * `mesh` (`Mesh`) is the mesh to be digested
  41562. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41563. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41564. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41565. */
  41566. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41567. var size = (options && options.facetNb) || 1;
  41568. var number = (options && options.number);
  41569. var delta = (options && options.delta) || 0;
  41570. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41571. var meshInd = mesh.getIndices();
  41572. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41573. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41574. var f = 0; // facet counter
  41575. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41576. // compute size from number
  41577. if (number) {
  41578. number = (number > totalFacets) ? totalFacets : number;
  41579. size = Math.round(totalFacets / number);
  41580. delta = 0;
  41581. }
  41582. else {
  41583. size = (size > totalFacets) ? totalFacets : size;
  41584. }
  41585. var facetPos = []; // submesh positions
  41586. var facetInd = []; // submesh indices
  41587. var facetUV = []; // submesh UV
  41588. var facetCol = []; // submesh colors
  41589. var barycenter = BABYLON.Tmp.Vector3[0];
  41590. var rand;
  41591. var sizeO = size;
  41592. while (f < totalFacets) {
  41593. size = sizeO + Math.floor((1 + delta) * Math.random());
  41594. if (f > totalFacets - size) {
  41595. size = totalFacets - f;
  41596. }
  41597. // reset temp arrays
  41598. facetPos.length = 0;
  41599. facetInd.length = 0;
  41600. facetUV.length = 0;
  41601. facetCol.length = 0;
  41602. // iterate over "size" facets
  41603. var fi = 0;
  41604. for (var j = f * 3; j < (f + size) * 3; j++) {
  41605. facetInd.push(fi);
  41606. var i = meshInd[j];
  41607. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41608. if (meshUV) {
  41609. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41610. }
  41611. if (meshCol) {
  41612. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41613. }
  41614. fi++;
  41615. }
  41616. // create a model shape for each single particle
  41617. var idx = this.nbParticles;
  41618. var shape = this._posToShape(facetPos);
  41619. var shapeUV = this._uvsToShapeUV(facetUV);
  41620. // compute the barycenter of the shape
  41621. var v;
  41622. for (v = 0; v < shape.length; v++) {
  41623. barycenter.addInPlace(shape[v]);
  41624. }
  41625. barycenter.scaleInPlace(1 / shape.length);
  41626. // shift the shape from its barycenter to the origin
  41627. for (v = 0; v < shape.length; v++) {
  41628. shape[v].subtractInPlace(barycenter);
  41629. }
  41630. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41631. // add the particle in the SPS
  41632. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  41633. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  41634. // initialize the particle position
  41635. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41636. this._index += shape.length;
  41637. idx++;
  41638. this.nbParticles++;
  41639. this._shapeCounter++;
  41640. f += size;
  41641. }
  41642. return this;
  41643. };
  41644. //reset copy
  41645. SolidParticleSystem.prototype._resetCopy = function () {
  41646. this._copy.position.x = 0;
  41647. this._copy.position.y = 0;
  41648. this._copy.position.z = 0;
  41649. this._copy.rotation.x = 0;
  41650. this._copy.rotation.y = 0;
  41651. this._copy.rotation.z = 0;
  41652. this._copy.rotationQuaternion = null;
  41653. this._copy.scaling.x = 1;
  41654. this._copy.scaling.y = 1;
  41655. this._copy.scaling.z = 1;
  41656. this._copy.uvs.x = 0;
  41657. this._copy.uvs.y = 0;
  41658. this._copy.uvs.z = 1;
  41659. this._copy.uvs.w = 1;
  41660. this._copy.color = null;
  41661. };
  41662. // _meshBuilder : inserts the shape model in the global SPS mesh
  41663. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  41664. var i;
  41665. var u = 0;
  41666. var c = 0;
  41667. this._resetCopy();
  41668. if (options && options.positionFunction) {
  41669. options.positionFunction(this._copy, idx, idxInShape);
  41670. }
  41671. if (this._copy.rotationQuaternion) {
  41672. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41673. }
  41674. else {
  41675. this._yaw = this._copy.rotation.y;
  41676. this._pitch = this._copy.rotation.x;
  41677. this._roll = this._copy.rotation.z;
  41678. this._quaternionRotationYPR();
  41679. }
  41680. this._quaternionToRotationMatrix();
  41681. for (i = 0; i < shape.length; i++) {
  41682. this._vertex.x = shape[i].x;
  41683. this._vertex.y = shape[i].y;
  41684. this._vertex.z = shape[i].z;
  41685. if (options && options.vertexFunction) {
  41686. options.vertexFunction(this._copy, this._vertex, i);
  41687. }
  41688. this._vertex.x *= this._copy.scaling.x;
  41689. this._vertex.y *= this._copy.scaling.y;
  41690. this._vertex.z *= this._copy.scaling.z;
  41691. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41692. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41693. if (meshUV) {
  41694. 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);
  41695. u += 2;
  41696. }
  41697. if (this._copy.color) {
  41698. this._color = this._copy.color;
  41699. }
  41700. else if (meshCol && meshCol[c]) {
  41701. this._color.r = meshCol[c];
  41702. this._color.g = meshCol[c + 1];
  41703. this._color.b = meshCol[c + 2];
  41704. this._color.a = meshCol[c + 3];
  41705. }
  41706. else {
  41707. this._color.r = 1;
  41708. this._color.g = 1;
  41709. this._color.b = 1;
  41710. this._color.a = 1;
  41711. }
  41712. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41713. c += 4;
  41714. }
  41715. for (i = 0; i < meshInd.length; i++) {
  41716. indices.push(p + meshInd[i]);
  41717. }
  41718. if (this._pickable) {
  41719. var nbfaces = meshInd.length / 3;
  41720. for (i = 0; i < nbfaces; i++) {
  41721. this.pickedParticles.push({ idx: idx, faceId: i });
  41722. }
  41723. }
  41724. };
  41725. // returns a shape array from positions array
  41726. SolidParticleSystem.prototype._posToShape = function (positions) {
  41727. var shape = [];
  41728. for (var i = 0; i < positions.length; i += 3) {
  41729. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41730. }
  41731. return shape;
  41732. };
  41733. // returns a shapeUV array from a Vector4 uvs
  41734. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41735. var shapeUV = [];
  41736. if (uvs) {
  41737. for (var i = 0; i < uvs.length; i++)
  41738. shapeUV.push(uvs[i]);
  41739. }
  41740. return shapeUV;
  41741. };
  41742. // adds a new particle object in the particles array
  41743. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  41744. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  41745. };
  41746. /**
  41747. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41748. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  41749. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  41750. * `nb` (positive integer) the number of particles to be created from this model
  41751. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41752. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41753. */
  41754. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41755. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41756. var meshInd = mesh.getIndices();
  41757. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41758. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41759. var shape = this._posToShape(meshPos);
  41760. var shapeUV = this._uvsToShapeUV(meshUV);
  41761. var posfunc = options ? options.positionFunction : null;
  41762. var vtxfunc = options ? options.vertexFunction : null;
  41763. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41764. // particles
  41765. var idx = this.nbParticles;
  41766. for (var i = 0; i < nb; i++) {
  41767. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  41768. if (this._updatable) {
  41769. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  41770. }
  41771. this._index += shape.length;
  41772. idx++;
  41773. }
  41774. this.nbParticles += nb;
  41775. this._shapeCounter++;
  41776. return this._shapeCounter - 1;
  41777. };
  41778. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41779. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41780. this._resetCopy();
  41781. if (particle._model._positionFunction) {
  41782. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41783. }
  41784. if (this._copy.rotationQuaternion) {
  41785. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41786. }
  41787. else {
  41788. this._yaw = this._copy.rotation.y;
  41789. this._pitch = this._copy.rotation.x;
  41790. this._roll = this._copy.rotation.z;
  41791. this._quaternionRotationYPR();
  41792. }
  41793. this._quaternionToRotationMatrix();
  41794. this._shape = particle._model._shape;
  41795. for (var pt = 0; pt < this._shape.length; pt++) {
  41796. this._vertex.x = this._shape[pt].x;
  41797. this._vertex.y = this._shape[pt].y;
  41798. this._vertex.z = this._shape[pt].z;
  41799. if (particle._model._vertexFunction) {
  41800. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41801. }
  41802. this._vertex.x *= this._copy.scaling.x;
  41803. this._vertex.y *= this._copy.scaling.y;
  41804. this._vertex.z *= this._copy.scaling.z;
  41805. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41806. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41807. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41808. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41809. }
  41810. particle.position.x = 0;
  41811. particle.position.y = 0;
  41812. particle.position.z = 0;
  41813. particle.rotation.x = 0;
  41814. particle.rotation.y = 0;
  41815. particle.rotation.z = 0;
  41816. particle.rotationQuaternion = null;
  41817. particle.scaling.x = 1;
  41818. particle.scaling.y = 1;
  41819. particle.scaling.z = 1;
  41820. };
  41821. /**
  41822. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41823. */
  41824. SolidParticleSystem.prototype.rebuildMesh = function () {
  41825. for (var p = 0; p < this.particles.length; p++) {
  41826. this._rebuildParticle(this.particles[p]);
  41827. }
  41828. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41829. };
  41830. /**
  41831. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41832. * This method calls `updateParticle()` for each particle of the SPS.
  41833. * For an animated SPS, it is usually called within the render loop.
  41834. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  41835. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  41836. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  41837. */
  41838. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41839. if (start === void 0) { start = 0; }
  41840. if (end === void 0) { end = this.nbParticles - 1; }
  41841. if (update === void 0) { update = true; }
  41842. if (!this._updatable) {
  41843. return;
  41844. }
  41845. // custom beforeUpdate
  41846. this.beforeUpdateParticles(start, end, update);
  41847. this._cam_axisX.x = 1;
  41848. this._cam_axisX.y = 0;
  41849. this._cam_axisX.z = 0;
  41850. this._cam_axisY.x = 0;
  41851. this._cam_axisY.y = 1;
  41852. this._cam_axisY.z = 0;
  41853. this._cam_axisZ.x = 0;
  41854. this._cam_axisZ.y = 0;
  41855. this._cam_axisZ.z = 1;
  41856. // if the particles will always face the camera
  41857. if (this.billboard) {
  41858. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  41859. this._yaw = this.mesh.rotation.y;
  41860. this._pitch = this.mesh.rotation.x;
  41861. this._roll = this.mesh.rotation.z;
  41862. this._quaternionRotationYPR();
  41863. this._quaternionToRotationMatrix();
  41864. this._rotMatrix.invertToRef(this._invertMatrix);
  41865. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  41866. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  41867. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  41868. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  41869. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  41870. this._cam_axisY.normalize();
  41871. this._cam_axisX.normalize();
  41872. this._cam_axisZ.normalize();
  41873. }
  41874. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41875. var idx = 0;
  41876. var index = 0;
  41877. var colidx = 0;
  41878. var colorIndex = 0;
  41879. var uvidx = 0;
  41880. var uvIndex = 0;
  41881. if (this._computeBoundingBox) {
  41882. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41883. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41884. }
  41885. // particle loop
  41886. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  41887. for (var p = start; p <= end; p++) {
  41888. this._particle = this.particles[p];
  41889. this._shape = this._particle._model._shape;
  41890. this._shapeUV = this._particle._model._shapeUV;
  41891. // call to custom user function to update the particle properties
  41892. this.updateParticle(this._particle);
  41893. // particle rotation matrix
  41894. if (this.billboard) {
  41895. this._particle.rotation.x = 0.0;
  41896. this._particle.rotation.y = 0.0;
  41897. }
  41898. if (this._computeParticleRotation) {
  41899. if (this._particle.rotationQuaternion) {
  41900. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41901. }
  41902. else {
  41903. this._yaw = this._particle.rotation.y;
  41904. this._pitch = this._particle.rotation.x;
  41905. this._roll = this._particle.rotation.z;
  41906. this._quaternionRotationYPR();
  41907. }
  41908. this._quaternionToRotationMatrix();
  41909. }
  41910. for (var pt = 0; pt < this._shape.length; pt++) {
  41911. idx = index + pt * 3;
  41912. colidx = colorIndex + pt * 4;
  41913. uvidx = uvIndex + pt * 2;
  41914. this._vertex.x = this._shape[pt].x;
  41915. this._vertex.y = this._shape[pt].y;
  41916. this._vertex.z = this._shape[pt].z;
  41917. if (this._computeParticleVertex) {
  41918. this.updateParticleVertex(this._particle, this._vertex, pt);
  41919. }
  41920. // positions
  41921. this._vertex.x *= this._particle.scaling.x;
  41922. this._vertex.y *= this._particle.scaling.y;
  41923. this._vertex.z *= this._particle.scaling.z;
  41924. 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];
  41925. 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;
  41926. 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;
  41927. 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;
  41928. 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;
  41929. 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;
  41930. 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;
  41931. if (this._computeBoundingBox) {
  41932. if (this._positions32[idx] < this._minimum.x) {
  41933. this._minimum.x = this._positions32[idx];
  41934. }
  41935. if (this._positions32[idx] > this._maximum.x) {
  41936. this._maximum.x = this._positions32[idx];
  41937. }
  41938. if (this._positions32[idx + 1] < this._minimum.y) {
  41939. this._minimum.y = this._positions32[idx + 1];
  41940. }
  41941. if (this._positions32[idx + 1] > this._maximum.y) {
  41942. this._maximum.y = this._positions32[idx + 1];
  41943. }
  41944. if (this._positions32[idx + 2] < this._minimum.z) {
  41945. this._minimum.z = this._positions32[idx + 2];
  41946. }
  41947. if (this._positions32[idx + 2] > this._maximum.z) {
  41948. this._maximum.z = this._positions32[idx + 2];
  41949. }
  41950. }
  41951. // normals : if the particles can't be morphed then just rotate the normals
  41952. if (!this._computeParticleVertex && !this.billboard) {
  41953. this._normal.x = this._fixedNormal32[idx];
  41954. this._normal.y = this._fixedNormal32[idx + 1];
  41955. this._normal.z = this._fixedNormal32[idx + 2];
  41956. 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];
  41957. 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;
  41958. 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;
  41959. 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;
  41960. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  41961. 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;
  41962. 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;
  41963. }
  41964. if (this._computeParticleColor) {
  41965. this._colors32[colidx] = this._particle.color.r;
  41966. this._colors32[colidx + 1] = this._particle.color.g;
  41967. this._colors32[colidx + 2] = this._particle.color.b;
  41968. this._colors32[colidx + 3] = this._particle.color.a;
  41969. }
  41970. if (this._computeParticleTexture) {
  41971. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41972. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41973. }
  41974. }
  41975. index = idx + 3;
  41976. colorIndex = colidx + 4;
  41977. uvIndex = uvidx + 2;
  41978. }
  41979. if (update) {
  41980. if (this._computeParticleColor) {
  41981. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  41982. }
  41983. if (this._computeParticleTexture) {
  41984. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  41985. }
  41986. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41987. if (!this.mesh.areNormalsFrozen) {
  41988. if (this._computeParticleVertex || this.billboard) {
  41989. // recompute the normals only if the particles can be morphed, update then the normal reference array
  41990. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  41991. for (var i = 0; i < this._normals32.length; i++) {
  41992. this._fixedNormal32[i] = this._normals32[i];
  41993. }
  41994. }
  41995. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  41996. }
  41997. }
  41998. if (this._computeBoundingBox) {
  41999. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  42000. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  42001. }
  42002. this.afterUpdateParticles(start, end, update);
  42003. };
  42004. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  42005. this._halfroll = this._roll * 0.5;
  42006. this._halfpitch = this._pitch * 0.5;
  42007. this._halfyaw = this._yaw * 0.5;
  42008. this._sinRoll = Math.sin(this._halfroll);
  42009. this._cosRoll = Math.cos(this._halfroll);
  42010. this._sinPitch = Math.sin(this._halfpitch);
  42011. this._cosPitch = Math.cos(this._halfpitch);
  42012. this._sinYaw = Math.sin(this._halfyaw);
  42013. this._cosYaw = Math.cos(this._halfyaw);
  42014. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  42015. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  42016. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  42017. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  42018. };
  42019. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  42020. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  42021. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  42022. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  42023. this._rotMatrix.m[3] = 0;
  42024. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  42025. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  42026. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  42027. this._rotMatrix.m[7] = 0;
  42028. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  42029. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  42030. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  42031. this._rotMatrix.m[11] = 0;
  42032. this._rotMatrix.m[12] = 0;
  42033. this._rotMatrix.m[13] = 0;
  42034. this._rotMatrix.m[14] = 0;
  42035. this._rotMatrix.m[15] = 1.0;
  42036. };
  42037. /**
  42038. * Disposes the SPS
  42039. */
  42040. SolidParticleSystem.prototype.dispose = function () {
  42041. this.mesh.dispose();
  42042. this.vars = null;
  42043. // drop references to internal big arrays for the GC
  42044. this._positions = null;
  42045. this._indices = null;
  42046. this._normals = null;
  42047. this._uvs = null;
  42048. this._colors = null;
  42049. this._positions32 = null;
  42050. this._normals32 = null;
  42051. this._fixedNormal32 = null;
  42052. this._uvs32 = null;
  42053. this._colors32 = null;
  42054. this.pickedParticles = null;
  42055. };
  42056. /**
  42057. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  42058. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42059. */
  42060. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  42061. if (!this._isVisibilityBoxLocked) {
  42062. this.mesh.refreshBoundingInfo();
  42063. }
  42064. };
  42065. /**
  42066. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  42067. * @param size the size (float) of the visibility box
  42068. * note : this doesn't lock the SPS mesh bounding box.
  42069. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42070. */
  42071. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  42072. var vis = size / 2;
  42073. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  42074. };
  42075. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  42076. // getter and setter
  42077. get: function () {
  42078. return this._alwaysVisible;
  42079. },
  42080. /**
  42081. * Sets the SPS as always visible or not
  42082. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42083. */
  42084. set: function (val) {
  42085. this._alwaysVisible = val;
  42086. this.mesh.alwaysSelectAsActiveMesh = val;
  42087. },
  42088. enumerable: true,
  42089. configurable: true
  42090. });
  42091. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42092. get: function () {
  42093. return this._isVisibilityBoxLocked;
  42094. },
  42095. /**
  42096. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42097. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42098. */
  42099. set: function (val) {
  42100. this._isVisibilityBoxLocked = val;
  42101. this.mesh.getBoundingInfo().isLocked = val;
  42102. },
  42103. enumerable: true,
  42104. configurable: true
  42105. });
  42106. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42107. // getters
  42108. get: function () {
  42109. return this._computeParticleRotation;
  42110. },
  42111. // Optimizer setters
  42112. /**
  42113. * Tells to `setParticles()` to compute the particle rotations or not.
  42114. * Default value : true. The SPS is faster when it's set to false.
  42115. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42116. */
  42117. set: function (val) {
  42118. this._computeParticleRotation = val;
  42119. },
  42120. enumerable: true,
  42121. configurable: true
  42122. });
  42123. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42124. get: function () {
  42125. return this._computeParticleColor;
  42126. },
  42127. /**
  42128. * Tells to `setParticles()` to compute the particle colors or not.
  42129. * Default value : true. The SPS is faster when it's set to false.
  42130. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42131. */
  42132. set: function (val) {
  42133. this._computeParticleColor = val;
  42134. },
  42135. enumerable: true,
  42136. configurable: true
  42137. });
  42138. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42139. get: function () {
  42140. return this._computeParticleTexture;
  42141. },
  42142. /**
  42143. * Tells to `setParticles()` to compute the particle textures or not.
  42144. * Default value : true. The SPS is faster when it's set to false.
  42145. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42146. */
  42147. set: function (val) {
  42148. this._computeParticleTexture = val;
  42149. },
  42150. enumerable: true,
  42151. configurable: true
  42152. });
  42153. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42154. get: function () {
  42155. return this._computeParticleVertex;
  42156. },
  42157. /**
  42158. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42159. * Default value : false. The SPS is faster when it's set to false.
  42160. * Note : the particle custom vertex positions aren't stored values.
  42161. */
  42162. set: function (val) {
  42163. this._computeParticleVertex = val;
  42164. },
  42165. enumerable: true,
  42166. configurable: true
  42167. });
  42168. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42169. get: function () {
  42170. return this._computeBoundingBox;
  42171. },
  42172. /**
  42173. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42174. */
  42175. set: function (val) {
  42176. this._computeBoundingBox = val;
  42177. },
  42178. enumerable: true,
  42179. configurable: true
  42180. });
  42181. // =======================================================================
  42182. // Particle behavior logic
  42183. // these following methods may be overwritten by the user to fit his needs
  42184. /**
  42185. * This function does nothing. It may be overwritten to set all the particle first values.
  42186. * The SPS doesn't call this function, you may have to call it by your own.
  42187. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42188. */
  42189. SolidParticleSystem.prototype.initParticles = function () {
  42190. };
  42191. /**
  42192. * This function does nothing. It may be overwritten to recycle a particle.
  42193. * The SPS doesn't call this function, you may have to call it by your own.
  42194. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42195. */
  42196. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42197. return particle;
  42198. };
  42199. /**
  42200. * Updates a particle : this function should be overwritten by the user.
  42201. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42202. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42203. * ex : just set a particle position or velocity and recycle conditions
  42204. */
  42205. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42206. return particle;
  42207. };
  42208. /**
  42209. * Updates a vertex of a particle : it can be overwritten by the user.
  42210. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42211. * @param particle the current particle
  42212. * @param vertex the current index of the current particle
  42213. * @param pt the index of the current vertex in the particle shape
  42214. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  42215. * ex : just set a vertex particle position
  42216. */
  42217. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42218. return vertex;
  42219. };
  42220. /**
  42221. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42222. * This does nothing and may be overwritten by the user.
  42223. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42224. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42225. * @param update the boolean update value actually passed to setParticles()
  42226. */
  42227. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42228. };
  42229. /**
  42230. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42231. * This will be passed three parameters.
  42232. * This does nothing and may be overwritten by the user.
  42233. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42234. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42235. * @param update the boolean update value actually passed to setParticles()
  42236. */
  42237. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42238. };
  42239. return SolidParticleSystem;
  42240. })();
  42241. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42242. })(BABYLON || (BABYLON = {}));
  42243. var BABYLON;
  42244. (function (BABYLON) {
  42245. var Internals;
  42246. (function (Internals) {
  42247. var FileFaceOrientation = (function () {
  42248. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42249. this.name = name;
  42250. this.worldAxisForNormal = worldAxisForNormal;
  42251. this.worldAxisForFileX = worldAxisForFileX;
  42252. this.worldAxisForFileY = worldAxisForFileY;
  42253. }
  42254. return FileFaceOrientation;
  42255. })();
  42256. ;
  42257. /**
  42258. * Helper class dealing with the extraction of spherical polynomial dataArray
  42259. * from a cube map.
  42260. */
  42261. var CubeMapToSphericalPolynomialTools = (function () {
  42262. function CubeMapToSphericalPolynomialTools() {
  42263. }
  42264. /**
  42265. * Converts a cubemap to the according Spherical Polynomial data.
  42266. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42267. *
  42268. * @param cubeInfo The Cube map to extract the information from.
  42269. * @return The Spherical Polynomial data.
  42270. */
  42271. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  42272. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  42273. var totalSolidAngle = 0.0;
  42274. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  42275. var du = 2.0 / cubeInfo.size;
  42276. var dv = du;
  42277. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  42278. var minUV = du * 0.5 - 1.0;
  42279. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  42280. var fileFace = this.FileFaces[faceIndex];
  42281. var dataArray = cubeInfo[fileFace.name];
  42282. var v = minUV;
  42283. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  42284. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  42285. // Because SP is still linear, so summation is fine in that basis.
  42286. for (var y = 0; y < cubeInfo.size; y++) {
  42287. var u = minUV;
  42288. for (var x = 0; x < cubeInfo.size; x++) {
  42289. // World direction (not normalised)
  42290. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  42291. worldDirection.normalize();
  42292. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  42293. if (1) {
  42294. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  42295. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  42296. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  42297. var color = new BABYLON.Color3(r, g, b);
  42298. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42299. }
  42300. else {
  42301. if (faceIndex == 0) {
  42302. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42303. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42304. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42305. }
  42306. else if (faceIndex == 1) {
  42307. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42308. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42309. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42310. }
  42311. else if (faceIndex == 2) {
  42312. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42313. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42314. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42315. }
  42316. else if (faceIndex == 3) {
  42317. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42318. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42319. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42320. }
  42321. else if (faceIndex == 4) {
  42322. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42323. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42324. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42325. }
  42326. else if (faceIndex == 5) {
  42327. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42328. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42329. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42330. }
  42331. 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]);
  42332. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42333. }
  42334. totalSolidAngle += deltaSolidAngle;
  42335. u += du;
  42336. }
  42337. v += dv;
  42338. }
  42339. }
  42340. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  42341. var correction = correctSolidAngle / totalSolidAngle;
  42342. sphericalHarmonics.scale(correction);
  42343. // Additionally scale by pi -- audit needed
  42344. sphericalHarmonics.scale(1.0 / Math.PI);
  42345. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  42346. };
  42347. CubeMapToSphericalPolynomialTools.FileFaces = [
  42348. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  42349. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  42350. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  42351. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  42352. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  42353. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  42354. ];
  42355. return CubeMapToSphericalPolynomialTools;
  42356. })();
  42357. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  42358. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42359. })(BABYLON || (BABYLON = {}));
  42360. var BABYLON;
  42361. (function (BABYLON) {
  42362. var Internals;
  42363. (function (Internals) {
  42364. /**
  42365. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  42366. */
  42367. var PanoramaToCubeMapTools = (function () {
  42368. function PanoramaToCubeMapTools() {
  42369. }
  42370. /**
  42371. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  42372. *
  42373. * @param float32Array The source data.
  42374. * @param inputWidth The width of the input panorama.
  42375. * @param inputhHeight The height of the input panorama.
  42376. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  42377. * @return The cubemap data
  42378. */
  42379. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  42380. if (!float32Array) {
  42381. throw "ConvertPanoramaToCubemap: input cannot be null";
  42382. }
  42383. if (float32Array.length != inputWidth * inputHeight * 3) {
  42384. throw "ConvertPanoramaToCubemap: input size is wrong";
  42385. }
  42386. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  42387. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  42388. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  42389. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  42390. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  42391. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  42392. return {
  42393. front: textureFront,
  42394. back: textureBack,
  42395. left: textureLeft,
  42396. right: textureRight,
  42397. up: textureUp,
  42398. down: textureDown,
  42399. size: size
  42400. };
  42401. };
  42402. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  42403. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  42404. var textureArray = new Float32Array(buffer);
  42405. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  42406. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  42407. var dy = 1 / texSize;
  42408. var fy = 0;
  42409. for (var y = 0; y < texSize; y++) {
  42410. var xv1 = faceData[0];
  42411. var xv2 = faceData[2];
  42412. for (var x = 0; x < texSize; x++) {
  42413. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  42414. v.normalize();
  42415. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  42416. // 3 channels per pixels
  42417. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  42418. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  42419. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  42420. xv1 = xv1.add(rotDX1);
  42421. xv2 = xv2.add(rotDX2);
  42422. }
  42423. fy += dy;
  42424. }
  42425. return textureArray;
  42426. };
  42427. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  42428. var theta = Math.atan2(vDir.z, vDir.x);
  42429. var phi = Math.acos(vDir.y);
  42430. while (theta < -Math.PI)
  42431. theta += 2 * Math.PI;
  42432. while (theta > Math.PI)
  42433. theta -= 2 * Math.PI;
  42434. var dx = theta / Math.PI;
  42435. var dy = phi / Math.PI;
  42436. // recenter.
  42437. dx = dx * 0.5 + 0.5;
  42438. var px = Math.round(dx * inputWidth);
  42439. if (px < 0)
  42440. px = 0;
  42441. else if (px >= inputWidth)
  42442. px = inputWidth - 1;
  42443. var py = Math.round(dy * inputHeight);
  42444. if (py < 0)
  42445. py = 0;
  42446. else if (py >= inputHeight)
  42447. py = inputHeight - 1;
  42448. var inputY = (inputHeight - py - 1);
  42449. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  42450. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  42451. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  42452. return {
  42453. r: r,
  42454. g: g,
  42455. b: b
  42456. };
  42457. };
  42458. PanoramaToCubeMapTools.FACE_FRONT = [
  42459. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42460. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42461. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42462. new BABYLON.Vector3(1.0, 1.0, -1.0)
  42463. ];
  42464. PanoramaToCubeMapTools.FACE_BACK = [
  42465. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42466. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42467. new BABYLON.Vector3(1.0, 1.0, 1.0),
  42468. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  42469. ];
  42470. PanoramaToCubeMapTools.FACE_RIGHT = [
  42471. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42472. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42473. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42474. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42475. ];
  42476. PanoramaToCubeMapTools.FACE_LEFT = [
  42477. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42478. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42479. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42480. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  42481. ];
  42482. PanoramaToCubeMapTools.FACE_DOWN = [
  42483. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42484. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42485. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42486. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42487. ];
  42488. PanoramaToCubeMapTools.FACE_UP = [
  42489. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42490. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42491. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42492. new BABYLON.Vector3(1.0, -1.0, -1.0)
  42493. ];
  42494. return PanoramaToCubeMapTools;
  42495. })();
  42496. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  42497. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42498. })(BABYLON || (BABYLON = {}));
  42499. var BABYLON;
  42500. (function (BABYLON) {
  42501. var Internals;
  42502. (function (Internals) {
  42503. ;
  42504. /**
  42505. * This groups tools to convert HDR texture to native colors array.
  42506. */
  42507. var HDRTools = (function () {
  42508. function HDRTools() {
  42509. }
  42510. HDRTools.Ldexp = function (mantissa, exponent) {
  42511. if (exponent > 1023) {
  42512. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  42513. }
  42514. if (exponent < -1074) {
  42515. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  42516. }
  42517. return mantissa * Math.pow(2, exponent);
  42518. };
  42519. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  42520. if (exponent > 0) {
  42521. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  42522. float32array[index + 0] = red * exponent;
  42523. float32array[index + 1] = green * exponent;
  42524. float32array[index + 2] = blue * exponent;
  42525. }
  42526. else {
  42527. float32array[index + 0] = 0;
  42528. float32array[index + 1] = 0;
  42529. float32array[index + 2] = 0;
  42530. }
  42531. };
  42532. HDRTools.readStringLine = function (uint8array, startIndex) {
  42533. var line = "";
  42534. var character = "";
  42535. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  42536. character = String.fromCharCode(uint8array[i]);
  42537. if (character == "\n") {
  42538. break;
  42539. }
  42540. line += character;
  42541. }
  42542. return line;
  42543. };
  42544. /**
  42545. * Reads header information from an RGBE texture stored in a native array.
  42546. * More information on this format are available here:
  42547. * https://en.wikipedia.org/wiki/RGBE_image_format
  42548. *
  42549. * @param uint8array The binary file stored in native array.
  42550. * @return The header information.
  42551. */
  42552. HDRTools.RGBE_ReadHeader = function (uint8array) {
  42553. var height = 0;
  42554. var width = 0;
  42555. var line = this.readStringLine(uint8array, 0);
  42556. if (line[0] != '#' || line[1] != '?') {
  42557. throw "Bad HDR Format.";
  42558. }
  42559. var endOfHeader = false;
  42560. var findFormat = false;
  42561. var lineIndex = 0;
  42562. do {
  42563. lineIndex += (line.length + 1);
  42564. line = this.readStringLine(uint8array, lineIndex);
  42565. if (line == "FORMAT=32-bit_rle_rgbe") {
  42566. findFormat = true;
  42567. }
  42568. else if (line.length == 0) {
  42569. endOfHeader = true;
  42570. }
  42571. } while (!endOfHeader);
  42572. if (!findFormat) {
  42573. throw "HDR Bad header format, unsupported FORMAT";
  42574. }
  42575. lineIndex += (line.length + 1);
  42576. line = this.readStringLine(uint8array, lineIndex);
  42577. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  42578. var match = sizeRegexp.exec(line);
  42579. // TODO. Support +Y and -X if needed.
  42580. if (match.length < 3) {
  42581. throw "HDR Bad header format, no size";
  42582. }
  42583. width = parseInt(match[2]);
  42584. height = parseInt(match[1]);
  42585. if (width < 8 || width > 0x7fff) {
  42586. throw "HDR Bad header format, unsupported size";
  42587. }
  42588. lineIndex += (line.length + 1);
  42589. return {
  42590. height: height,
  42591. width: width,
  42592. dataPosition: lineIndex
  42593. };
  42594. };
  42595. /**
  42596. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  42597. * This RGBE texture needs to store the information as a panorama.
  42598. *
  42599. * More information on this format are available here:
  42600. * https://en.wikipedia.org/wiki/RGBE_image_format
  42601. *
  42602. * @param buffer The binary file stored in an array buffer.
  42603. * @param size The expected size of the extracted cubemap.
  42604. * @return The Cube Map information.
  42605. */
  42606. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  42607. var uint8array = new Uint8Array(buffer);
  42608. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  42609. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42610. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  42611. return cubeMapData;
  42612. };
  42613. /**
  42614. * Returns the pixels data extracted from an RGBE texture.
  42615. * This pixels will be stored left to right up to down in the R G B order in one array.
  42616. *
  42617. * More information on this format are available here:
  42618. * https://en.wikipedia.org/wiki/RGBE_image_format
  42619. *
  42620. * @param uint8array The binary file stored in an array buffer.
  42621. * @param hdrInfo The header information of the file.
  42622. * @return The pixels data in RGB right to left up to down order.
  42623. */
  42624. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  42625. // Keep for multi format supports.
  42626. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42627. };
  42628. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  42629. var num_scanlines = hdrInfo.height;
  42630. var scanline_width = hdrInfo.width;
  42631. var a, b, c, d, count;
  42632. var dataIndex = hdrInfo.dataPosition;
  42633. var index = 0, endIndex = 0, i = 0;
  42634. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  42635. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  42636. // 3 channels of 4 bytes per pixel in float.
  42637. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  42638. var resultArray = new Float32Array(resultBuffer);
  42639. // read in each successive scanline
  42640. while (num_scanlines > 0) {
  42641. a = uint8array[dataIndex++];
  42642. b = uint8array[dataIndex++];
  42643. c = uint8array[dataIndex++];
  42644. d = uint8array[dataIndex++];
  42645. if (a != 2 || b != 2 || (c & 0x80)) {
  42646. // this file is not run length encoded
  42647. throw "HDR Bad header format, not RLE";
  42648. }
  42649. if (((c << 8) | d) != scanline_width) {
  42650. throw "HDR Bad header format, wrong scan line width";
  42651. }
  42652. index = 0;
  42653. // read each of the four channels for the scanline into the buffer
  42654. for (i = 0; i < 4; i++) {
  42655. endIndex = (i + 1) * scanline_width;
  42656. while (index < endIndex) {
  42657. a = uint8array[dataIndex++];
  42658. b = uint8array[dataIndex++];
  42659. if (a > 128) {
  42660. // a run of the same value
  42661. count = a - 128;
  42662. if ((count == 0) || (count > endIndex - index)) {
  42663. throw "HDR Bad Format, bad scanline data (run)";
  42664. }
  42665. while (count-- > 0) {
  42666. scanLineArray[index++] = b;
  42667. }
  42668. }
  42669. else {
  42670. // a non-run
  42671. count = a;
  42672. if ((count == 0) || (count > endIndex - index)) {
  42673. throw "HDR Bad Format, bad scanline data (non-run)";
  42674. }
  42675. scanLineArray[index++] = b;
  42676. if (--count > 0) {
  42677. for (var j = 0; j < count; j++) {
  42678. scanLineArray[index++] = uint8array[dataIndex++];
  42679. }
  42680. }
  42681. }
  42682. }
  42683. }
  42684. // now convert data from buffer into floats
  42685. for (i = 0; i < scanline_width; i++) {
  42686. a = scanLineArray[i];
  42687. b = scanLineArray[i + scanline_width];
  42688. c = scanLineArray[i + 2 * scanline_width];
  42689. d = scanLineArray[i + 3 * scanline_width];
  42690. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  42691. }
  42692. num_scanlines--;
  42693. }
  42694. return resultArray;
  42695. };
  42696. return HDRTools;
  42697. })();
  42698. Internals.HDRTools = HDRTools;
  42699. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42700. })(BABYLON || (BABYLON = {}));
  42701. //_______________________________________________________________
  42702. // Extracted from CubeMapGen:
  42703. // https://code.google.com/archive/p/cubemapgen/
  42704. //
  42705. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42706. //_______________________________________________________________
  42707. var BABYLON;
  42708. (function (BABYLON) {
  42709. var Internals;
  42710. (function (Internals) {
  42711. /**
  42712. * The bounding box information used during the conversion process.
  42713. */
  42714. var CMGBoundinBox = (function () {
  42715. function CMGBoundinBox() {
  42716. this.min = new BABYLON.Vector3(0, 0, 0);
  42717. this.max = new BABYLON.Vector3(0, 0, 0);
  42718. this.clear();
  42719. }
  42720. CMGBoundinBox.prototype.clear = function () {
  42721. this.min.x = CMGBoundinBox.MAX;
  42722. this.min.y = CMGBoundinBox.MAX;
  42723. this.min.z = CMGBoundinBox.MAX;
  42724. this.max.x = CMGBoundinBox.MIN;
  42725. this.max.y = CMGBoundinBox.MIN;
  42726. this.max.z = CMGBoundinBox.MIN;
  42727. };
  42728. CMGBoundinBox.prototype.augment = function (x, y, z) {
  42729. this.min.x = Math.min(this.min.x, x);
  42730. this.min.y = Math.min(this.min.y, y);
  42731. this.min.z = Math.min(this.min.z, z);
  42732. this.max.x = Math.max(this.max.x, x);
  42733. this.max.y = Math.max(this.max.y, y);
  42734. this.max.z = Math.max(this.max.z, z);
  42735. };
  42736. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  42737. this.min.x = Math.max(this.min.x, x);
  42738. this.min.y = Math.max(this.min.y, y);
  42739. this.min.z = Math.max(this.min.z, z);
  42740. };
  42741. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  42742. this.max.x = Math.min(this.max.x, x);
  42743. this.max.y = Math.min(this.max.y, y);
  42744. this.max.z = Math.min(this.max.z, z);
  42745. };
  42746. CMGBoundinBox.prototype.empty = function () {
  42747. if ((this.min.x > this.max.y) ||
  42748. (this.min.y > this.max.y) ||
  42749. (this.min.z > this.max.y)) {
  42750. return true;
  42751. }
  42752. else {
  42753. return false;
  42754. }
  42755. };
  42756. CMGBoundinBox.MAX = Number.MAX_VALUE;
  42757. CMGBoundinBox.MIN = Number.MIN_VALUE;
  42758. return CMGBoundinBox;
  42759. })();
  42760. /**
  42761. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  42762. * required by the glossinees of a material.
  42763. *
  42764. * This only supports the cosine drop power as well as Warp fixup generation method.
  42765. *
  42766. * This is using the process from CubeMapGen described here:
  42767. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42768. */
  42769. var PMREMGenerator = (function () {
  42770. /**
  42771. * Constructor of the generator.
  42772. *
  42773. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  42774. * @param inputSize The size of the cubemap faces
  42775. * @param outputSize The size of the output cubemap faces
  42776. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  42777. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  42778. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  42779. * @param specularPower The max specular level of the desired cubemap
  42780. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  42781. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  42782. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  42783. */
  42784. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  42785. this.input = input;
  42786. this.inputSize = inputSize;
  42787. this.outputSize = outputSize;
  42788. this.maxNumMipLevels = maxNumMipLevels;
  42789. this.numChannels = numChannels;
  42790. this.isFloat = isFloat;
  42791. this.specularPower = specularPower;
  42792. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  42793. this.excludeBase = excludeBase;
  42794. this.fixup = fixup;
  42795. this._outputSurface = [];
  42796. this._numMipLevels = 0;
  42797. }
  42798. /**
  42799. * Launches the filter process and return the result.
  42800. *
  42801. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  42802. */
  42803. PMREMGenerator.prototype.filterCubeMap = function () {
  42804. // Init cubemap processor
  42805. this.init();
  42806. // Filters the cubemap
  42807. this.filterCubeMapMipChain();
  42808. // Returns the filtered mips.
  42809. return this._outputSurface;
  42810. };
  42811. PMREMGenerator.prototype.init = function () {
  42812. var i;
  42813. var j;
  42814. var mipLevelSize;
  42815. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  42816. if (this.maxNumMipLevels == 0) {
  42817. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  42818. }
  42819. //first miplevel size
  42820. mipLevelSize = this.outputSize;
  42821. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  42822. for (j = 0; j < this.maxNumMipLevels; j++) {
  42823. this._outputSurface.length++;
  42824. this._outputSurface[j] = [];
  42825. //Iterate over faces for output images
  42826. for (i = 0; i < 6; i++) {
  42827. this._outputSurface[j].length++;
  42828. // Initializes a new array for the output.
  42829. if (this.isFloat) {
  42830. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42831. }
  42832. else {
  42833. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42834. }
  42835. }
  42836. //next mip level is half size
  42837. mipLevelSize >>= 1;
  42838. this._numMipLevels++;
  42839. //terminate if mip chain becomes too small
  42840. if (mipLevelSize == 0) {
  42841. this.maxNumMipLevels = j;
  42842. return;
  42843. }
  42844. }
  42845. };
  42846. //--------------------------------------------------------------------------------------
  42847. //Cube map filtering and mip chain generation.
  42848. // the cube map filtereing is specified using a number of parameters:
  42849. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  42850. // indicates the region of the hemisphere to filter over for each tap.
  42851. //
  42852. // Note that the top mip level is also a filtered version of the original input images
  42853. // as well in order to create mip chains for diffuse environment illumination.
  42854. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  42855. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  42856. //
  42857. // Then the mip angle used to genreate the next level of the mip chain from the first level
  42858. // is a_InitialMipAngle
  42859. //
  42860. // The angle for the subsequent levels of the mip chain are specified by their parents
  42861. // filtering angle and a per-level scale and bias
  42862. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  42863. //
  42864. //--------------------------------------------------------------------------------------
  42865. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  42866. // First, take count of the lighting model to modify SpecularPower
  42867. // 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;
  42868. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  42869. //Cone angle start (for generating subsequent mip levels)
  42870. var currentSpecularPower = this.specularPower;
  42871. //Build filter lookup tables based on the source miplevel size
  42872. this.precomputeFilterLookupTables(this.inputSize);
  42873. // Note that we need to filter the first level before generating mipmap
  42874. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  42875. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  42876. // TODO : Write a function to copy and scale the base mipmap in output
  42877. // I am just lazy here and just put a high specular power value, and do some if.
  42878. if (this.excludeBase && (levelIndex == 0)) {
  42879. // 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).
  42880. currentSpecularPower = 100000.0;
  42881. }
  42882. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  42883. var srcCubeImage = this.input;
  42884. var dstCubeImage = this._outputSurface[levelIndex];
  42885. var dstSize = this.outputSize >> levelIndex;
  42886. // Compute required angle.
  42887. var angle = this.getBaseFilterAngle(currentSpecularPower);
  42888. // filter cube surfaces
  42889. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  42890. // fix seams
  42891. if (this.fixup) {
  42892. this.fixupCubeEdges(dstCubeImage, dstSize);
  42893. }
  42894. // Decrease the specular power to generate the mipmap chain
  42895. // TODO : Use another method for Exclude (see first comment at start of the function
  42896. if (this.excludeBase && (levelIndex == 0)) {
  42897. currentSpecularPower = this.specularPower;
  42898. }
  42899. currentSpecularPower *= this.cosinePowerDropPerMip;
  42900. }
  42901. };
  42902. //--------------------------------------------------------------------------------------
  42903. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  42904. // It allow to optimize the texel to access base on the specular power.
  42905. //--------------------------------------------------------------------------------------
  42906. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  42907. // We want to find the alpha such that:
  42908. // cos(alpha)^cosinePower = epsilon
  42909. // That's: acos(epsilon^(1/cosinePower))
  42910. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  42911. var angle = 180.0;
  42912. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  42913. angle *= 180.0 / Math.PI; // Convert to degree
  42914. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  42915. return angle;
  42916. };
  42917. //--------------------------------------------------------------------------------------
  42918. //Builds the following lookup tables prior to filtering:
  42919. // -normalizer cube map
  42920. // -tap weight lookup table
  42921. //
  42922. //--------------------------------------------------------------------------------------
  42923. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  42924. var srcTexelAngle;
  42925. var iCubeFace;
  42926. //clear pre-existing normalizer cube map
  42927. this._normCubeMap = [];
  42928. //Normalized vectors per cubeface and per-texel solid angle
  42929. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  42930. };
  42931. //--------------------------------------------------------------------------------------
  42932. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  42933. //
  42934. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  42935. //
  42936. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  42937. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  42938. // below
  42939. //--------------------------------------------------------------------------------------
  42940. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  42941. var iCubeFace;
  42942. var u;
  42943. var v;
  42944. //iterate over cube faces
  42945. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  42946. //First three channels for norm cube, and last channel for solid angle
  42947. this._normCubeMap.push(new Float32Array(size * size * 4));
  42948. //fast texture walk, build normalizer cube map
  42949. var facesData = this.input[iCubeFace];
  42950. for (v = 0; v < size; v++) {
  42951. for (u = 0; u < size; u++) {
  42952. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  42953. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  42954. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  42955. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  42956. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  42957. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  42958. }
  42959. }
  42960. }
  42961. };
  42962. //--------------------------------------------------------------------------------------
  42963. // Convert cubemap face texel coordinates and face idx to 3D vector
  42964. // note the U and V coords are integer coords and range from 0 to size-1
  42965. // this routine can be used to generate a normalizer cube map
  42966. //--------------------------------------------------------------------------------------
  42967. // SL BEGIN
  42968. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  42969. var nvcU;
  42970. var nvcV;
  42971. var tempVec;
  42972. // Change from original AMD code
  42973. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  42974. // + 0.5f is for texel center addressing
  42975. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  42976. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  42977. // warp fixup
  42978. if (fixup && size > 1) {
  42979. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  42980. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  42981. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  42982. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  42983. }
  42984. // Get current vector
  42985. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  42986. // U contribution
  42987. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  42988. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  42989. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  42990. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  42991. // V contribution and Sum
  42992. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  42993. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  42994. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  42995. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  42996. //add face axis
  42997. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  42998. PMREMGenerator._vectorTemp.x += faceAxis[0];
  42999. PMREMGenerator._vectorTemp.y += faceAxis[1];
  43000. PMREMGenerator._vectorTemp.z += faceAxis[2];
  43001. //normalize vector
  43002. PMREMGenerator._vectorTemp.normalize();
  43003. return PMREMGenerator._vectorTemp;
  43004. };
  43005. //--------------------------------------------------------------------------------------
  43006. // Convert 3D vector to cubemap face texel coordinates and face idx
  43007. // note the U and V coords are integer coords and range from 0 to size-1
  43008. // this routine can be used to generate a normalizer cube map
  43009. //
  43010. // returns face IDX and texel coords
  43011. //--------------------------------------------------------------------------------------
  43012. // SL BEGIN
  43013. /*
  43014. Mapping Texture Coordinates to Cube Map Faces
  43015. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  43016. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  43017. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  43018. map arrangement in Pixar's RenderMan package.
  43019. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  43020. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  43021. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  43022. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  43023. the major axis direction). The target column in the table below explains how the major axis direction
  43024. maps to the 2D image of a particular cube map target.
  43025. major axis
  43026. direction target sc tc ma
  43027. ---------- --------------------------------- --- --- ---
  43028. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  43029. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  43030. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  43031. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  43032. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  43033. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  43034. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  43035. an updated (s,t) is calculated as follows
  43036. s = ( sc/|ma| + 1 ) / 2
  43037. t = ( tc/|ma| + 1 ) / 2
  43038. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  43039. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  43040. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  43041. */
  43042. // Note this method return U and V in range from 0 to size-1
  43043. // SL END
  43044. // Store the information in vector3 for convenience (faceindex, u, v)
  43045. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  43046. var maxCoord;
  43047. var faceIdx;
  43048. //absolute value 3
  43049. var absX = Math.abs(x);
  43050. var absY = Math.abs(y);
  43051. var absZ = Math.abs(z);
  43052. if (absX >= absY && absX >= absZ) {
  43053. maxCoord = absX;
  43054. if (x >= 0) {
  43055. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  43056. }
  43057. else {
  43058. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  43059. }
  43060. }
  43061. else if (absY >= absX && absY >= absZ) {
  43062. maxCoord = absY;
  43063. if (y >= 0) {
  43064. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  43065. }
  43066. else {
  43067. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  43068. }
  43069. }
  43070. else {
  43071. maxCoord = absZ;
  43072. if (z >= 0) {
  43073. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  43074. }
  43075. else {
  43076. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  43077. }
  43078. }
  43079. //divide through by max coord so face vector lies on cube face
  43080. var scale = 1 / maxCoord;
  43081. x *= scale;
  43082. y *= scale;
  43083. z *= scale;
  43084. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  43085. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  43086. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  43087. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  43088. // Modify original AMD code to return value from 0 to Size - 1
  43089. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  43090. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  43091. PMREMGenerator._vectorTemp.x = faceIdx;
  43092. PMREMGenerator._vectorTemp.y = u;
  43093. PMREMGenerator._vectorTemp.z = v;
  43094. return PMREMGenerator._vectorTemp;
  43095. };
  43096. //--------------------------------------------------------------------------------------
  43097. //Original code from Ignacio CastaÒo
  43098. // This formula is from Manne ÷hrstrˆm's thesis.
  43099. // Take two coordiantes in the range [-1, 1] that define a portion of a
  43100. // cube face and return the area of the projection of that portion on the
  43101. // surface of the sphere.
  43102. //--------------------------------------------------------------------------------------
  43103. PMREMGenerator.prototype.areaElement = function (x, y) {
  43104. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  43105. };
  43106. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  43107. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  43108. // (+ 0.5f is for texel center addressing)
  43109. u = (2.0 * (u + 0.5) / size) - 1.0;
  43110. v = (2.0 * (v + 0.5) / size) - 1.0;
  43111. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  43112. var invResolution = 1.0 / size;
  43113. // U and V are the -1..1 texture coordinate on the current face.
  43114. // Get projected area for this texel
  43115. var x0 = u - invResolution;
  43116. var y0 = v - invResolution;
  43117. var x1 = u + invResolution;
  43118. var y1 = v + invResolution;
  43119. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  43120. return solidAngle;
  43121. };
  43122. //--------------------------------------------------------------------------------------
  43123. //The key to the speed of these filtering routines is to quickly define a per-face
  43124. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  43125. // Later these pixels are selectively processed based on their dot products to see if
  43126. // they reside within the filtering cone.
  43127. //
  43128. //This is done by computing the smallest per-texel angle to get a conservative estimate
  43129. // of the number of texels needed to be covered in width and height order to filter the
  43130. // region. the bounding box for the center taps face is defined first, and if the
  43131. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  43132. // defined next
  43133. //--------------------------------------------------------------------------------------
  43134. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  43135. // note that pixels within these regions may be rejected
  43136. // based on the anlge
  43137. var iCubeFace;
  43138. var u;
  43139. var v;
  43140. // bounding box per face to specify region to process
  43141. var filterExtents = [];
  43142. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43143. filterExtents.push(new CMGBoundinBox());
  43144. }
  43145. // min angle a src texel can cover (in degrees)
  43146. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  43147. // angle about center tap to define filter cone
  43148. // filter angle is 1/2 the cone angle
  43149. var filterAngle = filterConeAngle / 2.0;
  43150. //ensure filter angle is larger than a texel
  43151. if (filterAngle < srcTexelAngle) {
  43152. filterAngle = srcTexelAngle;
  43153. }
  43154. //ensure filter cone is always smaller than the hemisphere
  43155. if (filterAngle > 90.0) {
  43156. filterAngle = 90.0;
  43157. }
  43158. // the maximum number of texels in 1D the filter cone angle will cover
  43159. // used to determine bounding box size for filter extents
  43160. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  43161. // ensure conservative region always covers at least one texel
  43162. if (filterSize < 1) {
  43163. filterSize = 1;
  43164. }
  43165. // dotProdThresh threshold based on cone angle to determine whether or not taps
  43166. // reside within the cone angle
  43167. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  43168. // process required faces
  43169. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43170. //iterate over dst cube map face texel
  43171. for (v = 0; v < dstSize; v++) {
  43172. for (u = 0; u < dstSize; u++) {
  43173. //get center tap direction
  43174. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  43175. //clear old per-face filter extents
  43176. this.clearFilterExtents(filterExtents);
  43177. //define per-face filter extents
  43178. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  43179. //perform filtering of src faces using filter extents
  43180. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  43181. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  43182. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  43183. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  43184. }
  43185. }
  43186. }
  43187. };
  43188. //--------------------------------------------------------------------------------------
  43189. //Clear filter extents for the 6 cube map faces
  43190. //--------------------------------------------------------------------------------------
  43191. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  43192. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  43193. filterExtents[iCubeFaces].clear();
  43194. }
  43195. };
  43196. //--------------------------------------------------------------------------------------
  43197. //Define per-face bounding box filter extents
  43198. //
  43199. // These define conservative texel regions in each of the faces the filter can possibly
  43200. // process. When the pixels in the regions are actually processed, the dot product
  43201. // between the tap vector and the center tap vector is used to determine the weight of
  43202. // the tap and whether or not the tap is within the cone.
  43203. //
  43204. //--------------------------------------------------------------------------------------
  43205. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  43206. //neighboring face and bleed over amount, and width of BBOX for
  43207. // left, right, top, and bottom edges of this face
  43208. var bleedOverAmount = [0, 0, 0, 0];
  43209. var bleedOverBBoxMin = [0, 0, 0, 0];
  43210. var bleedOverBBoxMax = [0, 0, 0, 0];
  43211. var neighborFace;
  43212. var neighborEdge;
  43213. var oppositeFaceIdx;
  43214. //get face idx, and u, v info from center tap dir
  43215. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  43216. var faceIdx = result.x;
  43217. var u = result.y;
  43218. var v = result.z;
  43219. //define bbox size within face
  43220. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  43221. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  43222. filterExtents[faceIdx].clampMin(0, 0, 0);
  43223. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  43224. //u and v extent in face corresponding to center tap
  43225. var minU = filterExtents[faceIdx].min.x;
  43226. var minV = filterExtents[faceIdx].min.y;
  43227. var maxU = filterExtents[faceIdx].max.x;
  43228. var maxV = filterExtents[faceIdx].max.y;
  43229. //bleed over amounts for face across u=0 edge (left)
  43230. bleedOverAmount[0] = (bboxSize - u);
  43231. bleedOverBBoxMin[0] = minV;
  43232. bleedOverBBoxMax[0] = maxV;
  43233. //bleed over amounts for face across u=1 edge (right)
  43234. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  43235. bleedOverBBoxMin[1] = minV;
  43236. bleedOverBBoxMax[1] = maxV;
  43237. //bleed over to face across v=0 edge (up)
  43238. bleedOverAmount[2] = (bboxSize - v);
  43239. bleedOverBBoxMin[2] = minU;
  43240. bleedOverBBoxMax[2] = maxU;
  43241. //bleed over to face across v=1 edge (down)
  43242. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  43243. bleedOverBBoxMin[3] = minU;
  43244. bleedOverBBoxMax[3] = maxU;
  43245. //compute bleed over regions in neighboring faces
  43246. for (var i = 0; i < 4; i++) {
  43247. if (bleedOverAmount[i] > 0) {
  43248. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  43249. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  43250. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  43251. // be flipped: the cases are
  43252. // if a left edge mates with a left or bottom edge on the neighbor
  43253. // if a top edge mates with a top or right edge on the neighbor
  43254. // if a right edge mates with a right or top edge on the neighbor
  43255. // if a bottom edge mates with a bottom or left edge on the neighbor
  43256. //Seeing as the edges are enumerated as follows
  43257. // left =0
  43258. // right =1
  43259. // top =2
  43260. // bottom =3
  43261. //
  43262. // so if the edge enums are the same, or the sum of the enums == 3,
  43263. // the bbox needs to be flipped
  43264. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  43265. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  43266. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  43267. }
  43268. //The way the bounding box is extended onto the neighboring face
  43269. // depends on which edge of neighboring face abuts with this one
  43270. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  43271. case PMREMGenerator.CP_EDGE_LEFT:
  43272. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  43273. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43274. break;
  43275. case PMREMGenerator.CP_EDGE_RIGHT:
  43276. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  43277. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43278. break;
  43279. case PMREMGenerator.CP_EDGE_TOP:
  43280. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  43281. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  43282. break;
  43283. case PMREMGenerator.CP_EDGE_BOTTOM:
  43284. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  43285. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  43286. break;
  43287. }
  43288. //clamp filter extents in non-center tap faces to remain within surface
  43289. filterExtents[neighborFace].clampMin(0, 0, 0);
  43290. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  43291. }
  43292. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  43293. // from the center tap face, then process the opposite face entirely for now.
  43294. //Note that the cases in which this happens, what usually happens is that
  43295. // more than one edge bleeds onto the opposite face, and the bounding box
  43296. // encompasses the entire cube map face.
  43297. if (bleedOverAmount[i] > srcSize) {
  43298. //determine opposite face
  43299. switch (faceIdx) {
  43300. case PMREMGenerator.CP_FACE_X_POS:
  43301. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  43302. break;
  43303. case PMREMGenerator.CP_FACE_X_NEG:
  43304. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  43305. break;
  43306. case PMREMGenerator.CP_FACE_Y_POS:
  43307. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  43308. break;
  43309. case PMREMGenerator.CP_FACE_Y_NEG:
  43310. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  43311. break;
  43312. case PMREMGenerator.CP_FACE_Z_POS:
  43313. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  43314. break;
  43315. case PMREMGenerator.CP_FACE_Z_NEG:
  43316. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  43317. break;
  43318. default:
  43319. break;
  43320. }
  43321. //just encompass entire face for now
  43322. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  43323. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  43324. }
  43325. }
  43326. };
  43327. //--------------------------------------------------------------------------------------
  43328. //ProcessFilterExtents
  43329. // Process bounding box in each cube face
  43330. //
  43331. //--------------------------------------------------------------------------------------
  43332. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  43333. //accumulators are 64-bit floats in order to have the precision needed
  43334. // over a summation of a large number of pixels
  43335. var dstAccum = [0, 0, 0, 0];
  43336. var weightAccum = 0;
  43337. var k = 0;
  43338. var nSrcChannels = this.numChannels;
  43339. // norm cube map and srcCubeMap have same face width
  43340. var faceWidth = srcSize;
  43341. //amount to add to pointer to move to next scanline in images
  43342. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  43343. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  43344. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  43345. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  43346. // iterate over cubefaces
  43347. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  43348. //if bbox is non empty
  43349. if (!filterExtents[iFaceIdx].empty()) {
  43350. var uStart = filterExtents[iFaceIdx].min.x;
  43351. var vStart = filterExtents[iFaceIdx].min.y;
  43352. var uEnd = filterExtents[iFaceIdx].max.x;
  43353. var vEnd = filterExtents[iFaceIdx].max.y;
  43354. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  43355. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  43356. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  43357. for (var v = vStart; v <= vEnd; v++) {
  43358. var normCubeRowWalk = 0;
  43359. var srcCubeRowWalk = 0;
  43360. for (var u = uStart; u <= uEnd; u++) {
  43361. //pointer to direction in cube map associated with texel
  43362. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  43363. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  43364. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  43365. //check dot product to see if texel is within cone
  43366. var tapDotProd = texelVectX * centerTapDir.x +
  43367. texelVectY * centerTapDir.y +
  43368. texelVectZ * centerTapDir.z;
  43369. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  43370. //solid angle stored in 4th channel of normalizer/solid angle cube map
  43371. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  43372. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  43373. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  43374. // so just adding one to specularpower do the trick.
  43375. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  43376. //iterate over channels
  43377. for (k = 0; k < nSrcChannels; k++) {
  43378. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  43379. srcCubeRowWalk++;
  43380. }
  43381. weightAccum += weight; //accumulate weight
  43382. }
  43383. else {
  43384. //step across source pixel
  43385. srcCubeRowWalk += nSrcChannels;
  43386. }
  43387. normCubeRowWalk += 4; // 4 channels per norm cube map.
  43388. }
  43389. startIndexNormCubeMap += normCubePitch;
  43390. startIndexSrcCubeMap += srcCubePitch;
  43391. }
  43392. }
  43393. }
  43394. //divide through by weights if weight is non zero
  43395. if (weightAccum != 0.0) {
  43396. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  43397. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  43398. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  43399. if (this.numChannels > 3) {
  43400. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  43401. }
  43402. }
  43403. else {
  43404. // otherwise sample nearest
  43405. // get face idx and u, v texel coordinate in face
  43406. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  43407. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  43408. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  43409. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  43410. if (this.numChannels > 3) {
  43411. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  43412. }
  43413. }
  43414. return PMREMGenerator._vectorTemp;
  43415. };
  43416. //--------------------------------------------------------------------------------------
  43417. // Fixup cube edges
  43418. //
  43419. // average texels on cube map faces across the edges
  43420. // WARP/BENT Method Only.
  43421. //--------------------------------------------------------------------------------------
  43422. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  43423. var k;
  43424. var j;
  43425. var i;
  43426. var iFace;
  43427. var iCorner = 0;
  43428. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  43429. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  43430. // note that if functionality to filter across the three texels for each corner, then
  43431. //indexed by corner and face idx. the array contains the face the start points belongs to.
  43432. var cornerPtr = [
  43433. [[], [], []],
  43434. [[], [], []],
  43435. [[], [], []],
  43436. [[], [], []],
  43437. [[], [], []],
  43438. [[], [], []],
  43439. [[], [], []],
  43440. [[], [], []]
  43441. ];
  43442. //if there is no fixup, or fixup width = 0, do nothing
  43443. if (cubeMapSize < 1) {
  43444. return;
  43445. }
  43446. //special case 1x1 cubemap, average face colors
  43447. if (cubeMapSize == 1) {
  43448. //iterate over channels
  43449. for (k = 0; k < this.numChannels; k++) {
  43450. var accum = 0.0;
  43451. //iterate over faces to accumulate face colors
  43452. for (iFace = 0; iFace < 6; iFace++) {
  43453. accum += cubeMap[iFace][k];
  43454. }
  43455. //compute average over 6 face colors
  43456. accum /= 6.0;
  43457. //iterate over faces to distribute face colors
  43458. for (iFace = 0; iFace < 6; iFace++) {
  43459. cubeMap[iFace][k] = accum;
  43460. }
  43461. }
  43462. return;
  43463. }
  43464. //iterate over faces to collect list of corner texel pointers
  43465. for (iFace = 0; iFace < 6; iFace++) {
  43466. //the 4 corner pointers for this face
  43467. faceCornerStartIndicies[0] = [iFace, 0];
  43468. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  43469. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  43470. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  43471. //iterate over face corners to collect cube corner pointers
  43472. for (iCorner = 0; iCorner < 4; iCorner++) {
  43473. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  43474. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  43475. cornerNumPtrs[corner]++;
  43476. }
  43477. }
  43478. //iterate over corners to average across corner tap values
  43479. for (iCorner = 0; iCorner < 8; iCorner++) {
  43480. for (k = 0; k < this.numChannels; k++) {
  43481. var cornerTapAccum = 0.0;
  43482. //iterate over corner texels and average results
  43483. for (i = 0; i < 3; i++) {
  43484. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  43485. }
  43486. //divide by 3 to compute average of corner tap values
  43487. cornerTapAccum *= (1.0 / 3.0);
  43488. //iterate over corner texels and average results
  43489. for (i = 0; i < 3; i++) {
  43490. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  43491. }
  43492. }
  43493. }
  43494. //iterate over the twelve edges of the cube to average across edges
  43495. for (i = 0; i < 12; i++) {
  43496. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  43497. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  43498. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  43499. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  43500. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  43501. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  43502. var edgeWalk = 0;
  43503. var neighborEdgeWalk = 0;
  43504. //Determine walking pointers based on edge type
  43505. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  43506. switch (edge) {
  43507. case PMREMGenerator.CP_EDGE_LEFT:
  43508. // no change to faceEdgeStartPtr
  43509. edgeWalk = this.numChannels * cubeMapSize;
  43510. break;
  43511. case PMREMGenerator.CP_EDGE_RIGHT:
  43512. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43513. edgeWalk = this.numChannels * cubeMapSize;
  43514. break;
  43515. case PMREMGenerator.CP_EDGE_TOP:
  43516. // no change to faceEdgeStartPtr
  43517. edgeWalk = this.numChannels;
  43518. break;
  43519. case PMREMGenerator.CP_EDGE_BOTTOM:
  43520. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43521. edgeWalk = this.numChannels;
  43522. break;
  43523. }
  43524. //For certain types of edge abutments, the neighbor edge walk needs to
  43525. // be flipped: the cases are
  43526. // if a left edge mates with a left or bottom edge on the neighbor
  43527. // if a top edge mates with a top or right edge on the neighbor
  43528. // if a right edge mates with a right or top edge on the neighbor
  43529. // if a bottom edge mates with a bottom or left edge on the neighbor
  43530. //Seeing as the edges are enumerated as follows
  43531. // left =0
  43532. // right =1
  43533. // top =2
  43534. // bottom =3
  43535. //
  43536. //If the edge enums are the same, or the sum of the enums == 3,
  43537. // the neighbor edge walk needs to be flipped
  43538. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  43539. switch (neighborEdge) {
  43540. case PMREMGenerator.CP_EDGE_LEFT:
  43541. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  43542. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43543. break;
  43544. case PMREMGenerator.CP_EDGE_RIGHT:
  43545. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43546. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43547. break;
  43548. case PMREMGenerator.CP_EDGE_TOP:
  43549. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43550. neighborEdgeWalk = -this.numChannels;
  43551. break;
  43552. case PMREMGenerator.CP_EDGE_BOTTOM:
  43553. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43554. neighborEdgeWalk = -this.numChannels;
  43555. break;
  43556. }
  43557. }
  43558. else {
  43559. //swapped direction neighbor edge walk
  43560. switch (neighborEdge) {
  43561. case PMREMGenerator.CP_EDGE_LEFT:
  43562. //no change to neighborEdgeStartPtr for this case since it points
  43563. // to the upper left corner already
  43564. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43565. break;
  43566. case PMREMGenerator.CP_EDGE_RIGHT:
  43567. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43568. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43569. break;
  43570. case PMREMGenerator.CP_EDGE_TOP:
  43571. //no change to neighborEdgeStartPtr for this case since it points
  43572. // to the upper left corner already
  43573. neighborEdgeWalk = this.numChannels;
  43574. break;
  43575. case PMREMGenerator.CP_EDGE_BOTTOM:
  43576. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43577. neighborEdgeWalk = this.numChannels;
  43578. break;
  43579. }
  43580. }
  43581. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  43582. //nearby neighborhood
  43583. //step ahead one texel on edge
  43584. edgeStartIndex += edgeWalk;
  43585. neighborEdgeStartIndex += neighborEdgeWalk;
  43586. // note that this loop does not process the corner texels, since they have already been
  43587. // averaged across faces across earlier
  43588. for (j = 1; j < (cubeMapSize - 1); j++) {
  43589. //for each set of taps along edge, average them
  43590. // and rewrite the results into the edges
  43591. for (k = 0; k < this.numChannels; k++) {
  43592. var edgeTap = cubeMap[face][edgeStartIndex + k];
  43593. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  43594. //compute average of tap intensity values
  43595. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  43596. //propagate average of taps to edge taps
  43597. cubeMap[face][edgeStartIndex + k] = avgTap;
  43598. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  43599. }
  43600. edgeStartIndex += edgeWalk;
  43601. neighborEdgeStartIndex += neighborEdgeWalk;
  43602. }
  43603. }
  43604. };
  43605. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  43606. PMREMGenerator.CP_UDIR = 0;
  43607. PMREMGenerator.CP_VDIR = 1;
  43608. PMREMGenerator.CP_FACEAXIS = 2;
  43609. //used to index cube faces
  43610. PMREMGenerator.CP_FACE_X_POS = 0;
  43611. PMREMGenerator.CP_FACE_X_NEG = 1;
  43612. PMREMGenerator.CP_FACE_Y_POS = 2;
  43613. PMREMGenerator.CP_FACE_Y_NEG = 3;
  43614. PMREMGenerator.CP_FACE_Z_POS = 4;
  43615. PMREMGenerator.CP_FACE_Z_NEG = 5;
  43616. //used to index image edges
  43617. // NOTE.. the actual number corresponding to the edge is important
  43618. // do not change these, or the code will break
  43619. //
  43620. // CP_EDGE_LEFT is u = 0
  43621. // CP_EDGE_RIGHT is u = width-1
  43622. // CP_EDGE_TOP is v = 0
  43623. // CP_EDGE_BOTTOM is v = height-1
  43624. PMREMGenerator.CP_EDGE_LEFT = 0;
  43625. PMREMGenerator.CP_EDGE_RIGHT = 1;
  43626. PMREMGenerator.CP_EDGE_TOP = 2;
  43627. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  43628. //corners of CUBE map (P or N specifys if it corresponds to the
  43629. // positive or negative direction each of X, Y, and Z
  43630. PMREMGenerator.CP_CORNER_NNN = 0;
  43631. PMREMGenerator.CP_CORNER_NNP = 1;
  43632. PMREMGenerator.CP_CORNER_NPN = 2;
  43633. PMREMGenerator.CP_CORNER_NPP = 3;
  43634. PMREMGenerator.CP_CORNER_PNN = 4;
  43635. PMREMGenerator.CP_CORNER_PNP = 5;
  43636. PMREMGenerator.CP_CORNER_PPN = 6;
  43637. PMREMGenerator.CP_CORNER_PPP = 7;
  43638. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  43639. //3x2 matrices that map cube map indexing vectors in 3d
  43640. // (after face selection and divide through by the
  43641. // _ABSOLUTE VALUE_ of the max coord)
  43642. // into NVC space
  43643. //Note this currently assumes the D3D cube face ordering and orientation
  43644. PMREMGenerator._sgFace2DMapping = [
  43645. //XPOS face
  43646. [[0, 0, -1],
  43647. [0, -1, 0],
  43648. [1, 0, 0]],
  43649. //XNEG face
  43650. [[0, 0, 1],
  43651. [0, -1, 0],
  43652. [-1, 0, 0]],
  43653. //YPOS face
  43654. [[1, 0, 0],
  43655. [0, 0, 1],
  43656. [0, 1, 0]],
  43657. //YNEG face
  43658. [[1, 0, 0],
  43659. [0, 0, -1],
  43660. [0, -1, 0]],
  43661. //ZPOS face
  43662. [[1, 0, 0],
  43663. [0, -1, 0],
  43664. [0, 0, 1]],
  43665. //ZNEG face
  43666. [[-1, 0, 0],
  43667. [0, -1, 0],
  43668. [0, 0, -1]],
  43669. ];
  43670. //------------------------------------------------------------------------------
  43671. // D3D cube map face specification
  43672. // mapping from 3D x,y,z cube map lookup coordinates
  43673. // to 2D within face u,v coordinates
  43674. //
  43675. // --------------------> U direction
  43676. // | (within-face texture space)
  43677. // | _____
  43678. // | | |
  43679. // | | +Y |
  43680. // | _____|_____|_____ _____
  43681. // | | | | | |
  43682. // | | -X | +Z | +X | -Z |
  43683. // | |_____|_____|_____|_____|
  43684. // | | |
  43685. // | | -Y |
  43686. // | |_____|
  43687. // |
  43688. // v V direction
  43689. // (within-face texture space)
  43690. //------------------------------------------------------------------------------
  43691. //Information about neighbors and how texture coorrdinates change across faces
  43692. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  43693. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  43694. //Note this currently assumes the D3D cube face ordering and orientation
  43695. PMREMGenerator._sgCubeNgh = [
  43696. //XPOS face
  43697. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43698. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43699. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43700. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  43701. //XNEG face
  43702. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43703. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  43704. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  43705. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  43706. //YPOS face
  43707. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43708. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43709. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43710. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  43711. //YNEG face
  43712. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43713. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43714. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43715. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  43716. //ZPOS face
  43717. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43718. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43719. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43720. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  43721. //ZNEG face
  43722. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43723. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43724. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  43725. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  43726. ];
  43727. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  43728. // this table is used to average over the edges.
  43729. PMREMGenerator._sgCubeEdgeList = [
  43730. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43731. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43732. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43733. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43734. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43735. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43736. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43737. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43738. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  43739. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43740. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43741. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  43742. ];
  43743. //Information about which of the 8 cube corners are correspond to the
  43744. // the 4 corners in each cube face
  43745. // the order is upper left, upper right, lower left, lower right
  43746. PMREMGenerator._sgCubeCornerList = [
  43747. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  43748. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  43749. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  43750. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  43751. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  43752. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  43753. ];
  43754. return PMREMGenerator;
  43755. })();
  43756. Internals.PMREMGenerator = PMREMGenerator;
  43757. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43758. })(BABYLON || (BABYLON = {}));
  43759. var BABYLON;
  43760. (function (BABYLON) {
  43761. /**
  43762. * This represents a texture coming from an HDR input.
  43763. *
  43764. * The only supported format is currently panorama picture stored in RGBE format.
  43765. * Example of such files can be found on HDRLib: http://hdrlib.com/
  43766. */
  43767. var HDRCubeTexture = (function (_super) {
  43768. __extends(HDRCubeTexture, _super);
  43769. /**
  43770. * Instantiates an HDRTexture from the following parameters.
  43771. *
  43772. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  43773. * @param scene The scene the texture will be used in
  43774. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  43775. * @param noMipmap Forces to not generate the mipmap if true
  43776. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  43777. * @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)
  43778. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  43779. */
  43780. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  43781. if (noMipmap === void 0) { noMipmap = false; }
  43782. if (generateHarmonics === void 0) { generateHarmonics = true; }
  43783. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  43784. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  43785. _super.call(this, scene);
  43786. this._useInGammaSpace = false;
  43787. this._generateHarmonics = true;
  43788. /**
  43789. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  43790. */
  43791. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  43792. /**
  43793. * The spherical polynomial data extracted from the texture.
  43794. */
  43795. this.sphericalPolynomial = null;
  43796. /**
  43797. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  43798. * This is usefull at run time to apply the good shader.
  43799. */
  43800. this.isPMREM = false;
  43801. this.name = url;
  43802. this.url = url;
  43803. this._noMipmap = noMipmap;
  43804. this.hasAlpha = false;
  43805. this._size = size;
  43806. this._useInGammaSpace = useInGammaSpace;
  43807. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  43808. this.isPMREM = this._usePMREMGenerator;
  43809. if (!url) {
  43810. return;
  43811. }
  43812. this._texture = this._getFromCache(url, noMipmap);
  43813. if (!this._texture) {
  43814. if (!scene.useDelayedTextureLoading) {
  43815. this.loadTexture();
  43816. }
  43817. else {
  43818. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  43819. }
  43820. }
  43821. this.isCube = true;
  43822. this._textureMatrix = BABYLON.Matrix.Identity();
  43823. }
  43824. HDRCubeTexture.prototype.loadTexture = function () {
  43825. var _this = this;
  43826. var callback = function (buffer) {
  43827. // Extract the raw linear data.
  43828. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  43829. // Generate harmonics if needed.
  43830. if (_this._generateHarmonics) {
  43831. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  43832. }
  43833. var results = [];
  43834. var byteArray = null;
  43835. // Create uintarray fallback.
  43836. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  43837. // 3 channels of 1 bytes per pixel in bytes.
  43838. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  43839. byteArray = new Uint8Array(byteBuffer);
  43840. }
  43841. // Push each faces.
  43842. for (var j = 0; j < 6; j++) {
  43843. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  43844. // If special cases.
  43845. if (_this._useInGammaSpace || byteArray) {
  43846. for (var i = 0; i < _this._size * _this._size; i++) {
  43847. // Put in gamma space if requested.
  43848. if (_this._useInGammaSpace) {
  43849. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  43850. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  43851. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  43852. }
  43853. // Convert to int texture for fallback.
  43854. if (byteArray) {
  43855. // R
  43856. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  43857. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  43858. // G
  43859. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  43860. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  43861. // B
  43862. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  43863. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  43864. }
  43865. }
  43866. }
  43867. results.push(dataFace);
  43868. }
  43869. return results;
  43870. };
  43871. var mipmapGenerator = null;
  43872. if (!this._noMipmap && this._usePMREMGenerator) {
  43873. mipmapGenerator = function (data) {
  43874. // Custom setup of the generator matching with the PBR shader values.
  43875. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  43876. return generator.filterCubeMap();
  43877. };
  43878. }
  43879. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  43880. };
  43881. HDRCubeTexture.prototype.clone = function () {
  43882. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  43883. // Base texture
  43884. newTexture.level = this.level;
  43885. newTexture.wrapU = this.wrapU;
  43886. newTexture.wrapV = this.wrapV;
  43887. newTexture.coordinatesIndex = this.coordinatesIndex;
  43888. newTexture.coordinatesMode = this.coordinatesMode;
  43889. return newTexture;
  43890. };
  43891. // Methods
  43892. HDRCubeTexture.prototype.delayLoad = function () {
  43893. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  43894. return;
  43895. }
  43896. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  43897. this._texture = this._getFromCache(this.url, this._noMipmap);
  43898. if (!this._texture) {
  43899. this.loadTexture();
  43900. }
  43901. };
  43902. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  43903. return this._textureMatrix;
  43904. };
  43905. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  43906. var texture = null;
  43907. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  43908. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  43909. texture.name = parsedTexture.name;
  43910. texture.hasAlpha = parsedTexture.hasAlpha;
  43911. texture.level = parsedTexture.level;
  43912. texture.coordinatesMode = parsedTexture.coordinatesMode;
  43913. }
  43914. return texture;
  43915. };
  43916. HDRCubeTexture.prototype.serialize = function () {
  43917. if (!this.name) {
  43918. return null;
  43919. }
  43920. var serializationObject = {};
  43921. serializationObject.name = this.name;
  43922. serializationObject.hasAlpha = this.hasAlpha;
  43923. serializationObject.isCube = true;
  43924. serializationObject.level = this.level;
  43925. serializationObject.size = this._size;
  43926. serializationObject.coordinatesMode = this.coordinatesMode;
  43927. serializationObject.useInGammaSpace = this._useInGammaSpace;
  43928. serializationObject.generateHarmonics = this._generateHarmonics;
  43929. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  43930. return serializationObject;
  43931. };
  43932. HDRCubeTexture._facesMapping = [
  43933. "right",
  43934. "up",
  43935. "front",
  43936. "left",
  43937. "down",
  43938. "back"
  43939. ];
  43940. return HDRCubeTexture;
  43941. })(BABYLON.BaseTexture);
  43942. BABYLON.HDRCubeTexture = HDRCubeTexture;
  43943. })(BABYLON || (BABYLON = {}));
  43944. var BABYLON;
  43945. (function (BABYLON) {
  43946. var Debug;
  43947. (function (Debug) {
  43948. /**
  43949. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  43950. */
  43951. var SkeletonViewer = (function () {
  43952. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  43953. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  43954. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  43955. this.skeleton = skeleton;
  43956. this.mesh = mesh;
  43957. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  43958. this.renderingGroupId = renderingGroupId;
  43959. this.color = BABYLON.Color3.White();
  43960. this._debugLines = [];
  43961. this._isEnabled = false;
  43962. this._scene = scene;
  43963. this.update();
  43964. this._renderFunction = this.update.bind(this);
  43965. }
  43966. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  43967. get: function () {
  43968. return this._isEnabled;
  43969. },
  43970. set: function (value) {
  43971. if (this._isEnabled === value) {
  43972. return;
  43973. }
  43974. this._isEnabled = value;
  43975. if (value) {
  43976. this._scene.registerBeforeRender(this._renderFunction);
  43977. }
  43978. else {
  43979. this._scene.unregisterBeforeRender(this._renderFunction);
  43980. }
  43981. },
  43982. enumerable: true,
  43983. configurable: true
  43984. });
  43985. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  43986. if (x === void 0) { x = 0; }
  43987. if (y === void 0) { y = 0; }
  43988. if (z === void 0) { z = 0; }
  43989. var tmat = BABYLON.Tmp.Matrix[0];
  43990. var parentBone = bone.getParent();
  43991. tmat.copyFrom(bone.getLocalMatrix());
  43992. if (x !== 0 || y !== 0 || z !== 0) {
  43993. var tmat2 = BABYLON.Tmp.Matrix[1];
  43994. BABYLON.Matrix.IdentityToRef(tmat2);
  43995. tmat2.m[12] = x;
  43996. tmat2.m[13] = y;
  43997. tmat2.m[14] = z;
  43998. tmat2.multiplyToRef(tmat, tmat);
  43999. }
  44000. if (parentBone) {
  44001. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  44002. }
  44003. tmat.multiplyToRef(meshMat, tmat);
  44004. position.x = tmat.m[12];
  44005. position.y = tmat.m[13];
  44006. position.z = tmat.m[14];
  44007. };
  44008. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  44009. var len = bones.length;
  44010. for (var i = 0; i < len; i++) {
  44011. var bone = bones[i];
  44012. var points = this._debugLines[i];
  44013. if (!points) {
  44014. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44015. this._debugLines[i] = points;
  44016. }
  44017. this._getBonePosition(points[0], bone, meshMat);
  44018. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  44019. }
  44020. };
  44021. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  44022. var len = bones.length;
  44023. var boneNum = 0;
  44024. for (var i = len - 1; i >= 0; i--) {
  44025. var childBone = bones[i];
  44026. var parentBone = childBone.getParent();
  44027. if (!parentBone) {
  44028. continue;
  44029. }
  44030. var points = this._debugLines[boneNum];
  44031. if (!points) {
  44032. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44033. this._debugLines[boneNum] = points;
  44034. }
  44035. this._getBonePosition(points[0], childBone, meshMat);
  44036. this._getBonePosition(points[1], parentBone, meshMat);
  44037. boneNum++;
  44038. }
  44039. };
  44040. SkeletonViewer.prototype.update = function () {
  44041. if (this.autoUpdateBonesMatrices) {
  44042. this._updateBoneMatrix(this.skeleton.bones[0]);
  44043. }
  44044. if (this.skeleton.bones[0].length === undefined) {
  44045. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44046. }
  44047. else {
  44048. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44049. }
  44050. if (!this._debugMesh) {
  44051. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  44052. this._debugMesh.renderingGroupId = this.renderingGroupId;
  44053. }
  44054. else {
  44055. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  44056. }
  44057. this._debugMesh.color = this.color;
  44058. };
  44059. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  44060. if (bone.getParent()) {
  44061. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  44062. }
  44063. var children = bone.children;
  44064. var len = children.length;
  44065. for (var i = 0; i < len; i++) {
  44066. this._updateBoneMatrix(children[i]);
  44067. }
  44068. };
  44069. SkeletonViewer.prototype.dispose = function () {
  44070. if (this._debugMesh) {
  44071. this.isEnabled = false;
  44072. this._debugMesh.dispose();
  44073. this._debugMesh = null;
  44074. }
  44075. };
  44076. return SkeletonViewer;
  44077. })();
  44078. Debug.SkeletonViewer = SkeletonViewer;
  44079. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44080. })(BABYLON || (BABYLON = {}));
  44081. var BABYLON;
  44082. (function (BABYLON) {
  44083. var maxSimultaneousLights = 4;
  44084. var PBRMaterialDefines = (function (_super) {
  44085. __extends(PBRMaterialDefines, _super);
  44086. function PBRMaterialDefines() {
  44087. _super.call(this);
  44088. this.ALBEDO = false;
  44089. this.AMBIENT = false;
  44090. this.OPACITY = false;
  44091. this.OPACITYRGB = false;
  44092. this.REFLECTION = false;
  44093. this.EMISSIVE = false;
  44094. this.REFLECTIVITY = false;
  44095. this.BUMP = false;
  44096. this.PARALLAX = false;
  44097. this.PARALLAXOCCLUSION = false;
  44098. this.SPECULAROVERALPHA = false;
  44099. this.CLIPPLANE = false;
  44100. this.ALPHATEST = false;
  44101. this.ALPHAFROMALBEDO = false;
  44102. this.POINTSIZE = false;
  44103. this.FOG = false;
  44104. this.LIGHT0 = false;
  44105. this.LIGHT1 = false;
  44106. this.LIGHT2 = false;
  44107. this.LIGHT3 = false;
  44108. this.SPOTLIGHT0 = false;
  44109. this.SPOTLIGHT1 = false;
  44110. this.SPOTLIGHT2 = false;
  44111. this.SPOTLIGHT3 = false;
  44112. this.HEMILIGHT0 = false;
  44113. this.HEMILIGHT1 = false;
  44114. this.HEMILIGHT2 = false;
  44115. this.HEMILIGHT3 = false;
  44116. this.POINTLIGHT0 = false;
  44117. this.POINTLIGHT1 = false;
  44118. this.POINTLIGHT2 = false;
  44119. this.POINTLIGHT3 = false;
  44120. this.DIRLIGHT0 = false;
  44121. this.DIRLIGHT1 = false;
  44122. this.DIRLIGHT2 = false;
  44123. this.DIRLIGHT3 = false;
  44124. this.SPECULARTERM = false;
  44125. this.SHADOW0 = false;
  44126. this.SHADOW1 = false;
  44127. this.SHADOW2 = false;
  44128. this.SHADOW3 = false;
  44129. this.SHADOWS = false;
  44130. this.SHADOWVSM0 = false;
  44131. this.SHADOWVSM1 = false;
  44132. this.SHADOWVSM2 = false;
  44133. this.SHADOWVSM3 = false;
  44134. this.SHADOWPCF0 = false;
  44135. this.SHADOWPCF1 = false;
  44136. this.SHADOWPCF2 = false;
  44137. this.SHADOWPCF3 = false;
  44138. this.OPACITYFRESNEL = false;
  44139. this.EMISSIVEFRESNEL = false;
  44140. this.FRESNEL = false;
  44141. this.NORMAL = false;
  44142. this.UV1 = false;
  44143. this.UV2 = false;
  44144. this.VERTEXCOLOR = false;
  44145. this.VERTEXALPHA = false;
  44146. this.NUM_BONE_INFLUENCERS = 0;
  44147. this.BonesPerMesh = 0;
  44148. this.INSTANCES = false;
  44149. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44150. this.MICROSURFACEAUTOMATIC = false;
  44151. this.EMISSIVEASILLUMINATION = false;
  44152. this.LINKEMISSIVEWITHALBEDO = false;
  44153. this.LIGHTMAP = false;
  44154. this.USELIGHTMAPASSHADOWMAP = false;
  44155. this.REFLECTIONMAP_3D = false;
  44156. this.REFLECTIONMAP_SPHERICAL = false;
  44157. this.REFLECTIONMAP_PLANAR = false;
  44158. this.REFLECTIONMAP_CUBIC = false;
  44159. this.REFLECTIONMAP_PROJECTION = false;
  44160. this.REFLECTIONMAP_SKYBOX = false;
  44161. this.REFLECTIONMAP_EXPLICIT = false;
  44162. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44163. this.INVERTCUBICMAP = false;
  44164. this.LOGARITHMICDEPTH = false;
  44165. this.CAMERATONEMAP = false;
  44166. this.CAMERACONTRAST = false;
  44167. this.OVERLOADEDVALUES = false;
  44168. this.OVERLOADEDSHADOWVALUES = false;
  44169. this.USESPHERICALFROMREFLECTIONMAP = false;
  44170. this.REFRACTION = false;
  44171. this.REFRACTIONMAP_3D = false;
  44172. this.LINKREFRACTIONTOTRANSPARENCY = false;
  44173. this.REFRACTIONMAPINLINEARSPACE = false;
  44174. this.LODBASEDMICROSFURACE = false;
  44175. this.USEPHYSICALLIGHTFALLOFF = false;
  44176. this.RADIANCEOVERALPHA = false;
  44177. this.USEPMREMREFLECTION = false;
  44178. this.USEPMREMREFRACTION = false;
  44179. this._keys = Object.keys(this);
  44180. }
  44181. return PBRMaterialDefines;
  44182. })(BABYLON.MaterialDefines);
  44183. /**
  44184. * The Physically based material of BJS.
  44185. *
  44186. * This offers the main features of a standard PBR material.
  44187. * For more information, please refer to the documentation :
  44188. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44189. */
  44190. var PBRMaterial = (function (_super) {
  44191. __extends(PBRMaterial, _super);
  44192. /**
  44193. * Instantiates a new PBRMaterial instance.
  44194. *
  44195. * @param name The material name
  44196. * @param scene The scene the material will be use in.
  44197. */
  44198. function PBRMaterial(name, scene) {
  44199. var _this = this;
  44200. _super.call(this, name, scene);
  44201. /**
  44202. * Intensity of the direct lights e.g. the four lights available in your scene.
  44203. * This impacts both the direct diffuse and specular highlights.
  44204. */
  44205. this.directIntensity = 1.0;
  44206. /**
  44207. * Intensity of the emissive part of the material.
  44208. * This helps controlling the emissive effect without modifying the emissive color.
  44209. */
  44210. this.emissiveIntensity = 1.0;
  44211. /**
  44212. * Intensity of the environment e.g. how much the environment will light the object
  44213. * either through harmonics for rough material or through the refelction for shiny ones.
  44214. */
  44215. this.environmentIntensity = 1.0;
  44216. /**
  44217. * This is a special control allowing the reduction of the specular highlights coming from the
  44218. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44219. */
  44220. this.specularIntensity = 1.0;
  44221. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  44222. /**
  44223. * Debug Control allowing disabling the bump map on this material.
  44224. */
  44225. this.disableBumpMap = false;
  44226. /**
  44227. * Debug Control helping enforcing or dropping the darkness of shadows.
  44228. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  44229. */
  44230. this.overloadedShadowIntensity = 1.0;
  44231. /**
  44232. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  44233. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  44234. */
  44235. this.overloadedShadeIntensity = 1.0;
  44236. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  44237. /**
  44238. * The camera exposure used on this material.
  44239. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44240. * This corresponds to a photographic exposure.
  44241. */
  44242. this.cameraExposure = 1.0;
  44243. /**
  44244. * The camera contrast used on this material.
  44245. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  44246. */
  44247. this.cameraContrast = 1.0;
  44248. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  44249. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  44250. /**
  44251. * Debug Control allowing to overload the ambient color.
  44252. * This as to be use with the overloadedAmbientIntensity parameter.
  44253. */
  44254. this.overloadedAmbient = BABYLON.Color3.White();
  44255. /**
  44256. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  44257. */
  44258. this.overloadedAmbientIntensity = 0.0;
  44259. /**
  44260. * Debug Control allowing to overload the albedo color.
  44261. * This as to be use with the overloadedAlbedoIntensity parameter.
  44262. */
  44263. this.overloadedAlbedo = BABYLON.Color3.White();
  44264. /**
  44265. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  44266. */
  44267. this.overloadedAlbedoIntensity = 0.0;
  44268. /**
  44269. * Debug Control allowing to overload the reflectivity color.
  44270. * This as to be use with the overloadedReflectivityIntensity parameter.
  44271. */
  44272. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  44273. /**
  44274. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  44275. */
  44276. this.overloadedReflectivityIntensity = 0.0;
  44277. /**
  44278. * Debug Control allowing to overload the emissive color.
  44279. * This as to be use with the overloadedEmissiveIntensity parameter.
  44280. */
  44281. this.overloadedEmissive = BABYLON.Color3.White();
  44282. /**
  44283. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  44284. */
  44285. this.overloadedEmissiveIntensity = 0.0;
  44286. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  44287. /**
  44288. * Debug Control allowing to overload the reflection color.
  44289. * This as to be use with the overloadedReflectionIntensity parameter.
  44290. */
  44291. this.overloadedReflection = BABYLON.Color3.White();
  44292. /**
  44293. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  44294. */
  44295. this.overloadedReflectionIntensity = 0.0;
  44296. /**
  44297. * Debug Control allowing to overload the microsurface.
  44298. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  44299. */
  44300. this.overloadedMicroSurface = 0.0;
  44301. /**
  44302. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  44303. */
  44304. this.overloadedMicroSurfaceIntensity = 0.0;
  44305. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  44306. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44307. /**
  44308. * AKA Diffuse Color in other nomenclature.
  44309. */
  44310. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44311. /**
  44312. * AKA Specular Color in other nomenclature.
  44313. */
  44314. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44315. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  44316. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44317. /**
  44318. * AKA Glossiness in other nomenclature.
  44319. */
  44320. this.microSurface = 0.9;
  44321. /**
  44322. * source material index of refraction (IOR)' / 'destination material IOR.
  44323. */
  44324. this.indexOfRefraction = 0.66;
  44325. /**
  44326. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44327. */
  44328. this.invertRefractionY = false;
  44329. /**
  44330. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44331. * Materials half opaque for instance using refraction could benefit from this control.
  44332. */
  44333. this.linkRefractionWithTransparency = false;
  44334. /**
  44335. * The emissive and albedo are linked to never be more than one (Energy conservation).
  44336. */
  44337. this.linkEmissiveWithAlbedo = false;
  44338. this.useLightmapAsShadowmap = false;
  44339. /**
  44340. * In this mode, the emissive informtaion will always be added to the lighting once.
  44341. * A light for instance can be thought as emissive.
  44342. */
  44343. this.useEmissiveAsIllumination = false;
  44344. /**
  44345. * Secifies that the alpha is coming form the albedo channel alpha channel.
  44346. */
  44347. this.useAlphaFromAlbedoTexture = false;
  44348. /**
  44349. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44350. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44351. */
  44352. this.useSpecularOverAlpha = true;
  44353. /**
  44354. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44355. */
  44356. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44357. /**
  44358. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44359. * The material will try to infer what glossiness each pixel should be.
  44360. */
  44361. this.useAutoMicroSurfaceFromReflectivityMap = false;
  44362. /**
  44363. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  44364. * the creation of the material.
  44365. */
  44366. this.useScalarInLinearSpace = false;
  44367. /**
  44368. * BJS is using an harcoded light falloff based on a manually sets up range.
  44369. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44370. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44371. */
  44372. this.usePhysicalLightFalloff = true;
  44373. /**
  44374. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44375. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44376. */
  44377. this.useRadianceOverAlpha = true;
  44378. /**
  44379. * Allows using the bump map in parallax mode.
  44380. */
  44381. this.useParallax = false;
  44382. /**
  44383. * Allows using the bump map in parallax occlusion mode.
  44384. */
  44385. this.useParallaxOcclusion = false;
  44386. /**
  44387. * Controls the scale bias of the parallax mode.
  44388. */
  44389. this.parallaxScaleBias = 0.05;
  44390. this.disableLighting = false;
  44391. this._renderTargets = new BABYLON.SmartArray(16);
  44392. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44393. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44394. this._tempColor = new BABYLON.Color3();
  44395. this._defines = new PBRMaterialDefines();
  44396. this._cachedDefines = new PBRMaterialDefines();
  44397. this._myScene = null;
  44398. this._myShadowGenerator = null;
  44399. this._cachedDefines.BonesPerMesh = -1;
  44400. this.getRenderTargetTextures = function () {
  44401. _this._renderTargets.reset();
  44402. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  44403. _this._renderTargets.push(_this.reflectionTexture);
  44404. }
  44405. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  44406. _this._renderTargets.push(_this.refractionTexture);
  44407. }
  44408. return _this._renderTargets;
  44409. };
  44410. }
  44411. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  44412. get: function () {
  44413. return this._useLogarithmicDepth;
  44414. },
  44415. set: function (value) {
  44416. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44417. },
  44418. enumerable: true,
  44419. configurable: true
  44420. });
  44421. PBRMaterial.prototype.needAlphaBlending = function () {
  44422. if (this.linkRefractionWithTransparency) {
  44423. return false;
  44424. }
  44425. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  44426. };
  44427. PBRMaterial.prototype.needAlphaTesting = function () {
  44428. if (this.linkRefractionWithTransparency) {
  44429. return false;
  44430. }
  44431. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  44432. };
  44433. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44434. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  44435. };
  44436. PBRMaterial.prototype.getAlphaTestTexture = function () {
  44437. return this.albedoTexture;
  44438. };
  44439. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  44440. if (!mesh) {
  44441. return true;
  44442. }
  44443. if (this._defines.INSTANCES !== useInstances) {
  44444. return false;
  44445. }
  44446. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  44447. return true;
  44448. }
  44449. return false;
  44450. };
  44451. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  44452. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  44453. };
  44454. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  44455. if (!useScalarInLinear) {
  44456. color.toLinearSpaceToRef(ref);
  44457. }
  44458. else {
  44459. ref.r = color.r;
  44460. ref.g = color.g;
  44461. ref.b = color.b;
  44462. }
  44463. };
  44464. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace) {
  44465. var lightIndex = 0;
  44466. var depthValuesAlreadySet = false;
  44467. for (var index = 0; index < scene.lights.length; index++) {
  44468. var light = scene.lights[index];
  44469. if (!light.isEnabled()) {
  44470. continue;
  44471. }
  44472. if (!light.canAffectMesh(mesh)) {
  44473. continue;
  44474. }
  44475. this._lightRadiuses[lightIndex] = light.radius;
  44476. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  44477. // GAMMA CORRECTION.
  44478. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  44479. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  44480. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, light.range);
  44481. if (defines["SPECULARTERM"]) {
  44482. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  44483. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  44484. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  44485. }
  44486. // Shadows
  44487. if (scene.shadowsEnabled) {
  44488. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  44489. }
  44490. lightIndex++;
  44491. if (lightIndex === maxSimultaneousLights)
  44492. break;
  44493. }
  44494. effect.setFloat4("vLightRadiuses", this._lightRadiuses[0], this._lightRadiuses[1], this._lightRadiuses[2], this._lightRadiuses[3]);
  44495. };
  44496. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  44497. if (this.checkReadyOnlyOnce) {
  44498. if (this._wasPreviouslyReady) {
  44499. return true;
  44500. }
  44501. }
  44502. var scene = this.getScene();
  44503. if (!this.checkReadyOnEveryCall) {
  44504. if (this._renderId === scene.getRenderId()) {
  44505. if (this._checkCache(scene, mesh, useInstances)) {
  44506. return true;
  44507. }
  44508. }
  44509. }
  44510. var engine = scene.getEngine();
  44511. var needNormals = false;
  44512. var needUVs = false;
  44513. this._defines.reset();
  44514. if (scene.texturesEnabled) {
  44515. // Textures
  44516. if (scene.texturesEnabled) {
  44517. if (scene.getEngine().getCaps().textureLOD) {
  44518. this._defines.LODBASEDMICROSFURACE = true;
  44519. }
  44520. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44521. if (!this.albedoTexture.isReady()) {
  44522. return false;
  44523. }
  44524. else {
  44525. needUVs = true;
  44526. this._defines.ALBEDO = true;
  44527. }
  44528. }
  44529. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44530. if (!this.ambientTexture.isReady()) {
  44531. return false;
  44532. }
  44533. else {
  44534. needUVs = true;
  44535. this._defines.AMBIENT = true;
  44536. }
  44537. }
  44538. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44539. if (!this.opacityTexture.isReady()) {
  44540. return false;
  44541. }
  44542. else {
  44543. needUVs = true;
  44544. this._defines.OPACITY = true;
  44545. if (this.opacityTexture.getAlphaFromRGB) {
  44546. this._defines.OPACITYRGB = true;
  44547. }
  44548. }
  44549. }
  44550. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44551. if (!this.reflectionTexture.isReady()) {
  44552. return false;
  44553. }
  44554. else {
  44555. needNormals = true;
  44556. this._defines.REFLECTION = true;
  44557. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44558. this._defines.INVERTCUBICMAP = true;
  44559. }
  44560. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  44561. switch (this.reflectionTexture.coordinatesMode) {
  44562. case BABYLON.Texture.CUBIC_MODE:
  44563. case BABYLON.Texture.INVCUBIC_MODE:
  44564. this._defines.REFLECTIONMAP_CUBIC = true;
  44565. break;
  44566. case BABYLON.Texture.EXPLICIT_MODE:
  44567. this._defines.REFLECTIONMAP_EXPLICIT = true;
  44568. break;
  44569. case BABYLON.Texture.PLANAR_MODE:
  44570. this._defines.REFLECTIONMAP_PLANAR = true;
  44571. break;
  44572. case BABYLON.Texture.PROJECTION_MODE:
  44573. this._defines.REFLECTIONMAP_PROJECTION = true;
  44574. break;
  44575. case BABYLON.Texture.SKYBOX_MODE:
  44576. this._defines.REFLECTIONMAP_SKYBOX = true;
  44577. break;
  44578. case BABYLON.Texture.SPHERICAL_MODE:
  44579. this._defines.REFLECTIONMAP_SPHERICAL = true;
  44580. break;
  44581. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44582. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44583. break;
  44584. }
  44585. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  44586. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  44587. needNormals = true;
  44588. if (this.reflectionTexture.isPMREM) {
  44589. this._defines.USEPMREMREFLECTION = true;
  44590. }
  44591. }
  44592. }
  44593. }
  44594. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44595. if (!this.lightmapTexture.isReady()) {
  44596. return false;
  44597. }
  44598. else {
  44599. needUVs = true;
  44600. this._defines.LIGHTMAP = true;
  44601. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  44602. }
  44603. }
  44604. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44605. if (!this.emissiveTexture.isReady()) {
  44606. return false;
  44607. }
  44608. else {
  44609. needUVs = true;
  44610. this._defines.EMISSIVE = true;
  44611. }
  44612. }
  44613. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44614. if (!this.reflectivityTexture.isReady()) {
  44615. return false;
  44616. }
  44617. else {
  44618. needUVs = true;
  44619. this._defines.REFLECTIVITY = true;
  44620. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  44621. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  44622. }
  44623. }
  44624. }
  44625. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  44626. if (!this.bumpTexture.isReady()) {
  44627. return false;
  44628. }
  44629. else {
  44630. needUVs = true;
  44631. this._defines.BUMP = true;
  44632. if (this.useParallax) {
  44633. this._defines.PARALLAX = true;
  44634. if (this.useParallaxOcclusion) {
  44635. this._defines.PARALLAXOCCLUSION = true;
  44636. }
  44637. }
  44638. }
  44639. }
  44640. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44641. if (!this.refractionTexture.isReady()) {
  44642. return false;
  44643. }
  44644. else {
  44645. needUVs = true;
  44646. this._defines.REFRACTION = true;
  44647. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  44648. if (this.linkRefractionWithTransparency) {
  44649. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44650. }
  44651. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  44652. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  44653. if (this.refractionTexture.isPMREM) {
  44654. this._defines.USEPMREMREFRACTION = true;
  44655. }
  44656. }
  44657. }
  44658. }
  44659. }
  44660. // Effect
  44661. if (scene.clipPlane) {
  44662. this._defines.CLIPPLANE = true;
  44663. }
  44664. if (engine.getAlphaTesting()) {
  44665. this._defines.ALPHATEST = true;
  44666. }
  44667. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44668. this._defines.ALPHAFROMALBEDO = true;
  44669. }
  44670. if (this.useEmissiveAsIllumination) {
  44671. this._defines.EMISSIVEASILLUMINATION = true;
  44672. }
  44673. if (this.linkEmissiveWithAlbedo) {
  44674. this._defines.LINKEMISSIVEWITHALBEDO = true;
  44675. }
  44676. if (this.useLogarithmicDepth) {
  44677. this._defines.LOGARITHMICDEPTH = true;
  44678. }
  44679. if (this.cameraContrast != 1) {
  44680. this._defines.CAMERACONTRAST = true;
  44681. }
  44682. if (this.cameraExposure != 1) {
  44683. this._defines.CAMERATONEMAP = true;
  44684. }
  44685. if (this.overloadedShadeIntensity != 1 ||
  44686. this.overloadedShadowIntensity != 1) {
  44687. this._defines.OVERLOADEDSHADOWVALUES = true;
  44688. }
  44689. if (this.overloadedMicroSurfaceIntensity > 0 ||
  44690. this.overloadedEmissiveIntensity > 0 ||
  44691. this.overloadedReflectivityIntensity > 0 ||
  44692. this.overloadedAlbedoIntensity > 0 ||
  44693. this.overloadedAmbientIntensity > 0 ||
  44694. this.overloadedReflectionIntensity > 0) {
  44695. this._defines.OVERLOADEDVALUES = true;
  44696. }
  44697. // Point size
  44698. if (this.pointsCloud || scene.forcePointsCloud) {
  44699. this._defines.POINTSIZE = true;
  44700. }
  44701. // Fog
  44702. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44703. this._defines.FOG = true;
  44704. }
  44705. if (scene.lightsEnabled && !this.disableLighting) {
  44706. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines) || needNormals;
  44707. }
  44708. if (BABYLON.StandardMaterial.FresnelEnabled) {
  44709. // Fresnel
  44710. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  44711. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44712. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44713. this._defines.OPACITYFRESNEL = true;
  44714. }
  44715. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44716. this._defines.EMISSIVEFRESNEL = true;
  44717. }
  44718. needNormals = true;
  44719. this._defines.FRESNEL = true;
  44720. }
  44721. }
  44722. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  44723. this._defines.SPECULAROVERALPHA = true;
  44724. }
  44725. if (this.usePhysicalLightFalloff) {
  44726. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  44727. }
  44728. if (this.useRadianceOverAlpha) {
  44729. this._defines.RADIANCEOVERALPHA = true;
  44730. }
  44731. // Attribs
  44732. if (mesh) {
  44733. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44734. this._defines.NORMAL = true;
  44735. }
  44736. if (needUVs) {
  44737. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44738. this._defines.UV1 = true;
  44739. }
  44740. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44741. this._defines.UV2 = true;
  44742. }
  44743. }
  44744. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  44745. this._defines.VERTEXCOLOR = true;
  44746. if (mesh.hasVertexAlpha) {
  44747. this._defines.VERTEXALPHA = true;
  44748. }
  44749. }
  44750. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44751. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  44752. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  44753. }
  44754. // Instances
  44755. if (useInstances) {
  44756. this._defines.INSTANCES = true;
  44757. }
  44758. }
  44759. // Get correct effect
  44760. if (!this._defines.isEqual(this._cachedDefines)) {
  44761. this._defines.cloneTo(this._cachedDefines);
  44762. scene.resetCachedMaterial();
  44763. // Fallbacks
  44764. var fallbacks = new BABYLON.EffectFallbacks();
  44765. if (this._defines.REFLECTION) {
  44766. fallbacks.addFallback(0, "REFLECTION");
  44767. }
  44768. if (this._defines.REFRACTION) {
  44769. fallbacks.addFallback(0, "REFRACTION");
  44770. }
  44771. if (this._defines.REFLECTIVITY) {
  44772. fallbacks.addFallback(0, "REFLECTIVITY");
  44773. }
  44774. if (this._defines.BUMP) {
  44775. fallbacks.addFallback(0, "BUMP");
  44776. }
  44777. if (this._defines.PARALLAX) {
  44778. fallbacks.addFallback(1, "PARALLAX");
  44779. }
  44780. if (this._defines.PARALLAXOCCLUSION) {
  44781. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44782. }
  44783. if (this._defines.SPECULAROVERALPHA) {
  44784. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44785. }
  44786. if (this._defines.FOG) {
  44787. fallbacks.addFallback(1, "FOG");
  44788. }
  44789. if (this._defines.POINTSIZE) {
  44790. fallbacks.addFallback(0, "POINTSIZE");
  44791. }
  44792. if (this._defines.LOGARITHMICDEPTH) {
  44793. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44794. }
  44795. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  44796. if (this._defines.SPECULARTERM) {
  44797. fallbacks.addFallback(0, "SPECULARTERM");
  44798. }
  44799. if (this._defines.OPACITYFRESNEL) {
  44800. fallbacks.addFallback(1, "OPACITYFRESNEL");
  44801. }
  44802. if (this._defines.EMISSIVEFRESNEL) {
  44803. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  44804. }
  44805. if (this._defines.FRESNEL) {
  44806. fallbacks.addFallback(3, "FRESNEL");
  44807. }
  44808. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  44809. fallbacks.addCPUSkinningFallback(0, mesh);
  44810. }
  44811. //Attributes
  44812. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44813. if (this._defines.NORMAL) {
  44814. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44815. }
  44816. if (this._defines.UV1) {
  44817. attribs.push(BABYLON.VertexBuffer.UVKind);
  44818. }
  44819. if (this._defines.UV2) {
  44820. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44821. }
  44822. if (this._defines.VERTEXCOLOR) {
  44823. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44824. }
  44825. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  44826. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  44827. // Legacy browser patch
  44828. var shaderName = "pbr";
  44829. if (!scene.getEngine().getCaps().standardDerivatives) {
  44830. shaderName = "legacypbr";
  44831. }
  44832. var join = this._defines.toString();
  44833. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44834. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  44835. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  44836. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  44837. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  44838. "vFogInfos", "vFogColor", "pointSize",
  44839. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44840. "mBones",
  44841. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44842. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  44843. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  44844. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vCameraInfos", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  44845. "logarithmicDepthConstant",
  44846. "vSphericalX", "vSphericalY", "vSphericalZ",
  44847. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44848. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44849. "vMicrosurfaceTextureLods", "vLightRadiuses"
  44850. ], ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  44851. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  44852. ], join, fallbacks, this.onCompiled, this.onError);
  44853. }
  44854. if (!this._effect.isReady()) {
  44855. return false;
  44856. }
  44857. this._renderId = scene.getRenderId();
  44858. this._wasPreviouslyReady = true;
  44859. if (mesh) {
  44860. if (!mesh._materialDefines) {
  44861. mesh._materialDefines = new PBRMaterialDefines();
  44862. }
  44863. this._defines.cloneTo(mesh._materialDefines);
  44864. }
  44865. return true;
  44866. };
  44867. PBRMaterial.prototype.unbind = function () {
  44868. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  44869. this._effect.setTexture("reflection2DSampler", null);
  44870. }
  44871. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  44872. this._effect.setTexture("refraction2DSampler", null);
  44873. }
  44874. _super.prototype.unbind.call(this);
  44875. };
  44876. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  44877. this._effect.setMatrix("world", world);
  44878. };
  44879. PBRMaterial.prototype.bind = function (world, mesh) {
  44880. this._myScene = this.getScene();
  44881. // Matrices
  44882. this.bindOnlyWorldMatrix(world);
  44883. // Bones
  44884. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  44885. if (this._myScene.getCachedMaterial() !== this) {
  44886. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  44887. if (BABYLON.StandardMaterial.FresnelEnabled) {
  44888. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44889. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44890. }
  44891. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44892. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44893. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44894. }
  44895. }
  44896. // Textures
  44897. if (this._myScene.texturesEnabled) {
  44898. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44899. this._effect.setTexture("albedoSampler", this.albedoTexture);
  44900. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  44901. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  44902. }
  44903. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44904. this._effect.setTexture("ambientSampler", this.ambientTexture);
  44905. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  44906. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  44907. }
  44908. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44909. this._effect.setTexture("opacitySampler", this.opacityTexture);
  44910. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  44911. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  44912. }
  44913. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44914. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  44915. if (this.reflectionTexture.isCube) {
  44916. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  44917. }
  44918. else {
  44919. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  44920. }
  44921. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  44922. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  44923. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  44924. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  44925. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  44926. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  44927. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  44928. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  44929. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  44930. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  44931. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  44932. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  44933. }
  44934. }
  44935. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44936. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  44937. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  44938. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  44939. }
  44940. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44941. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  44942. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  44943. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  44944. }
  44945. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44946. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  44947. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  44948. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  44949. }
  44950. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  44951. this._effect.setTexture("bumpSampler", this.bumpTexture);
  44952. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  44953. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  44954. }
  44955. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44956. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  44957. var depth = 1.0;
  44958. if (this.refractionTexture.isCube) {
  44959. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  44960. }
  44961. else {
  44962. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  44963. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  44964. if (this.refractionTexture.depth) {
  44965. depth = this.refractionTexture.depth;
  44966. }
  44967. }
  44968. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44969. }
  44970. if ((this.reflectionTexture || this.refractionTexture)) {
  44971. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  44972. }
  44973. }
  44974. // Clip plane
  44975. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  44976. // Point size
  44977. if (this.pointsCloud) {
  44978. this._effect.setFloat("pointSize", this.pointSize);
  44979. }
  44980. // Colors
  44981. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44982. // GAMMA CORRECTION.
  44983. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  44984. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  44985. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44986. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  44987. // GAMMA CORRECTION.
  44988. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  44989. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  44990. // GAMMA CORRECTION.
  44991. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  44992. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  44993. }
  44994. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  44995. // GAMMA CORRECTION.
  44996. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  44997. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  44998. // Lights
  44999. if (this._myScene.lightsEnabled && !this.disableLighting) {
  45000. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace);
  45001. }
  45002. // View
  45003. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  45004. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  45005. }
  45006. // Fog
  45007. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  45008. this._lightingInfos.x = this.directIntensity;
  45009. this._lightingInfos.y = this.emissiveIntensity;
  45010. this._lightingInfos.z = this.environmentIntensity;
  45011. this._lightingInfos.w = this.specularIntensity;
  45012. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  45013. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  45014. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  45015. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  45016. this._cameraInfos.x = this.cameraExposure;
  45017. this._cameraInfos.y = this.cameraContrast;
  45018. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  45019. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  45020. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  45021. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  45022. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  45023. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  45024. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  45025. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  45026. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  45027. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  45028. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  45029. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  45030. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  45031. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  45032. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  45033. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  45034. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  45035. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  45036. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  45037. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  45038. // Log. depth
  45039. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  45040. }
  45041. _super.prototype.bind.call(this, world, mesh);
  45042. this._myScene = null;
  45043. };
  45044. PBRMaterial.prototype.getAnimatables = function () {
  45045. var results = [];
  45046. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  45047. results.push(this.albedoTexture);
  45048. }
  45049. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  45050. results.push(this.ambientTexture);
  45051. }
  45052. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  45053. results.push(this.opacityTexture);
  45054. }
  45055. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  45056. results.push(this.reflectionTexture);
  45057. }
  45058. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  45059. results.push(this.emissiveTexture);
  45060. }
  45061. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  45062. results.push(this.reflectivityTexture);
  45063. }
  45064. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  45065. results.push(this.bumpTexture);
  45066. }
  45067. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  45068. results.push(this.lightmapTexture);
  45069. }
  45070. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  45071. results.push(this.refractionTexture);
  45072. }
  45073. return results;
  45074. };
  45075. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  45076. if (this.albedoTexture) {
  45077. this.albedoTexture.dispose();
  45078. }
  45079. if (this.ambientTexture) {
  45080. this.ambientTexture.dispose();
  45081. }
  45082. if (this.opacityTexture) {
  45083. this.opacityTexture.dispose();
  45084. }
  45085. if (this.reflectionTexture) {
  45086. this.reflectionTexture.dispose();
  45087. }
  45088. if (this.emissiveTexture) {
  45089. this.emissiveTexture.dispose();
  45090. }
  45091. if (this.reflectivityTexture) {
  45092. this.reflectivityTexture.dispose();
  45093. }
  45094. if (this.bumpTexture) {
  45095. this.bumpTexture.dispose();
  45096. }
  45097. if (this.lightmapTexture) {
  45098. this.lightmapTexture.dispose();
  45099. }
  45100. if (this.refractionTexture) {
  45101. this.refractionTexture.dispose();
  45102. }
  45103. _super.prototype.dispose.call(this, forceDisposeEffect);
  45104. };
  45105. PBRMaterial.prototype.clone = function (name) {
  45106. var _this = this;
  45107. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45108. };
  45109. PBRMaterial.prototype.serialize = function () {
  45110. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45111. serializationObject.customType = "BABYLON.PBRMaterial";
  45112. return serializationObject;
  45113. };
  45114. // Statics
  45115. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45116. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45117. };
  45118. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  45119. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  45120. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  45121. PBRMaterial._scaledReflection = new BABYLON.Color3();
  45122. PBRMaterial._lightRadiuses = [1, 1, 1, 1];
  45123. __decorate([
  45124. BABYLON.serialize()
  45125. ], PBRMaterial.prototype, "directIntensity", void 0);
  45126. __decorate([
  45127. BABYLON.serialize()
  45128. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45129. __decorate([
  45130. BABYLON.serialize()
  45131. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45132. __decorate([
  45133. BABYLON.serialize()
  45134. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45135. __decorate([
  45136. BABYLON.serialize()
  45137. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45138. __decorate([
  45139. BABYLON.serialize()
  45140. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  45141. __decorate([
  45142. BABYLON.serialize()
  45143. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  45144. __decorate([
  45145. BABYLON.serialize()
  45146. ], PBRMaterial.prototype, "cameraExposure", void 0);
  45147. __decorate([
  45148. BABYLON.serialize()
  45149. ], PBRMaterial.prototype, "cameraContrast", void 0);
  45150. __decorate([
  45151. BABYLON.serializeAsColor3()
  45152. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  45153. __decorate([
  45154. BABYLON.serialize()
  45155. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  45156. __decorate([
  45157. BABYLON.serializeAsColor3()
  45158. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  45159. __decorate([
  45160. BABYLON.serialize()
  45161. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  45162. __decorate([
  45163. BABYLON.serializeAsColor3()
  45164. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  45165. __decorate([
  45166. BABYLON.serialize()
  45167. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  45168. __decorate([
  45169. BABYLON.serializeAsColor3()
  45170. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  45171. __decorate([
  45172. BABYLON.serialize()
  45173. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  45174. __decorate([
  45175. BABYLON.serializeAsColor3()
  45176. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  45177. __decorate([
  45178. BABYLON.serialize()
  45179. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  45180. __decorate([
  45181. BABYLON.serialize()
  45182. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  45183. __decorate([
  45184. BABYLON.serialize()
  45185. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  45186. __decorate([
  45187. BABYLON.serializeAsTexture()
  45188. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45189. __decorate([
  45190. BABYLON.serializeAsTexture()
  45191. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45192. __decorate([
  45193. BABYLON.serializeAsTexture()
  45194. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45195. __decorate([
  45196. BABYLON.serializeAsTexture()
  45197. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45198. __decorate([
  45199. BABYLON.serializeAsTexture()
  45200. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45201. __decorate([
  45202. BABYLON.serializeAsTexture()
  45203. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45204. __decorate([
  45205. BABYLON.serializeAsTexture()
  45206. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45207. __decorate([
  45208. BABYLON.serializeAsTexture()
  45209. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45210. __decorate([
  45211. BABYLON.serializeAsTexture()
  45212. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45213. __decorate([
  45214. BABYLON.serializeAsColor3("ambient")
  45215. ], PBRMaterial.prototype, "ambientColor", void 0);
  45216. __decorate([
  45217. BABYLON.serializeAsColor3("albedo")
  45218. ], PBRMaterial.prototype, "albedoColor", void 0);
  45219. __decorate([
  45220. BABYLON.serializeAsColor3("reflectivity")
  45221. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45222. __decorate([
  45223. BABYLON.serializeAsColor3("reflection")
  45224. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45225. __decorate([
  45226. BABYLON.serializeAsColor3("emissive")
  45227. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45228. __decorate([
  45229. BABYLON.serialize()
  45230. ], PBRMaterial.prototype, "microSurface", void 0);
  45231. __decorate([
  45232. BABYLON.serialize()
  45233. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45234. __decorate([
  45235. BABYLON.serialize()
  45236. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45237. __decorate([
  45238. BABYLON.serializeAsFresnelParameters()
  45239. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  45240. __decorate([
  45241. BABYLON.serializeAsFresnelParameters()
  45242. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  45243. __decorate([
  45244. BABYLON.serialize()
  45245. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45246. __decorate([
  45247. BABYLON.serialize()
  45248. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  45249. __decorate([
  45250. BABYLON.serialize()
  45251. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45252. __decorate([
  45253. BABYLON.serialize()
  45254. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45255. __decorate([
  45256. BABYLON.serialize()
  45257. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45258. __decorate([
  45259. BABYLON.serialize()
  45260. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45261. __decorate([
  45262. BABYLON.serialize()
  45263. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45264. __decorate([
  45265. BABYLON.serialize()
  45266. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45267. __decorate([
  45268. BABYLON.serialize()
  45269. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  45270. __decorate([
  45271. BABYLON.serialize()
  45272. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45273. __decorate([
  45274. BABYLON.serialize()
  45275. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45276. __decorate([
  45277. BABYLON.serialize()
  45278. ], PBRMaterial.prototype, "useParallax", void 0);
  45279. __decorate([
  45280. BABYLON.serialize()
  45281. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45282. __decorate([
  45283. BABYLON.serialize()
  45284. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45285. __decorate([
  45286. BABYLON.serialize()
  45287. ], PBRMaterial.prototype, "disableLighting", void 0);
  45288. __decorate([
  45289. BABYLON.serialize()
  45290. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  45291. return PBRMaterial;
  45292. })(BABYLON.Material);
  45293. BABYLON.PBRMaterial = PBRMaterial;
  45294. })(BABYLON || (BABYLON = {}));
  45295. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vLightRadiuses;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[3]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightRadiuses;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[3]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif (microSurface>0.5)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb); \n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb); \n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif (microSurface>0.5)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0 ,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0 ,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  45296. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,vec3(1.,1.,1.));\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\nfloat computeLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\nreturn lightDistanceFalloff;\n#else\nfloat lightFalloff=max(0.,1.0-length(lightOffset)/range);\nreturn lightFalloff;\n#endif\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeLightFalloff(lightOffset,lightDistanceSquared,range);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(lightOffset);\n\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeLightFalloff(lightOffset,lightDistanceSquared,range);\n\nattenuation*=cosAngle;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nvPositionFromLight0=lightMatrix0*worldPos;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvPositionFromLight1=lightMatrix1*worldPos;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvPositionFromLight2=lightMatrix2*worldPos;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvPositionFromLight3=lightMatrix3*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif"};
  45297. 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={}));";
  45298. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  45299. module.exports = BABYLON;
  45300. };