babylon.max.js 3.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478
  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. /**
  22. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  23. */
  24. MathTools.WithinEpsilon = function (a, b, epsilon) {
  25. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  26. var num = a - b;
  27. return -epsilon <= num && num <= epsilon;
  28. };
  29. /**
  30. * Returns a string : the upper case translation of the number i to hexadecimal.
  31. */
  32. MathTools.ToHex = function (i) {
  33. var str = i.toString(16);
  34. if (i <= 15) {
  35. return ("0" + str).toUpperCase();
  36. }
  37. return str.toUpperCase();
  38. };
  39. /**
  40. * Returns -1 if value is negative and +1 is value is positive.
  41. * Returns the value itself if it's equal to zero.
  42. */
  43. MathTools.Sign = function (value) {
  44. value = +value; // convert to a number
  45. if (value === 0 || isNaN(value))
  46. return value;
  47. return value > 0 ? 1 : -1;
  48. };
  49. /**
  50. * Returns the value itself if it's between min and max.
  51. * Returns min if the value is lower than min.
  52. * Returns max if the value is greater than max.
  53. */
  54. MathTools.Clamp = function (value, min, max) {
  55. if (min === void 0) { min = 0; }
  56. if (max === void 0) { max = 1; }
  57. return Math.min(max, Math.max(min, value));
  58. };
  59. return MathTools;
  60. }());
  61. BABYLON.MathTools = MathTools;
  62. var Color3 = (function () {
  63. /**
  64. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  65. */
  66. function Color3(r, g, b) {
  67. if (r === void 0) { r = 0; }
  68. if (g === void 0) { g = 0; }
  69. if (b === void 0) { b = 0; }
  70. this.r = r;
  71. this.g = g;
  72. this.b = b;
  73. }
  74. /**
  75. * Returns a string with the Color3 current values.
  76. */
  77. Color3.prototype.toString = function () {
  78. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  79. };
  80. /**
  81. * Returns the string "Color3".
  82. */
  83. Color3.prototype.getClassName = function () {
  84. return "Color3";
  85. };
  86. /**
  87. * Returns the Color3 hash code.
  88. */
  89. Color3.prototype.getHashCode = function () {
  90. var hash = this.r || 0;
  91. hash = (hash * 397) ^ (this.g || 0);
  92. hash = (hash * 397) ^ (this.b || 0);
  93. return hash;
  94. };
  95. // Operators
  96. /**
  97. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  98. * Returns the Color3.
  99. */
  100. Color3.prototype.toArray = function (array, index) {
  101. if (index === undefined) {
  102. index = 0;
  103. }
  104. array[index] = this.r;
  105. array[index + 1] = this.g;
  106. array[index + 2] = this.b;
  107. return this;
  108. };
  109. /**
  110. * Returns a new Color4 object from the current Color3 and the passed alpha.
  111. */
  112. Color3.prototype.toColor4 = function (alpha) {
  113. if (alpha === void 0) { alpha = 1; }
  114. return new Color4(this.r, this.g, this.b, alpha);
  115. };
  116. /**
  117. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  118. */
  119. Color3.prototype.asArray = function () {
  120. var result = [];
  121. this.toArray(result, 0);
  122. return result;
  123. };
  124. /**
  125. * Returns the luminance value (float).
  126. */
  127. Color3.prototype.toLuminance = function () {
  128. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  129. };
  130. /**
  131. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  132. * Returns this new object.
  133. */
  134. Color3.prototype.multiply = function (otherColor) {
  135. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  136. };
  137. /**
  138. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  139. * Returns the current Color3.
  140. */
  141. Color3.prototype.multiplyToRef = function (otherColor, result) {
  142. result.r = this.r * otherColor.r;
  143. result.g = this.g * otherColor.g;
  144. result.b = this.b * otherColor.b;
  145. return this;
  146. };
  147. /**
  148. * Boolean : True if the rgb values are equal to the passed ones.
  149. */
  150. Color3.prototype.equals = function (otherColor) {
  151. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  152. };
  153. /**
  154. * Boolean : True if the rgb values are equal to the passed ones.
  155. */
  156. Color3.prototype.equalsFloats = function (r, g, b) {
  157. return this.r === r && this.g === g && this.b === b;
  158. };
  159. /**
  160. * Multiplies in place each rgb value by scale.
  161. * Returns the updated Color3.
  162. */
  163. Color3.prototype.scale = function (scale) {
  164. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  165. };
  166. /**
  167. * Multiplies the rgb values by scale and stores the result into "result".
  168. * Returns the unmodified current Color3.
  169. */
  170. Color3.prototype.scaleToRef = function (scale, result) {
  171. result.r = this.r * scale;
  172. result.g = this.g * scale;
  173. result.b = this.b * scale;
  174. return this;
  175. };
  176. /**
  177. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  178. */
  179. Color3.prototype.add = function (otherColor) {
  180. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  181. };
  182. /**
  183. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  184. * Returns the unmodified current Color3.
  185. */
  186. Color3.prototype.addToRef = function (otherColor, result) {
  187. result.r = this.r + otherColor.r;
  188. result.g = this.g + otherColor.g;
  189. result.b = this.b + otherColor.b;
  190. return this;
  191. };
  192. /**
  193. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  194. */
  195. Color3.prototype.subtract = function (otherColor) {
  196. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  197. };
  198. /**
  199. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  200. * Returns the unmodified current Color3.
  201. */
  202. Color3.prototype.subtractToRef = function (otherColor, result) {
  203. result.r = this.r - otherColor.r;
  204. result.g = this.g - otherColor.g;
  205. result.b = this.b - otherColor.b;
  206. return this;
  207. };
  208. /**
  209. * Returns a new Color3 copied the current one.
  210. */
  211. Color3.prototype.clone = function () {
  212. return new Color3(this.r, this.g, this.b);
  213. };
  214. /**
  215. * Copies the rgb values from the source in the current Color3.
  216. * Returns the updated Color3.
  217. */
  218. Color3.prototype.copyFrom = function (source) {
  219. this.r = source.r;
  220. this.g = source.g;
  221. this.b = source.b;
  222. return this;
  223. };
  224. /**
  225. * Updates the Color3 rgb values from the passed floats.
  226. * Returns the Color3.
  227. */
  228. Color3.prototype.copyFromFloats = function (r, g, b) {
  229. this.r = r;
  230. this.g = g;
  231. this.b = b;
  232. return this;
  233. };
  234. /**
  235. * Updates the Color3 rgb values from the passed floats.
  236. * Returns the Color3.
  237. */
  238. Color3.prototype.set = function (r, g, b) {
  239. return this.copyFromFloats(r, g, b);
  240. };
  241. /**
  242. * Returns the Color3 hexadecimal code as a string.
  243. */
  244. Color3.prototype.toHexString = function () {
  245. var intR = (this.r * 255) | 0;
  246. var intG = (this.g * 255) | 0;
  247. var intB = (this.b * 255) | 0;
  248. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  249. };
  250. /**
  251. * Returns a new Color3 converted to linear space.
  252. */
  253. Color3.prototype.toLinearSpace = function () {
  254. var convertedColor = new Color3();
  255. this.toLinearSpaceToRef(convertedColor);
  256. return convertedColor;
  257. };
  258. /**
  259. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  260. * Returns the unmodified Color3.
  261. */
  262. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  263. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  264. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  265. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  266. return this;
  267. };
  268. /**
  269. * Returns a new Color3 converted to gamma space.
  270. */
  271. Color3.prototype.toGammaSpace = function () {
  272. var convertedColor = new Color3();
  273. this.toGammaSpaceToRef(convertedColor);
  274. return convertedColor;
  275. };
  276. /**
  277. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  278. * Returns the unmodified Color3.
  279. */
  280. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  281. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  282. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  283. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  284. return this;
  285. };
  286. // Statics
  287. /**
  288. * Creates a new Color3 from the string containing valid hexadecimal values.
  289. */
  290. Color3.FromHexString = function (hex) {
  291. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  292. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  293. return new Color3(0, 0, 0);
  294. }
  295. var r = parseInt(hex.substring(1, 3), 16);
  296. var g = parseInt(hex.substring(3, 5), 16);
  297. var b = parseInt(hex.substring(5, 7), 16);
  298. return Color3.FromInts(r, g, b);
  299. };
  300. /**
  301. * Creates a new Vector3 from the startind index of the passed array.
  302. */
  303. Color3.FromArray = function (array, offset) {
  304. if (offset === void 0) { offset = 0; }
  305. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  306. };
  307. /**
  308. * Creates a new Color3 from integer values ( < 256).
  309. */
  310. Color3.FromInts = function (r, g, b) {
  311. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  312. };
  313. /**
  314. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  315. */
  316. Color3.Lerp = function (start, end, amount) {
  317. var r = start.r + ((end.r - start.r) * amount);
  318. var g = start.g + ((end.g - start.g) * amount);
  319. var b = start.b + ((end.b - start.b) * amount);
  320. return new Color3(r, g, b);
  321. };
  322. Color3.Red = function () { return new Color3(1, 0, 0); };
  323. Color3.Green = function () { return new Color3(0, 1, 0); };
  324. Color3.Blue = function () { return new Color3(0, 0, 1); };
  325. Color3.Black = function () { return new Color3(0, 0, 0); };
  326. Color3.White = function () { return new Color3(1, 1, 1); };
  327. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  328. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  329. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  330. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  331. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  332. return Color3;
  333. }());
  334. BABYLON.Color3 = Color3;
  335. var Color4 = (function () {
  336. /**
  337. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  338. */
  339. function Color4(r, g, b, a) {
  340. this.r = r;
  341. this.g = g;
  342. this.b = b;
  343. this.a = a;
  344. }
  345. // Operators
  346. /**
  347. * Adds in place the passed Color4 values to the current Color4.
  348. * Returns the updated Color4.
  349. */
  350. Color4.prototype.addInPlace = function (right) {
  351. this.r += right.r;
  352. this.g += right.g;
  353. this.b += right.b;
  354. this.a += right.a;
  355. return this;
  356. };
  357. /**
  358. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  359. */
  360. Color4.prototype.asArray = function () {
  361. var result = [];
  362. this.toArray(result, 0);
  363. return result;
  364. };
  365. /**
  366. * Stores from the starting index in the passed array the Color4 successive values.
  367. * Returns the Color4.
  368. */
  369. Color4.prototype.toArray = function (array, index) {
  370. if (index === undefined) {
  371. index = 0;
  372. }
  373. array[index] = this.r;
  374. array[index + 1] = this.g;
  375. array[index + 2] = this.b;
  376. array[index + 3] = this.a;
  377. return this;
  378. };
  379. /**
  380. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  381. */
  382. Color4.prototype.add = function (right) {
  383. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  384. };
  385. /**
  386. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  387. */
  388. Color4.prototype.subtract = function (right) {
  389. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  390. };
  391. /**
  392. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  393. * Returns the Color4.
  394. */
  395. Color4.prototype.subtractToRef = function (right, result) {
  396. result.r = this.r - right.r;
  397. result.g = this.g - right.g;
  398. result.b = this.b - right.b;
  399. result.a = this.a - right.a;
  400. return this;
  401. };
  402. /**
  403. * Creates a new Color4 with the current Color4 values multiplied by scale.
  404. */
  405. Color4.prototype.scale = function (scale) {
  406. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  407. };
  408. /**
  409. * Multiplies the current Color4 values by scale and stores the result in "result".
  410. * Returns the Color4.
  411. */
  412. Color4.prototype.scaleToRef = function (scale, result) {
  413. result.r = this.r * scale;
  414. result.g = this.g * scale;
  415. result.b = this.b * scale;
  416. result.a = this.a * scale;
  417. return this;
  418. };
  419. /**
  420. * Multipy an RGBA Color4 value by another and return a new Color4 object
  421. * @param color The Color4 (RGBA) value to multiply by
  422. * @returns A new Color4.
  423. */
  424. Color4.prototype.multiply = function (color) {
  425. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  426. };
  427. /**
  428. * Multipy an RGBA Color4 value by another and push the result in a reference value
  429. * @param color The Color4 (RGBA) value to multiply by
  430. * @param result The Color4 (RGBA) to fill the result in
  431. * @returns the result Color4.
  432. */
  433. Color4.prototype.multiplyToRef = function (color, result) {
  434. result.r = this.r * color.r;
  435. result.g = this.g * color.g;
  436. result.b = this.b * color.b;
  437. result.a = this.a * color.a;
  438. return result;
  439. };
  440. /**
  441. * Returns a string with the Color4 values.
  442. */
  443. Color4.prototype.toString = function () {
  444. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  445. };
  446. /**
  447. * Returns the string "Color4"
  448. */
  449. Color4.prototype.getClassName = function () {
  450. return "Color4";
  451. };
  452. /**
  453. * Return the Color4 hash code as a number.
  454. */
  455. Color4.prototype.getHashCode = function () {
  456. var hash = this.r || 0;
  457. hash = (hash * 397) ^ (this.g || 0);
  458. hash = (hash * 397) ^ (this.b || 0);
  459. hash = (hash * 397) ^ (this.a || 0);
  460. return hash;
  461. };
  462. /**
  463. * Creates a new Color4 copied from the current one.
  464. */
  465. Color4.prototype.clone = function () {
  466. return new Color4(this.r, this.g, this.b, this.a);
  467. };
  468. /**
  469. * Copies the passed Color4 values into the current one.
  470. * Returns the updated Color4.
  471. */
  472. Color4.prototype.copyFrom = function (source) {
  473. this.r = source.r;
  474. this.g = source.g;
  475. this.b = source.b;
  476. this.a = source.a;
  477. return this;
  478. };
  479. /**
  480. * Copies the passed float values into the current one.
  481. * Returns the updated Color4.
  482. */
  483. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  484. this.r = r;
  485. this.g = g;
  486. this.b = b;
  487. this.a = a;
  488. return this;
  489. };
  490. /**
  491. * Copies the passed float values into the current one.
  492. * Returns the updated Color4.
  493. */
  494. Color4.prototype.set = function (r, g, b, a) {
  495. return this.copyFromFloats(r, g, b, a);
  496. };
  497. /**
  498. * Returns a string containing the hexadecimal Color4 code.
  499. */
  500. Color4.prototype.toHexString = function () {
  501. var intR = (this.r * 255) | 0;
  502. var intG = (this.g * 255) | 0;
  503. var intB = (this.b * 255) | 0;
  504. var intA = (this.a * 255) | 0;
  505. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  506. };
  507. // Statics
  508. /**
  509. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  510. */
  511. Color4.FromHexString = function (hex) {
  512. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  513. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  514. return new Color4(0.0, 0.0, 0.0, 0.0);
  515. }
  516. var r = parseInt(hex.substring(1, 3), 16);
  517. var g = parseInt(hex.substring(3, 5), 16);
  518. var b = parseInt(hex.substring(5, 7), 16);
  519. var a = parseInt(hex.substring(7, 9), 16);
  520. return Color4.FromInts(r, g, b, a);
  521. };
  522. /**
  523. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  524. */
  525. Color4.Lerp = function (left, right, amount) {
  526. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  527. Color4.LerpToRef(left, right, amount, result);
  528. return result;
  529. };
  530. /**
  531. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  532. */
  533. Color4.LerpToRef = function (left, right, amount, result) {
  534. result.r = left.r + (right.r - left.r) * amount;
  535. result.g = left.g + (right.g - left.g) * amount;
  536. result.b = left.b + (right.b - left.b) * amount;
  537. result.a = left.a + (right.a - left.a) * amount;
  538. };
  539. /**
  540. * Creates a new Color4 from the starting index element of the passed array.
  541. */
  542. Color4.FromArray = function (array, offset) {
  543. if (offset === void 0) { offset = 0; }
  544. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  545. };
  546. /**
  547. * Creates a new Color4 from the passed integers ( < 256 ).
  548. */
  549. Color4.FromInts = function (r, g, b, a) {
  550. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  551. };
  552. Color4.CheckColors4 = function (colors, count) {
  553. // Check if color3 was used
  554. if (colors.length === count * 3) {
  555. var colors4 = [];
  556. for (var index = 0; index < colors.length; index += 3) {
  557. var newIndex = (index / 3) * 4;
  558. colors4[newIndex] = colors[index];
  559. colors4[newIndex + 1] = colors[index + 1];
  560. colors4[newIndex + 2] = colors[index + 2];
  561. colors4[newIndex + 3] = 1.0;
  562. }
  563. return colors4;
  564. }
  565. return colors;
  566. };
  567. return Color4;
  568. }());
  569. BABYLON.Color4 = Color4;
  570. var Vector2 = (function () {
  571. /**
  572. * Creates a new Vector2 from the passed x and y coordinates.
  573. */
  574. function Vector2(x, y) {
  575. this.x = x;
  576. this.y = y;
  577. }
  578. /**
  579. * Returns a string with the Vector2 coordinates.
  580. */
  581. Vector2.prototype.toString = function () {
  582. return "{X: " + this.x + " Y:" + this.y + "}";
  583. };
  584. /**
  585. * Returns the string "Vector2"
  586. */
  587. Vector2.prototype.getClassName = function () {
  588. return "Vector2";
  589. };
  590. /**
  591. * Returns the Vector2 hash code as a number.
  592. */
  593. Vector2.prototype.getHashCode = function () {
  594. var hash = this.x || 0;
  595. hash = (hash * 397) ^ (this.y || 0);
  596. return hash;
  597. };
  598. // Operators
  599. /**
  600. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  601. * Returns the Vector2.
  602. */
  603. Vector2.prototype.toArray = function (array, index) {
  604. if (index === void 0) { index = 0; }
  605. array[index] = this.x;
  606. array[index + 1] = this.y;
  607. return this;
  608. };
  609. /**
  610. * Returns a new array with 2 elements : the Vector2 coordinates.
  611. */
  612. Vector2.prototype.asArray = function () {
  613. var result = [];
  614. this.toArray(result, 0);
  615. return result;
  616. };
  617. /**
  618. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  619. * Returns the updated Vector2.
  620. */
  621. Vector2.prototype.copyFrom = function (source) {
  622. this.x = source.x;
  623. this.y = source.y;
  624. return this;
  625. };
  626. /**
  627. * Sets the Vector2 coordinates with the passed floats.
  628. * Returns the updated Vector2.
  629. */
  630. Vector2.prototype.copyFromFloats = function (x, y) {
  631. this.x = x;
  632. this.y = y;
  633. return this;
  634. };
  635. /**
  636. * Sets the Vector2 coordinates with the passed floats.
  637. * Returns the updated Vector2.
  638. */
  639. Vector2.prototype.set = function (x, y) {
  640. return this.copyFromFloats(x, y);
  641. };
  642. /**
  643. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  644. */
  645. Vector2.prototype.add = function (otherVector) {
  646. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  647. };
  648. /**
  649. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  650. * Returns the Vector2.
  651. */
  652. Vector2.prototype.addToRef = function (otherVector, result) {
  653. result.x = this.x + otherVector.x;
  654. result.y = this.y + otherVector.y;
  655. return this;
  656. };
  657. /**
  658. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  659. * Returns the updated Vector2.
  660. */
  661. Vector2.prototype.addInPlace = function (otherVector) {
  662. this.x += otherVector.x;
  663. this.y += otherVector.y;
  664. return this;
  665. };
  666. /**
  667. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  668. */
  669. Vector2.prototype.addVector3 = function (otherVector) {
  670. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  671. };
  672. /**
  673. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  674. */
  675. Vector2.prototype.subtract = function (otherVector) {
  676. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  677. };
  678. /**
  679. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  680. * Returns the Vector2.
  681. */
  682. Vector2.prototype.subtractToRef = function (otherVector, result) {
  683. result.x = this.x - otherVector.x;
  684. result.y = this.y - otherVector.y;
  685. return this;
  686. };
  687. /**
  688. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  689. * Returns the updated Vector2.
  690. */
  691. Vector2.prototype.subtractInPlace = function (otherVector) {
  692. this.x -= otherVector.x;
  693. this.y -= otherVector.y;
  694. return this;
  695. };
  696. /**
  697. * Multiplies in place the current Vector2 coordinates by the passed ones.
  698. * Returns the updated Vector2.
  699. */
  700. Vector2.prototype.multiplyInPlace = function (otherVector) {
  701. this.x *= otherVector.x;
  702. this.y *= otherVector.y;
  703. return this;
  704. };
  705. /**
  706. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  707. */
  708. Vector2.prototype.multiply = function (otherVector) {
  709. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  710. };
  711. /**
  712. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  713. * Returns the Vector2.
  714. */
  715. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  716. result.x = this.x * otherVector.x;
  717. result.y = this.y * otherVector.y;
  718. return this;
  719. };
  720. /**
  721. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  722. */
  723. Vector2.prototype.multiplyByFloats = function (x, y) {
  724. return new Vector2(this.x * x, this.y * y);
  725. };
  726. /**
  727. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  728. */
  729. Vector2.prototype.divide = function (otherVector) {
  730. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  731. };
  732. /**
  733. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  734. * Returns the Vector2.
  735. */
  736. Vector2.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. return this;
  740. };
  741. /**
  742. * Returns a new Vector2 with current Vector2 negated coordinates.
  743. */
  744. Vector2.prototype.negate = function () {
  745. return new Vector2(-this.x, -this.y);
  746. };
  747. /**
  748. * Multiply the Vector2 coordinates by scale.
  749. * Returns the updated Vector2.
  750. */
  751. Vector2.prototype.scaleInPlace = function (scale) {
  752. this.x *= scale;
  753. this.y *= scale;
  754. return this;
  755. };
  756. /**
  757. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  758. */
  759. Vector2.prototype.scale = function (scale) {
  760. return new Vector2(this.x * scale, this.y * scale);
  761. };
  762. /**
  763. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  764. */
  765. Vector2.prototype.equals = function (otherVector) {
  766. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  767. };
  768. /**
  769. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  770. */
  771. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  772. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  773. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  774. };
  775. // Properties
  776. /**
  777. * Returns the vector length (float).
  778. */
  779. Vector2.prototype.length = function () {
  780. return Math.sqrt(this.x * this.x + this.y * this.y);
  781. };
  782. /**
  783. * Returns the vector squared length (float);
  784. */
  785. Vector2.prototype.lengthSquared = function () {
  786. return (this.x * this.x + this.y * this.y);
  787. };
  788. // Methods
  789. /**
  790. * Normalize the vector.
  791. * Returns the updated Vector2.
  792. */
  793. Vector2.prototype.normalize = function () {
  794. var len = this.length();
  795. if (len === 0)
  796. return this;
  797. var num = 1.0 / len;
  798. this.x *= num;
  799. this.y *= num;
  800. return this;
  801. };
  802. /**
  803. * Returns a new Vector2 copied from the Vector2.
  804. */
  805. Vector2.prototype.clone = function () {
  806. return new Vector2(this.x, this.y);
  807. };
  808. // Statics
  809. /**
  810. * Returns a new Vector2(0, 0)
  811. */
  812. Vector2.Zero = function () {
  813. return new Vector2(0, 0);
  814. };
  815. /**
  816. * Returns a new Vector2 set from the passed index element of the passed array or Float32Array.
  817. */
  818. Vector2.FromArray = function (array, offset) {
  819. if (offset === void 0) { offset = 0; }
  820. return new Vector2(array[offset], array[offset + 1]);
  821. };
  822. /**
  823. * Sets "result" from the passed index element of the passed array or Float32Array.
  824. * Returns the Vector2.
  825. */
  826. Vector2.FromArrayToRef = function (array, offset, result) {
  827. result.x = array[offset];
  828. result.y = array[offset + 1];
  829. };
  830. /**
  831. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  832. */
  833. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  834. var squared = amount * amount;
  835. var cubed = amount * squared;
  836. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  837. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  838. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  839. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  840. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  841. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  842. return new Vector2(x, y);
  843. };
  844. /**
  845. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  846. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  847. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  848. */
  849. Vector2.Clamp = function (value, min, max) {
  850. var x = value.x;
  851. x = (x > max.x) ? max.x : x;
  852. x = (x < min.x) ? min.x : x;
  853. var y = value.y;
  854. y = (y > max.y) ? max.y : y;
  855. y = (y < min.y) ? min.y : y;
  856. return new Vector2(x, y);
  857. };
  858. /**
  859. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  860. */
  861. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  862. var squared = amount * amount;
  863. var cubed = amount * squared;
  864. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  865. var part2 = (-2.0 * cubed) + (3.0 * squared);
  866. var part3 = (cubed - (2.0 * squared)) + amount;
  867. var part4 = cubed - squared;
  868. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  869. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  870. return new Vector2(x, y);
  871. };
  872. /**
  873. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  874. */
  875. Vector2.Lerp = function (start, end, amount) {
  876. var x = start.x + ((end.x - start.x) * amount);
  877. var y = start.y + ((end.y - start.y) * amount);
  878. return new Vector2(x, y);
  879. };
  880. /**
  881. * Returns the dot product (float) of the vector "left" and the vector "right".
  882. */
  883. Vector2.Dot = function (left, right) {
  884. return left.x * right.x + left.y * right.y;
  885. };
  886. /**
  887. * Returns a new Vector2 equal to the normalized passed vector.
  888. */
  889. Vector2.Normalize = function (vector) {
  890. var newVector = vector.clone();
  891. newVector.normalize();
  892. return newVector;
  893. };
  894. /**
  895. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  896. */
  897. Vector2.Minimize = function (left, right) {
  898. var x = (left.x < right.x) ? left.x : right.x;
  899. var y = (left.y < right.y) ? left.y : right.y;
  900. return new Vector2(x, y);
  901. };
  902. /**
  903. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  904. */
  905. Vector2.Maximize = function (left, right) {
  906. var x = (left.x > right.x) ? left.x : right.x;
  907. var y = (left.y > right.y) ? left.y : right.y;
  908. return new Vector2(x, y);
  909. };
  910. /**
  911. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  912. */
  913. Vector2.Transform = function (vector, transformation) {
  914. var r = Vector2.Zero();
  915. Vector2.TransformToRef(vector, transformation, r);
  916. return r;
  917. };
  918. /**
  919. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  920. */
  921. Vector2.TransformToRef = function (vector, transformation, result) {
  922. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  923. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  924. result.x = x;
  925. result.y = y;
  926. };
  927. /**
  928. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  929. */
  930. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  931. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  932. var sign = a < 0 ? -1 : 1;
  933. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  934. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  935. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  936. };
  937. /**
  938. * Returns the distance (float) between the vectors "value1" and "value2".
  939. */
  940. Vector2.Distance = function (value1, value2) {
  941. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  942. };
  943. /**
  944. * Returns the squared distance (float) between the vectors "value1" and "value2".
  945. */
  946. Vector2.DistanceSquared = function (value1, value2) {
  947. var x = value1.x - value2.x;
  948. var y = value1.y - value2.y;
  949. return (x * x) + (y * y);
  950. };
  951. /**
  952. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  953. */
  954. Vector2.Center = function (value1, value2) {
  955. var center = value1.add(value2);
  956. center.scaleInPlace(0.5);
  957. return center;
  958. };
  959. /**
  960. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  961. */
  962. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  963. var l2 = Vector2.DistanceSquared(segA, segB);
  964. if (l2 === 0.0) {
  965. return Vector2.Distance(p, segA);
  966. }
  967. var v = segB.subtract(segA);
  968. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  969. var proj = segA.add(v.multiplyByFloats(t, t));
  970. return Vector2.Distance(p, proj);
  971. };
  972. return Vector2;
  973. }());
  974. BABYLON.Vector2 = Vector2;
  975. var Vector3 = (function () {
  976. /**
  977. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  978. * A Vector3 is the main object used in 3D geometry.
  979. * It can represent etiher the coordinates of a point the space, either a direction.
  980. */
  981. function Vector3(x, y, z) {
  982. this.x = x;
  983. this.y = y;
  984. this.z = z;
  985. }
  986. /**
  987. * Returns a string with the Vector3 coordinates.
  988. */
  989. Vector3.prototype.toString = function () {
  990. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  991. };
  992. /**
  993. * Returns the string "Vector3"
  994. */
  995. Vector3.prototype.getClassName = function () {
  996. return "Vector3";
  997. };
  998. /**
  999. * Returns the Vector hash code.
  1000. */
  1001. Vector3.prototype.getHashCode = function () {
  1002. var hash = this.x || 0;
  1003. hash = (hash * 397) ^ (this.y || 0);
  1004. hash = (hash * 397) ^ (this.z || 0);
  1005. return hash;
  1006. };
  1007. // Operators
  1008. /**
  1009. * Returns a new array with three elements : the coordinates the Vector3.
  1010. */
  1011. Vector3.prototype.asArray = function () {
  1012. var result = [];
  1013. this.toArray(result, 0);
  1014. return result;
  1015. };
  1016. /**
  1017. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1018. * Returns the Vector3.
  1019. */
  1020. Vector3.prototype.toArray = function (array, index) {
  1021. if (index === void 0) { index = 0; }
  1022. array[index] = this.x;
  1023. array[index + 1] = this.y;
  1024. array[index + 2] = this.z;
  1025. return this;
  1026. };
  1027. /**
  1028. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1029. */
  1030. Vector3.prototype.toQuaternion = function () {
  1031. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1032. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1033. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1034. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1035. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1036. var cosy = Math.cos(this.y * 0.5);
  1037. var siny = Math.sin(this.y * 0.5);
  1038. result.x = coszMinusx * siny;
  1039. result.y = -sinzMinusx * siny;
  1040. result.z = sinxPlusz * cosy;
  1041. result.w = cosxPlusz * cosy;
  1042. return result;
  1043. };
  1044. /**
  1045. * Adds the passed vector to the current Vector3.
  1046. * Returns the updated Vector3.
  1047. */
  1048. Vector3.prototype.addInPlace = function (otherVector) {
  1049. this.x += otherVector.x;
  1050. this.y += otherVector.y;
  1051. this.z += otherVector.z;
  1052. return this;
  1053. };
  1054. /**
  1055. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1056. */
  1057. Vector3.prototype.add = function (otherVector) {
  1058. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1059. };
  1060. /**
  1061. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1062. * Returns the current Vector3.
  1063. */
  1064. Vector3.prototype.addToRef = function (otherVector, result) {
  1065. result.x = this.x + otherVector.x;
  1066. result.y = this.y + otherVector.y;
  1067. result.z = this.z + otherVector.z;
  1068. return this;
  1069. };
  1070. /**
  1071. * Subtract the passed vector from the current Vector3.
  1072. * Returns the updated Vector3.
  1073. */
  1074. Vector3.prototype.subtractInPlace = function (otherVector) {
  1075. this.x -= otherVector.x;
  1076. this.y -= otherVector.y;
  1077. this.z -= otherVector.z;
  1078. return this;
  1079. };
  1080. /**
  1081. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1082. */
  1083. Vector3.prototype.subtract = function (otherVector) {
  1084. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1085. };
  1086. /**
  1087. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1088. * Returns the current Vector3.
  1089. */
  1090. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1091. result.x = this.x - otherVector.x;
  1092. result.y = this.y - otherVector.y;
  1093. result.z = this.z - otherVector.z;
  1094. return this;
  1095. };
  1096. /**
  1097. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1098. */
  1099. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1100. return new Vector3(this.x - x, this.y - y, this.z - z);
  1101. };
  1102. /**
  1103. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1104. * Returns the current Vector3.
  1105. */
  1106. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1107. result.x = this.x - x;
  1108. result.y = this.y - y;
  1109. result.z = this.z - z;
  1110. return this;
  1111. };
  1112. /**
  1113. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1114. */
  1115. Vector3.prototype.negate = function () {
  1116. return new Vector3(-this.x, -this.y, -this.z);
  1117. };
  1118. /**
  1119. * Multiplies the Vector3 coordinates by the float "scale".
  1120. * Returns the updated Vector3.
  1121. */
  1122. Vector3.prototype.scaleInPlace = function (scale) {
  1123. this.x *= scale;
  1124. this.y *= scale;
  1125. this.z *= scale;
  1126. return this;
  1127. };
  1128. /**
  1129. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1130. */
  1131. Vector3.prototype.scale = function (scale) {
  1132. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1133. };
  1134. /**
  1135. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1136. * Returns the current Vector3.
  1137. */
  1138. Vector3.prototype.scaleToRef = function (scale, result) {
  1139. result.x = this.x * scale;
  1140. result.y = this.y * scale;
  1141. result.z = this.z * scale;
  1142. return this;
  1143. };
  1144. /**
  1145. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1146. */
  1147. Vector3.prototype.equals = function (otherVector) {
  1148. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1149. };
  1150. /**
  1151. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1152. */
  1153. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1154. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1155. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1156. };
  1157. /**
  1158. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1159. */
  1160. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1161. return this.x === x && this.y === y && this.z === z;
  1162. };
  1163. /**
  1164. * Muliplies the current Vector3 coordinates by the passed ones.
  1165. * Returns the updated Vector3.
  1166. */
  1167. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1168. this.x *= otherVector.x;
  1169. this.y *= otherVector.y;
  1170. this.z *= otherVector.z;
  1171. return this;
  1172. };
  1173. /**
  1174. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1175. */
  1176. Vector3.prototype.multiply = function (otherVector) {
  1177. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1178. };
  1179. /**
  1180. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1181. * Returns the current Vector3.
  1182. */
  1183. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1184. result.x = this.x * otherVector.x;
  1185. result.y = this.y * otherVector.y;
  1186. result.z = this.z * otherVector.z;
  1187. return this;
  1188. };
  1189. /**
  1190. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1191. */
  1192. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1193. return new Vector3(this.x * x, this.y * y, this.z * z);
  1194. };
  1195. /**
  1196. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1197. */
  1198. Vector3.prototype.divide = function (otherVector) {
  1199. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1200. };
  1201. /**
  1202. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1203. * Returns the current Vector3.
  1204. */
  1205. Vector3.prototype.divideToRef = function (otherVector, result) {
  1206. result.x = this.x / otherVector.x;
  1207. result.y = this.y / otherVector.y;
  1208. result.z = this.z / otherVector.z;
  1209. return this;
  1210. };
  1211. /**
  1212. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1213. * Returns the updated Vector3.
  1214. */
  1215. Vector3.prototype.MinimizeInPlace = function (other) {
  1216. if (other.x < this.x)
  1217. this.x = other.x;
  1218. if (other.y < this.y)
  1219. this.y = other.y;
  1220. if (other.z < this.z)
  1221. this.z = other.z;
  1222. return this;
  1223. };
  1224. /**
  1225. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1226. * Returns the updated Vector3.
  1227. */
  1228. Vector3.prototype.MaximizeInPlace = function (other) {
  1229. if (other.x > this.x)
  1230. this.x = other.x;
  1231. if (other.y > this.y)
  1232. this.y = other.y;
  1233. if (other.z > this.z)
  1234. this.z = other.z;
  1235. return this;
  1236. };
  1237. // Properties
  1238. /**
  1239. * Returns the length of the Vector3 (float).
  1240. */
  1241. Vector3.prototype.length = function () {
  1242. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1243. };
  1244. /**
  1245. * Returns the squared length of the Vector3 (float).
  1246. */
  1247. Vector3.prototype.lengthSquared = function () {
  1248. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1249. };
  1250. // Methods
  1251. /**
  1252. * Normalize the current Vector3.
  1253. * Returns the updated Vector3.
  1254. */
  1255. Vector3.prototype.normalize = function () {
  1256. var len = this.length();
  1257. if (len === 0 || len === 1.0)
  1258. return this;
  1259. var num = 1.0 / len;
  1260. this.x *= num;
  1261. this.y *= num;
  1262. this.z *= num;
  1263. return this;
  1264. };
  1265. /**
  1266. * Returns a new Vector3 copied from the current Vector3.
  1267. */
  1268. Vector3.prototype.clone = function () {
  1269. return new Vector3(this.x, this.y, this.z);
  1270. };
  1271. /**
  1272. * Copies the passed vector coordinates to the current Vector3 ones.
  1273. * Returns the updated Vector3.
  1274. */
  1275. Vector3.prototype.copyFrom = function (source) {
  1276. this.x = source.x;
  1277. this.y = source.y;
  1278. this.z = source.z;
  1279. return this;
  1280. };
  1281. /**
  1282. * Copies the passed floats to the current Vector3 coordinates.
  1283. * Returns the updated Vector3.
  1284. */
  1285. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1286. this.x = x;
  1287. this.y = y;
  1288. this.z = z;
  1289. return this;
  1290. };
  1291. /**
  1292. * Copies the passed floats to the current Vector3 coordinates.
  1293. * Returns the updated Vector3.
  1294. */
  1295. Vector3.prototype.set = function (x, y, z) {
  1296. return this.copyFromFloats(x, y, z);
  1297. };
  1298. // Statics
  1299. /**
  1300. *
  1301. */
  1302. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1303. var d0 = Vector3.Dot(vector0, axis) - size;
  1304. var d1 = Vector3.Dot(vector1, axis) - size;
  1305. var s = d0 / (d0 - d1);
  1306. return s;
  1307. };
  1308. /**
  1309. * Returns a new Vector3 set from the index "offset" of the passed array or Float32Array.
  1310. */
  1311. Vector3.FromArray = function (array, offset) {
  1312. if (!offset) {
  1313. offset = 0;
  1314. }
  1315. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1316. };
  1317. /**
  1318. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1319. */
  1320. Vector3.FromFloatArray = function (array, offset) {
  1321. if (!offset) {
  1322. offset = 0;
  1323. }
  1324. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1325. };
  1326. /**
  1327. * Sets the passed vector "result" with the element values from the index "offset" of the passed array or Float32Array.
  1328. */
  1329. Vector3.FromArrayToRef = function (array, offset, result) {
  1330. result.x = array[offset];
  1331. result.y = array[offset + 1];
  1332. result.z = array[offset + 2];
  1333. };
  1334. /**
  1335. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1336. */
  1337. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. };
  1342. /**
  1343. * Sets the passed vector "result" with the passed floats.
  1344. */
  1345. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1346. result.x = x;
  1347. result.y = y;
  1348. result.z = z;
  1349. };
  1350. /**
  1351. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1352. */
  1353. Vector3.Zero = function () {
  1354. return new Vector3(0.0, 0.0, 0.0);
  1355. };
  1356. /**
  1357. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1358. */
  1359. Vector3.Up = function () {
  1360. return new Vector3(0.0, 1.0, 0.0);
  1361. };
  1362. /**
  1363. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1364. */
  1365. Vector3.Forward = function () {
  1366. return new Vector3(0.0, 0.0, 1.0);
  1367. };
  1368. /**
  1369. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1370. */
  1371. Vector3.Right = function () {
  1372. return new Vector3(1.0, 0.0, 0.0);
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1376. */
  1377. Vector3.Left = function () {
  1378. return new Vector3(-1.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1382. * This method computes tranformed coordinates only, not transformed direction vectors.
  1383. */
  1384. Vector3.TransformCoordinates = function (vector, transformation) {
  1385. var result = Vector3.Zero();
  1386. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1387. return result;
  1388. };
  1389. /**
  1390. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1391. * This method computes tranformed coordinates only, not transformed direction vectors.
  1392. */
  1393. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1394. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1395. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1396. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1397. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1398. result.x = x / w;
  1399. result.y = y / w;
  1400. result.z = z / w;
  1401. };
  1402. /**
  1403. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1404. * This method computes tranformed coordinates only, not transformed direction vectors.
  1405. */
  1406. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1407. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1408. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1409. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1410. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1411. result.x = rx / rw;
  1412. result.y = ry / rw;
  1413. result.z = rz / rw;
  1414. };
  1415. /**
  1416. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1417. * This methods computes transformed normalized direction vectors only.
  1418. */
  1419. Vector3.TransformNormal = function (vector, transformation) {
  1420. var result = Vector3.Zero();
  1421. Vector3.TransformNormalToRef(vector, transformation, result);
  1422. return result;
  1423. };
  1424. /**
  1425. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1426. * This methods computes transformed normalized direction vectors only.
  1427. */
  1428. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1429. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1430. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1431. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1432. result.x = x;
  1433. result.y = y;
  1434. result.z = z;
  1435. };
  1436. /**
  1437. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1438. * This methods computes transformed normalized direction vectors only.
  1439. */
  1440. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1441. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1442. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1443. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1444. };
  1445. /**
  1446. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1447. */
  1448. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1449. var squared = amount * amount;
  1450. var cubed = amount * squared;
  1451. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1452. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1453. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1454. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1455. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1456. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1457. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1458. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1459. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1460. return new Vector3(x, y, z);
  1461. };
  1462. /**
  1463. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1464. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1465. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1466. */
  1467. Vector3.Clamp = function (value, min, max) {
  1468. var x = value.x;
  1469. x = (x > max.x) ? max.x : x;
  1470. x = (x < min.x) ? min.x : x;
  1471. var y = value.y;
  1472. y = (y > max.y) ? max.y : y;
  1473. y = (y < min.y) ? min.y : y;
  1474. var z = value.z;
  1475. z = (z > max.z) ? max.z : z;
  1476. z = (z < min.z) ? min.z : z;
  1477. return new Vector3(x, y, z);
  1478. };
  1479. /**
  1480. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1481. */
  1482. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1483. var squared = amount * amount;
  1484. var cubed = amount * squared;
  1485. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1486. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1487. var part3 = (cubed - (2.0 * squared)) + amount;
  1488. var part4 = cubed - squared;
  1489. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1490. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1491. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1492. return new Vector3(x, y, z);
  1493. };
  1494. /**
  1495. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1496. */
  1497. Vector3.Lerp = function (start, end, amount) {
  1498. var result = new Vector3(0, 0, 0);
  1499. Vector3.LerpToRef(start, end, amount, result);
  1500. return result;
  1501. };
  1502. /**
  1503. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1504. */
  1505. Vector3.LerpToRef = function (start, end, amount, result) {
  1506. result.x = start.x + ((end.x - start.x) * amount);
  1507. result.y = start.y + ((end.y - start.y) * amount);
  1508. result.z = start.z + ((end.z - start.z) * amount);
  1509. };
  1510. /**
  1511. * Returns the dot product (float) between the vectors "left" and "right".
  1512. */
  1513. Vector3.Dot = function (left, right) {
  1514. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1515. };
  1516. /**
  1517. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1518. * The cross product is then orthogonal to both "left" and "right".
  1519. */
  1520. Vector3.Cross = function (left, right) {
  1521. var result = Vector3.Zero();
  1522. Vector3.CrossToRef(left, right, result);
  1523. return result;
  1524. };
  1525. /**
  1526. * Sets the passed vector "result" with the cross product of "left" and "right".
  1527. * The cross product is then orthogonal to both "left" and "right".
  1528. */
  1529. Vector3.CrossToRef = function (left, right, result) {
  1530. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1531. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1532. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1533. result.copyFrom(MathTmp.Vector3[0]);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 as the normalization of the passed vector.
  1537. */
  1538. Vector3.Normalize = function (vector) {
  1539. var result = Vector3.Zero();
  1540. Vector3.NormalizeToRef(vector, result);
  1541. return result;
  1542. };
  1543. /**
  1544. * Sets the passed vector "result" with the normalization of the passed first vector.
  1545. */
  1546. Vector3.NormalizeToRef = function (vector, result) {
  1547. result.copyFrom(vector);
  1548. result.normalize();
  1549. };
  1550. Vector3.Project = function (vector, world, transform, viewport) {
  1551. var cw = viewport.width;
  1552. var ch = viewport.height;
  1553. var cx = viewport.x;
  1554. var cy = viewport.y;
  1555. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1556. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1557. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1558. world.multiplyToRef(transform, matrix);
  1559. matrix.multiplyToRef(viewportMatrix, matrix);
  1560. return Vector3.TransformCoordinates(vector, matrix);
  1561. };
  1562. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1563. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1564. world.multiplyToRef(transform, matrix);
  1565. matrix.invert();
  1566. source.x = source.x / viewportWidth * 2 - 1;
  1567. source.y = -(source.y / viewportHeight * 2 - 1);
  1568. var vector = Vector3.TransformCoordinates(source, matrix);
  1569. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1570. if (MathTools.WithinEpsilon(num, 1.0)) {
  1571. vector = vector.scale(1.0 / num);
  1572. }
  1573. return vector;
  1574. };
  1575. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1576. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1577. world.multiplyToRef(view, matrix);
  1578. matrix.multiplyToRef(projection, matrix);
  1579. matrix.invert();
  1580. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1581. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1582. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1583. if (MathTools.WithinEpsilon(num, 1.0)) {
  1584. vector = vector.scale(1.0 / num);
  1585. }
  1586. return vector;
  1587. };
  1588. Vector3.Minimize = function (left, right) {
  1589. var min = left.clone();
  1590. min.MinimizeInPlace(right);
  1591. return min;
  1592. };
  1593. Vector3.Maximize = function (left, right) {
  1594. var max = left.clone();
  1595. max.MaximizeInPlace(right);
  1596. return max;
  1597. };
  1598. /**
  1599. * Returns the distance (float) between the vectors "value1" and "value2".
  1600. */
  1601. Vector3.Distance = function (value1, value2) {
  1602. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1603. };
  1604. /**
  1605. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1606. */
  1607. Vector3.DistanceSquared = function (value1, value2) {
  1608. var x = value1.x - value2.x;
  1609. var y = value1.y - value2.y;
  1610. var z = value1.z - value2.z;
  1611. return (x * x) + (y * y) + (z * z);
  1612. };
  1613. /**
  1614. * Returns a new Vector3 located at the center between "value1" and "value2".
  1615. */
  1616. Vector3.Center = function (value1, value2) {
  1617. var center = value1.add(value2);
  1618. center.scaleInPlace(0.5);
  1619. return center;
  1620. };
  1621. /**
  1622. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1623. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1624. * to something in order to rotate it from its local system to the given target system.
  1625. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1626. * Returns a new Vector3.
  1627. */
  1628. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1629. var rotation = Vector3.Zero();
  1630. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1631. return rotation;
  1632. };
  1633. /**
  1634. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1635. */
  1636. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1637. var quat = MathTmp.Quaternion[0];
  1638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1639. quat.toEulerAnglesToRef(ref);
  1640. };
  1641. return Vector3;
  1642. }());
  1643. BABYLON.Vector3 = Vector3;
  1644. //Vector4 class created for EulerAngle class conversion to Quaternion
  1645. var Vector4 = (function () {
  1646. /**
  1647. * Creates a Vector4 object from the passed floats.
  1648. */
  1649. function Vector4(x, y, z, w) {
  1650. this.x = x;
  1651. this.y = y;
  1652. this.z = z;
  1653. this.w = w;
  1654. }
  1655. /**
  1656. * Returns the string with the Vector4 coordinates.
  1657. */
  1658. Vector4.prototype.toString = function () {
  1659. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1660. };
  1661. /**
  1662. * Returns the string "Vector4".
  1663. */
  1664. Vector4.prototype.getClassName = function () {
  1665. return "Vector4";
  1666. };
  1667. /**
  1668. * Returns the Vector4 hash code.
  1669. */
  1670. Vector4.prototype.getHashCode = function () {
  1671. var hash = this.x || 0;
  1672. hash = (hash * 397) ^ (this.y || 0);
  1673. hash = (hash * 397) ^ (this.z || 0);
  1674. hash = (hash * 397) ^ (this.w || 0);
  1675. return hash;
  1676. };
  1677. // Operators
  1678. /**
  1679. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1680. */
  1681. Vector4.prototype.asArray = function () {
  1682. var result = [];
  1683. this.toArray(result, 0);
  1684. return result;
  1685. };
  1686. /**
  1687. * Populates the passed array from the passed index with the Vector4 coordinates.
  1688. * Returns the Vector4.
  1689. */
  1690. Vector4.prototype.toArray = function (array, index) {
  1691. if (index === undefined) {
  1692. index = 0;
  1693. }
  1694. array[index] = this.x;
  1695. array[index + 1] = this.y;
  1696. array[index + 2] = this.z;
  1697. array[index + 3] = this.w;
  1698. return this;
  1699. };
  1700. /**
  1701. * Adds the passed vector to the current Vector4.
  1702. * Returns the updated Vector4.
  1703. */
  1704. Vector4.prototype.addInPlace = function (otherVector) {
  1705. this.x += otherVector.x;
  1706. this.y += otherVector.y;
  1707. this.z += otherVector.z;
  1708. this.w += otherVector.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1713. */
  1714. Vector4.prototype.add = function (otherVector) {
  1715. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1716. };
  1717. /**
  1718. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1719. * Returns the current Vector4.
  1720. */
  1721. Vector4.prototype.addToRef = function (otherVector, result) {
  1722. result.x = this.x + otherVector.x;
  1723. result.y = this.y + otherVector.y;
  1724. result.z = this.z + otherVector.z;
  1725. result.w = this.w + otherVector.w;
  1726. return this;
  1727. };
  1728. /**
  1729. * Subtract in place the passed vector from the current Vector4.
  1730. * Returns the updated Vector4.
  1731. */
  1732. Vector4.prototype.subtractInPlace = function (otherVector) {
  1733. this.x -= otherVector.x;
  1734. this.y -= otherVector.y;
  1735. this.z -= otherVector.z;
  1736. this.w -= otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1741. */
  1742. Vector4.prototype.subtract = function (otherVector) {
  1743. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1744. };
  1745. /**
  1746. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1747. * Returns the current Vector4.
  1748. */
  1749. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1750. result.x = this.x - otherVector.x;
  1751. result.y = this.y - otherVector.y;
  1752. result.z = this.z - otherVector.z;
  1753. result.w = this.w - otherVector.w;
  1754. return this;
  1755. };
  1756. /**
  1757. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1758. */
  1759. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1760. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1761. };
  1762. /**
  1763. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1764. * Returns the current Vector4.
  1765. */
  1766. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1767. result.x = this.x - x;
  1768. result.y = this.y - y;
  1769. result.z = this.z - z;
  1770. result.w = this.w - w;
  1771. return this;
  1772. };
  1773. /**
  1774. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1775. */
  1776. Vector4.prototype.negate = function () {
  1777. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1778. };
  1779. /**
  1780. * Multiplies the current Vector4 coordinates by scale (float).
  1781. * Returns the updated Vector4.
  1782. */
  1783. Vector4.prototype.scaleInPlace = function (scale) {
  1784. this.x *= scale;
  1785. this.y *= scale;
  1786. this.z *= scale;
  1787. this.w *= scale;
  1788. return this;
  1789. };
  1790. /**
  1791. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1792. */
  1793. Vector4.prototype.scale = function (scale) {
  1794. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1795. };
  1796. /**
  1797. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1798. * Returns the current Vector4.
  1799. */
  1800. Vector4.prototype.scaleToRef = function (scale, result) {
  1801. result.x = this.x * scale;
  1802. result.y = this.y * scale;
  1803. result.z = this.z * scale;
  1804. result.w = this.w * scale;
  1805. return this;
  1806. };
  1807. /**
  1808. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1809. */
  1810. Vector4.prototype.equals = function (otherVector) {
  1811. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1812. };
  1813. /**
  1814. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1815. */
  1816. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1817. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1818. return otherVector
  1819. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1820. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1821. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1822. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1823. };
  1824. /**
  1825. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1826. */
  1827. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1828. return this.x === x && this.y === y && this.z === z && this.w === w;
  1829. };
  1830. /**
  1831. * Multiplies in place the current Vector4 by the passed one.
  1832. * Returns the updated Vector4.
  1833. */
  1834. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1835. this.x *= otherVector.x;
  1836. this.y *= otherVector.y;
  1837. this.z *= otherVector.z;
  1838. this.w *= otherVector.w;
  1839. return this;
  1840. };
  1841. /**
  1842. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1843. */
  1844. Vector4.prototype.multiply = function (otherVector) {
  1845. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1846. };
  1847. /**
  1848. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1849. * Returns the current Vector4.
  1850. */
  1851. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1852. result.x = this.x * otherVector.x;
  1853. result.y = this.y * otherVector.y;
  1854. result.z = this.z * otherVector.z;
  1855. result.w = this.w * otherVector.w;
  1856. return this;
  1857. };
  1858. /**
  1859. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1860. */
  1861. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1862. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1863. };
  1864. /**
  1865. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1866. */
  1867. Vector4.prototype.divide = function (otherVector) {
  1868. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1869. };
  1870. /**
  1871. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1872. * Returns the current Vector4.
  1873. */
  1874. Vector4.prototype.divideToRef = function (otherVector, result) {
  1875. result.x = this.x / otherVector.x;
  1876. result.y = this.y / otherVector.y;
  1877. result.z = this.z / otherVector.z;
  1878. result.w = this.w / otherVector.w;
  1879. return this;
  1880. };
  1881. /**
  1882. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1883. */
  1884. Vector4.prototype.MinimizeInPlace = function (other) {
  1885. if (other.x < this.x)
  1886. this.x = other.x;
  1887. if (other.y < this.y)
  1888. this.y = other.y;
  1889. if (other.z < this.z)
  1890. this.z = other.z;
  1891. if (other.w < this.w)
  1892. this.w = other.w;
  1893. return this;
  1894. };
  1895. /**
  1896. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1897. */
  1898. Vector4.prototype.MaximizeInPlace = function (other) {
  1899. if (other.x > this.x)
  1900. this.x = other.x;
  1901. if (other.y > this.y)
  1902. this.y = other.y;
  1903. if (other.z > this.z)
  1904. this.z = other.z;
  1905. if (other.w > this.w)
  1906. this.w = other.w;
  1907. return this;
  1908. };
  1909. // Properties
  1910. /**
  1911. * Returns the Vector4 length (float).
  1912. */
  1913. Vector4.prototype.length = function () {
  1914. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1915. };
  1916. /**
  1917. * Returns the Vector4 squared length (float).
  1918. */
  1919. Vector4.prototype.lengthSquared = function () {
  1920. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1921. };
  1922. // Methods
  1923. /**
  1924. * Normalizes in place the Vector4.
  1925. * Returns the updated Vector4.
  1926. */
  1927. Vector4.prototype.normalize = function () {
  1928. var len = this.length();
  1929. if (len === 0)
  1930. return this;
  1931. var num = 1.0 / len;
  1932. this.x *= num;
  1933. this.y *= num;
  1934. this.z *= num;
  1935. this.w *= num;
  1936. return this;
  1937. };
  1938. /**
  1939. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1940. */
  1941. Vector4.prototype.toVector3 = function () {
  1942. return new Vector3(this.x, this.y, this.z);
  1943. };
  1944. /**
  1945. * Returns a new Vector4 copied from the current one.
  1946. */
  1947. Vector4.prototype.clone = function () {
  1948. return new Vector4(this.x, this.y, this.z, this.w);
  1949. };
  1950. /**
  1951. * Updates the current Vector4 with the passed one coordinates.
  1952. * Returns the updated Vector4.
  1953. */
  1954. Vector4.prototype.copyFrom = function (source) {
  1955. this.x = source.x;
  1956. this.y = source.y;
  1957. this.z = source.z;
  1958. this.w = source.w;
  1959. return this;
  1960. };
  1961. /**
  1962. * Updates the current Vector4 coordinates with the passed floats.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1966. this.x = x;
  1967. this.y = y;
  1968. this.z = z;
  1969. this.w = w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.set = function (x, y, z, w) {
  1977. return this.copyFromFloats(x, y, z, w);
  1978. };
  1979. // Statics
  1980. /**
  1981. * Returns a new Vector4 set from the starting index of the passed array.
  1982. */
  1983. Vector4.FromArray = function (array, offset) {
  1984. if (!offset) {
  1985. offset = 0;
  1986. }
  1987. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1988. };
  1989. /**
  1990. * Updates the passed vector "result" from the starting index of the passed array.
  1991. */
  1992. Vector4.FromArrayToRef = function (array, offset, result) {
  1993. result.x = array[offset];
  1994. result.y = array[offset + 1];
  1995. result.z = array[offset + 2];
  1996. result.w = array[offset + 3];
  1997. };
  1998. /**
  1999. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2000. */
  2001. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2002. result.x = array[offset];
  2003. result.y = array[offset + 1];
  2004. result.z = array[offset + 2];
  2005. result.w = array[offset + 3];
  2006. };
  2007. /**
  2008. * Updates the passed vector "result" coordinates from the passed floats.
  2009. */
  2010. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2011. result.x = x;
  2012. result.y = y;
  2013. result.z = z;
  2014. result.w = w;
  2015. };
  2016. /**
  2017. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2018. */
  2019. Vector4.Zero = function () {
  2020. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2021. };
  2022. /**
  2023. * Returns a new normalized Vector4 from the passed one.
  2024. */
  2025. Vector4.Normalize = function (vector) {
  2026. var result = Vector4.Zero();
  2027. Vector4.NormalizeToRef(vector, result);
  2028. return result;
  2029. };
  2030. /**
  2031. * Updates the passed vector "result" from the normalization of the passed one.
  2032. */
  2033. Vector4.NormalizeToRef = function (vector, result) {
  2034. result.copyFrom(vector);
  2035. result.normalize();
  2036. };
  2037. Vector4.Minimize = function (left, right) {
  2038. var min = left.clone();
  2039. min.MinimizeInPlace(right);
  2040. return min;
  2041. };
  2042. Vector4.Maximize = function (left, right) {
  2043. var max = left.clone();
  2044. max.MaximizeInPlace(right);
  2045. return max;
  2046. };
  2047. /**
  2048. * Returns the distance (float) between the vectors "value1" and "value2".
  2049. */
  2050. Vector4.Distance = function (value1, value2) {
  2051. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2052. };
  2053. /**
  2054. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2055. */
  2056. Vector4.DistanceSquared = function (value1, value2) {
  2057. var x = value1.x - value2.x;
  2058. var y = value1.y - value2.y;
  2059. var z = value1.z - value2.z;
  2060. var w = value1.w - value2.w;
  2061. return (x * x) + (y * y) + (z * z) + (w * w);
  2062. };
  2063. /**
  2064. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2065. */
  2066. Vector4.Center = function (value1, value2) {
  2067. var center = value1.add(value2);
  2068. center.scaleInPlace(0.5);
  2069. return center;
  2070. };
  2071. /**
  2072. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2073. * This methods computes transformed normalized direction vectors only.
  2074. */
  2075. Vector4.TransformNormal = function (vector, transformation) {
  2076. var result = Vector4.Zero();
  2077. Vector4.TransformNormalToRef(vector, transformation, result);
  2078. return result;
  2079. };
  2080. /**
  2081. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2082. * This methods computes transformed normalized direction vectors only.
  2083. */
  2084. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2085. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2086. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2087. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2088. result.x = x;
  2089. result.y = y;
  2090. result.z = z;
  2091. result.w = vector.w;
  2092. };
  2093. /**
  2094. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2095. * This methods computes transformed normalized direction vectors only.
  2096. */
  2097. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2098. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2099. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2100. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2101. result.w = w;
  2102. };
  2103. return Vector4;
  2104. }());
  2105. BABYLON.Vector4 = Vector4;
  2106. var Size = (function () {
  2107. /**
  2108. * Creates a Size object from the passed width and height (floats).
  2109. */
  2110. function Size(width, height) {
  2111. this.width = width;
  2112. this.height = height;
  2113. }
  2114. // Returns a string with the Size width and height.
  2115. Size.prototype.toString = function () {
  2116. return "{W: " + this.width + ", H: " + this.height + "}";
  2117. };
  2118. /**
  2119. * Returns the string "Size"
  2120. */
  2121. Size.prototype.getClassName = function () {
  2122. return "Size";
  2123. };
  2124. /**
  2125. * Returns the Size hash code.
  2126. */
  2127. Size.prototype.getHashCode = function () {
  2128. var hash = this.width || 0;
  2129. hash = (hash * 397) ^ (this.height || 0);
  2130. return hash;
  2131. };
  2132. /**
  2133. * Updates the current size from the passed one.
  2134. * Returns the updated Size.
  2135. */
  2136. Size.prototype.copyFrom = function (src) {
  2137. this.width = src.width;
  2138. this.height = src.height;
  2139. };
  2140. /**
  2141. * Updates in place the current Size from the passed floats.
  2142. * Returns the updated Size.
  2143. */
  2144. Size.prototype.copyFromFloats = function (width, height) {
  2145. this.width = width;
  2146. this.height = height;
  2147. return this;
  2148. };
  2149. /**
  2150. * Updates in place the current Size from the passed floats.
  2151. * Returns the updated Size.
  2152. */
  2153. Size.prototype.set = function (width, height) {
  2154. return this.copyFromFloats(width, height);
  2155. };
  2156. /**
  2157. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2158. */
  2159. Size.prototype.multiplyByFloats = function (w, h) {
  2160. return new Size(this.width * w, this.height * h);
  2161. };
  2162. /**
  2163. * Returns a new Size copied from the passed one.
  2164. */
  2165. Size.prototype.clone = function () {
  2166. return new Size(this.width, this.height);
  2167. };
  2168. /**
  2169. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2170. */
  2171. Size.prototype.equals = function (other) {
  2172. if (!other) {
  2173. return false;
  2174. }
  2175. return (this.width === other.width) && (this.height === other.height);
  2176. };
  2177. Object.defineProperty(Size.prototype, "surface", {
  2178. /**
  2179. * Returns the surface of the Size : width * height (float).
  2180. */
  2181. get: function () {
  2182. return this.width * this.height;
  2183. },
  2184. enumerable: true,
  2185. configurable: true
  2186. });
  2187. /**
  2188. * Returns a new Size set to (0.0, 0.0)
  2189. */
  2190. Size.Zero = function () {
  2191. return new Size(0.0, 0.0);
  2192. };
  2193. /**
  2194. * Returns a new Size set as the addition result of the current Size and the passed one.
  2195. */
  2196. Size.prototype.add = function (otherSize) {
  2197. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2198. return r;
  2199. };
  2200. /**
  2201. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2202. */
  2203. Size.prototype.subtract = function (otherSize) {
  2204. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2205. return r;
  2206. };
  2207. /**
  2208. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2209. */
  2210. Size.Lerp = function (start, end, amount) {
  2211. var w = start.width + ((end.width - start.width) * amount);
  2212. var h = start.height + ((end.height - start.height) * amount);
  2213. return new Size(w, h);
  2214. };
  2215. return Size;
  2216. }());
  2217. BABYLON.Size = Size;
  2218. var Quaternion = (function () {
  2219. /**
  2220. * Creates a new Quaternion from the passed floats.
  2221. */
  2222. function Quaternion(x, y, z, w) {
  2223. if (x === void 0) { x = 0.0; }
  2224. if (y === void 0) { y = 0.0; }
  2225. if (z === void 0) { z = 0.0; }
  2226. if (w === void 0) { w = 1.0; }
  2227. this.x = x;
  2228. this.y = y;
  2229. this.z = z;
  2230. this.w = w;
  2231. }
  2232. /**
  2233. * Returns a string with the Quaternion coordinates.
  2234. */
  2235. Quaternion.prototype.toString = function () {
  2236. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2237. };
  2238. /**
  2239. * Returns the string "Quaternion".
  2240. */
  2241. Quaternion.prototype.getClassName = function () {
  2242. return "Quaternion";
  2243. };
  2244. /**
  2245. * Returns the Quaternion hash code.
  2246. */
  2247. Quaternion.prototype.getHashCode = function () {
  2248. var hash = this.x || 0;
  2249. hash = (hash * 397) ^ (this.y || 0);
  2250. hash = (hash * 397) ^ (this.z || 0);
  2251. hash = (hash * 397) ^ (this.w || 0);
  2252. return hash;
  2253. };
  2254. /**
  2255. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2256. */
  2257. Quaternion.prototype.asArray = function () {
  2258. return [this.x, this.y, this.z, this.w];
  2259. };
  2260. /**
  2261. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2262. */
  2263. Quaternion.prototype.equals = function (otherQuaternion) {
  2264. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2265. };
  2266. /**
  2267. * Returns a new Quaternion copied from the current one.
  2268. */
  2269. Quaternion.prototype.clone = function () {
  2270. return new Quaternion(this.x, this.y, this.z, this.w);
  2271. };
  2272. /**
  2273. * Updates the current Quaternion from the passed one coordinates.
  2274. * Returns the updated Quaterion.
  2275. */
  2276. Quaternion.prototype.copyFrom = function (other) {
  2277. this.x = other.x;
  2278. this.y = other.y;
  2279. this.z = other.z;
  2280. this.w = other.w;
  2281. return this;
  2282. };
  2283. /**
  2284. * Updates the current Quaternion from the passed float coordinates.
  2285. * Returns the updated Quaterion.
  2286. */
  2287. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2288. this.x = x;
  2289. this.y = y;
  2290. this.z = z;
  2291. this.w = w;
  2292. return this;
  2293. };
  2294. /**
  2295. * Updates the current Quaternion from the passed float coordinates.
  2296. * Returns the updated Quaterion.
  2297. */
  2298. Quaternion.prototype.set = function (x, y, z, w) {
  2299. return this.copyFromFloats(x, y, z, w);
  2300. };
  2301. /**
  2302. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2303. */
  2304. Quaternion.prototype.add = function (other) {
  2305. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2306. };
  2307. /**
  2308. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2309. */
  2310. Quaternion.prototype.subtract = function (other) {
  2311. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2312. };
  2313. /**
  2314. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2315. */
  2316. Quaternion.prototype.scale = function (value) {
  2317. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2318. };
  2319. /**
  2320. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2321. */
  2322. Quaternion.prototype.multiply = function (q1) {
  2323. var result = new Quaternion(0, 0, 0, 1.0);
  2324. this.multiplyToRef(q1, result);
  2325. return result;
  2326. };
  2327. /**
  2328. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2329. * Returns the current Quaternion.
  2330. */
  2331. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2332. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2333. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2334. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2335. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2336. result.copyFromFloats(x, y, z, w);
  2337. return this;
  2338. };
  2339. /**
  2340. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2341. * Returns the updated Quaternion.
  2342. */
  2343. Quaternion.prototype.multiplyInPlace = function (q1) {
  2344. this.multiplyToRef(q1, this);
  2345. return this;
  2346. };
  2347. /**
  2348. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2349. * Returns the current Quaternion.
  2350. */
  2351. Quaternion.prototype.conjugateToRef = function (ref) {
  2352. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2353. return this;
  2354. };
  2355. /**
  2356. * Conjugates in place the current Quaternion.
  2357. * Returns the updated Quaternion.
  2358. */
  2359. Quaternion.prototype.conjugateInPlace = function () {
  2360. this.x *= -1;
  2361. this.y *= -1;
  2362. this.z *= -1;
  2363. return this;
  2364. };
  2365. /**
  2366. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2367. */
  2368. Quaternion.prototype.conjugate = function () {
  2369. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2370. return result;
  2371. };
  2372. /**
  2373. * Returns the Quaternion length (float).
  2374. */
  2375. Quaternion.prototype.length = function () {
  2376. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2377. };
  2378. /**
  2379. * Normalize in place the current Quaternion.
  2380. * Returns the updated Quaternion.
  2381. */
  2382. Quaternion.prototype.normalize = function () {
  2383. var length = 1.0 / this.length();
  2384. this.x *= length;
  2385. this.y *= length;
  2386. this.z *= length;
  2387. this.w *= length;
  2388. return this;
  2389. };
  2390. /**
  2391. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2392. */
  2393. Quaternion.prototype.toEulerAngles = function (order) {
  2394. if (order === void 0) { order = "YZX"; }
  2395. var result = Vector3.Zero();
  2396. this.toEulerAnglesToRef(result, order);
  2397. return result;
  2398. };
  2399. /**
  2400. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2401. * Returns the current Quaternion.
  2402. */
  2403. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2404. if (order === void 0) { order = "YZX"; }
  2405. var qz = this.z;
  2406. var qx = this.x;
  2407. var qy = this.y;
  2408. var qw = this.w;
  2409. var sqw = qw * qw;
  2410. var sqz = qz * qz;
  2411. var sqx = qx * qx;
  2412. var sqy = qy * qy;
  2413. var zAxisY = qy * qz - qx * qw;
  2414. var limit = .4999999;
  2415. if (zAxisY < -limit) {
  2416. result.y = 2 * Math.atan2(qy, qw);
  2417. result.x = Math.PI / 2;
  2418. result.z = 0;
  2419. }
  2420. else if (zAxisY > limit) {
  2421. result.y = 2 * Math.atan2(qy, qw);
  2422. result.x = -Math.PI / 2;
  2423. result.z = 0;
  2424. }
  2425. else {
  2426. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2427. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2428. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2429. }
  2430. return this;
  2431. };
  2432. /**
  2433. * Updates the passed rotation matrix with the current Quaternion values.
  2434. * Returns the current Quaternion.
  2435. */
  2436. Quaternion.prototype.toRotationMatrix = function (result) {
  2437. var xx = this.x * this.x;
  2438. var yy = this.y * this.y;
  2439. var zz = this.z * this.z;
  2440. var xy = this.x * this.y;
  2441. var zw = this.z * this.w;
  2442. var zx = this.z * this.x;
  2443. var yw = this.y * this.w;
  2444. var yz = this.y * this.z;
  2445. var xw = this.x * this.w;
  2446. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2447. result.m[1] = 2.0 * (xy + zw);
  2448. result.m[2] = 2.0 * (zx - yw);
  2449. result.m[3] = 0;
  2450. result.m[4] = 2.0 * (xy - zw);
  2451. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2452. result.m[6] = 2.0 * (yz + xw);
  2453. result.m[7] = 0;
  2454. result.m[8] = 2.0 * (zx + yw);
  2455. result.m[9] = 2.0 * (yz - xw);
  2456. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2457. result.m[11] = 0;
  2458. result.m[12] = 0;
  2459. result.m[13] = 0;
  2460. result.m[14] = 0;
  2461. result.m[15] = 1.0;
  2462. return this;
  2463. };
  2464. /**
  2465. * Updates the current Quaternion from the passed rotation matrix values.
  2466. * Returns the updated Quaternion.
  2467. */
  2468. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2469. Quaternion.FromRotationMatrixToRef(matrix, this);
  2470. return this;
  2471. };
  2472. // Statics
  2473. /**
  2474. * Returns a new Quaternion set from the passed rotation matrix values.
  2475. */
  2476. Quaternion.FromRotationMatrix = function (matrix) {
  2477. var result = new Quaternion();
  2478. Quaternion.FromRotationMatrixToRef(matrix, result);
  2479. return result;
  2480. };
  2481. /**
  2482. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2483. */
  2484. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2485. var data = matrix.m;
  2486. var m11 = data[0], m12 = data[4], m13 = data[8];
  2487. var m21 = data[1], m22 = data[5], m23 = data[9];
  2488. var m31 = data[2], m32 = data[6], m33 = data[10];
  2489. var trace = m11 + m22 + m33;
  2490. var s;
  2491. if (trace > 0) {
  2492. s = 0.5 / Math.sqrt(trace + 1.0);
  2493. result.w = 0.25 / s;
  2494. result.x = (m32 - m23) * s;
  2495. result.y = (m13 - m31) * s;
  2496. result.z = (m21 - m12) * s;
  2497. }
  2498. else if (m11 > m22 && m11 > m33) {
  2499. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2500. result.w = (m32 - m23) / s;
  2501. result.x = 0.25 * s;
  2502. result.y = (m12 + m21) / s;
  2503. result.z = (m13 + m31) / s;
  2504. }
  2505. else if (m22 > m33) {
  2506. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2507. result.w = (m13 - m31) / s;
  2508. result.x = (m12 + m21) / s;
  2509. result.y = 0.25 * s;
  2510. result.z = (m23 + m32) / s;
  2511. }
  2512. else {
  2513. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2514. result.w = (m21 - m12) / s;
  2515. result.x = (m13 + m31) / s;
  2516. result.y = (m23 + m32) / s;
  2517. result.z = 0.25 * s;
  2518. }
  2519. };
  2520. /**
  2521. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2522. */
  2523. Quaternion.Zero = function () {
  2524. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2525. };
  2526. /**
  2527. * Returns a new Quaternion as the inverted current Quaternion.
  2528. */
  2529. Quaternion.Inverse = function (q) {
  2530. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2531. };
  2532. /**
  2533. * Returns the identity Quaternion.
  2534. */
  2535. Quaternion.Identity = function () {
  2536. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2537. };
  2538. Quaternion.IsIdentity = function (quaternion) {
  2539. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2540. };
  2541. /**
  2542. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2543. */
  2544. Quaternion.RotationAxis = function (axis, angle) {
  2545. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2546. };
  2547. /**
  2548. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2549. */
  2550. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2551. var sin = Math.sin(angle / 2);
  2552. axis.normalize();
  2553. result.w = Math.cos(angle / 2);
  2554. result.x = axis.x * sin;
  2555. result.y = axis.y * sin;
  2556. result.z = axis.z * sin;
  2557. return result;
  2558. };
  2559. /**
  2560. * Retuns a new Quaternion set from the starting index of the passed array.
  2561. */
  2562. Quaternion.FromArray = function (array, offset) {
  2563. if (!offset) {
  2564. offset = 0;
  2565. }
  2566. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2567. };
  2568. /**
  2569. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2570. */
  2571. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2572. var q = new Quaternion();
  2573. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2574. return q;
  2575. };
  2576. /**
  2577. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2578. */
  2579. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2580. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2581. var halfRoll = roll * 0.5;
  2582. var halfPitch = pitch * 0.5;
  2583. var halfYaw = yaw * 0.5;
  2584. var sinRoll = Math.sin(halfRoll);
  2585. var cosRoll = Math.cos(halfRoll);
  2586. var sinPitch = Math.sin(halfPitch);
  2587. var cosPitch = Math.cos(halfPitch);
  2588. var sinYaw = Math.sin(halfYaw);
  2589. var cosYaw = Math.cos(halfYaw);
  2590. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2591. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2592. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2593. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2594. };
  2595. /**
  2596. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2597. */
  2598. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2599. var result = new Quaternion();
  2600. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2601. return result;
  2602. };
  2603. /**
  2604. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2605. */
  2606. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2607. // Produces a quaternion from Euler angles in the z-x-z orientation
  2608. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2609. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2610. var halfBeta = beta * 0.5;
  2611. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2612. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2613. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2614. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2615. };
  2616. /**
  2617. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2618. * cf to Vector3.RotationFromAxis() documentation.
  2619. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2620. */
  2621. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2622. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2623. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2624. return quat;
  2625. };
  2626. /**
  2627. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2628. * cf to Vector3.RotationFromAxis() documentation.
  2629. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2630. */
  2631. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2632. var rotMat = MathTmp.Matrix[0];
  2633. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2634. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2635. };
  2636. Quaternion.Slerp = function (left, right, amount) {
  2637. var result = Quaternion.Identity();
  2638. Quaternion.SlerpToRef(left, right, amount, result);
  2639. return result;
  2640. };
  2641. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2642. var num2;
  2643. var num3;
  2644. var num = amount;
  2645. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2646. var flag = false;
  2647. if (num4 < 0) {
  2648. flag = true;
  2649. num4 = -num4;
  2650. }
  2651. if (num4 > 0.999999) {
  2652. num3 = 1 - num;
  2653. num2 = flag ? -num : num;
  2654. }
  2655. else {
  2656. var num5 = Math.acos(num4);
  2657. var num6 = (1.0 / Math.sin(num5));
  2658. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2659. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2660. }
  2661. result.x = (num3 * left.x) + (num2 * right.x);
  2662. result.y = (num3 * left.y) + (num2 * right.y);
  2663. result.z = (num3 * left.z) + (num2 * right.z);
  2664. result.w = (num3 * left.w) + (num2 * right.w);
  2665. };
  2666. return Quaternion;
  2667. }());
  2668. BABYLON.Quaternion = Quaternion;
  2669. var Matrix = (function () {
  2670. function Matrix() {
  2671. this.m = new Float32Array(16);
  2672. }
  2673. // Properties
  2674. /**
  2675. * Boolean : True is the matrix is the identity matrix
  2676. */
  2677. Matrix.prototype.isIdentity = function () {
  2678. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2679. return false;
  2680. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2681. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2682. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2683. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2684. return false;
  2685. return true;
  2686. };
  2687. /**
  2688. * Returns the matrix determinant (float).
  2689. */
  2690. Matrix.prototype.determinant = function () {
  2691. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2692. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2693. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2694. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2695. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2696. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2697. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2698. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2699. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2700. };
  2701. // Methods
  2702. /**
  2703. * Returns the matrix underlying array.
  2704. */
  2705. Matrix.prototype.toArray = function () {
  2706. return this.m;
  2707. };
  2708. /**
  2709. * Returns the matrix underlying array.
  2710. */
  2711. Matrix.prototype.asArray = function () {
  2712. return this.toArray();
  2713. };
  2714. /**
  2715. * Inverts in place the Matrix.
  2716. * Returns the Matrix inverted.
  2717. */
  2718. Matrix.prototype.invert = function () {
  2719. this.invertToRef(this);
  2720. return this;
  2721. };
  2722. /**
  2723. * Sets all the matrix elements to zero.
  2724. * Returns the Matrix.
  2725. */
  2726. Matrix.prototype.reset = function () {
  2727. for (var index = 0; index < 16; index++) {
  2728. this.m[index] = 0.0;
  2729. }
  2730. return this;
  2731. };
  2732. /**
  2733. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2734. */
  2735. Matrix.prototype.add = function (other) {
  2736. var result = new Matrix();
  2737. this.addToRef(other, result);
  2738. return result;
  2739. };
  2740. /**
  2741. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2742. * Returns the Matrix.
  2743. */
  2744. Matrix.prototype.addToRef = function (other, result) {
  2745. for (var index = 0; index < 16; index++) {
  2746. result.m[index] = this.m[index] + other.m[index];
  2747. }
  2748. return this;
  2749. };
  2750. /**
  2751. * Adds in place the passed matrix to the current Matrix.
  2752. * Returns the updated Matrix.
  2753. */
  2754. Matrix.prototype.addToSelf = function (other) {
  2755. for (var index = 0; index < 16; index++) {
  2756. this.m[index] += other.m[index];
  2757. }
  2758. return this;
  2759. };
  2760. /**
  2761. * Sets the passed matrix with the current inverted Matrix.
  2762. * Returns the unmodified current Matrix.
  2763. */
  2764. Matrix.prototype.invertToRef = function (other) {
  2765. var l1 = this.m[0];
  2766. var l2 = this.m[1];
  2767. var l3 = this.m[2];
  2768. var l4 = this.m[3];
  2769. var l5 = this.m[4];
  2770. var l6 = this.m[5];
  2771. var l7 = this.m[6];
  2772. var l8 = this.m[7];
  2773. var l9 = this.m[8];
  2774. var l10 = this.m[9];
  2775. var l11 = this.m[10];
  2776. var l12 = this.m[11];
  2777. var l13 = this.m[12];
  2778. var l14 = this.m[13];
  2779. var l15 = this.m[14];
  2780. var l16 = this.m[15];
  2781. var l17 = (l11 * l16) - (l12 * l15);
  2782. var l18 = (l10 * l16) - (l12 * l14);
  2783. var l19 = (l10 * l15) - (l11 * l14);
  2784. var l20 = (l9 * l16) - (l12 * l13);
  2785. var l21 = (l9 * l15) - (l11 * l13);
  2786. var l22 = (l9 * l14) - (l10 * l13);
  2787. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2788. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2789. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2790. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2791. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2792. var l28 = (l7 * l16) - (l8 * l15);
  2793. var l29 = (l6 * l16) - (l8 * l14);
  2794. var l30 = (l6 * l15) - (l7 * l14);
  2795. var l31 = (l5 * l16) - (l8 * l13);
  2796. var l32 = (l5 * l15) - (l7 * l13);
  2797. var l33 = (l5 * l14) - (l6 * l13);
  2798. var l34 = (l7 * l12) - (l8 * l11);
  2799. var l35 = (l6 * l12) - (l8 * l10);
  2800. var l36 = (l6 * l11) - (l7 * l10);
  2801. var l37 = (l5 * l12) - (l8 * l9);
  2802. var l38 = (l5 * l11) - (l7 * l9);
  2803. var l39 = (l5 * l10) - (l6 * l9);
  2804. other.m[0] = l23 * l27;
  2805. other.m[4] = l24 * l27;
  2806. other.m[8] = l25 * l27;
  2807. other.m[12] = l26 * l27;
  2808. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2809. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2810. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2811. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2812. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2813. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2814. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2815. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2816. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2817. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2818. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2819. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2820. return this;
  2821. };
  2822. /**
  2823. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2824. * Returns the updated Matrix.
  2825. */
  2826. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2827. this.m[12] = x;
  2828. this.m[13] = y;
  2829. this.m[14] = z;
  2830. return this;
  2831. };
  2832. /**
  2833. * Inserts the translation vector in the current Matrix.
  2834. * Returns the updated Matrix.
  2835. */
  2836. Matrix.prototype.setTranslation = function (vector3) {
  2837. this.m[12] = vector3.x;
  2838. this.m[13] = vector3.y;
  2839. this.m[14] = vector3.z;
  2840. return this;
  2841. };
  2842. /**
  2843. * Returns a new Vector3 as the extracted translation from the Matrix.
  2844. */
  2845. Matrix.prototype.getTranslation = function () {
  2846. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2847. };
  2848. /**
  2849. * Fill a Vector3 with the extracted translation from the Matrix.
  2850. */
  2851. Matrix.prototype.getTranslationToRef = function (result) {
  2852. result.x = this.m[12];
  2853. result.y = this.m[13];
  2854. result.z = this.m[14];
  2855. return this;
  2856. };
  2857. /**
  2858. * Remove rotation and scaling part from the Matrix.
  2859. * Returns the updated Matrix.
  2860. */
  2861. Matrix.prototype.removeRotationAndScaling = function () {
  2862. this.setRowFromFloats(0, 1, 0, 0, 0);
  2863. this.setRowFromFloats(1, 0, 1, 0, 0);
  2864. this.setRowFromFloats(2, 0, 0, 1, 0);
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2869. */
  2870. Matrix.prototype.multiply = function (other) {
  2871. var result = new Matrix();
  2872. this.multiplyToRef(other, result);
  2873. return result;
  2874. };
  2875. /**
  2876. * Updates the current Matrix from the passed one values.
  2877. * Returns the updated Matrix.
  2878. */
  2879. Matrix.prototype.copyFrom = function (other) {
  2880. for (var index = 0; index < 16; index++) {
  2881. this.m[index] = other.m[index];
  2882. }
  2883. return this;
  2884. };
  2885. /**
  2886. * Populates the passed array from the starting index with the Matrix values.
  2887. * Returns the Matrix.
  2888. */
  2889. Matrix.prototype.copyToArray = function (array, offset) {
  2890. if (offset === void 0) { offset = 0; }
  2891. for (var index = 0; index < 16; index++) {
  2892. array[offset + index] = this.m[index];
  2893. }
  2894. return this;
  2895. };
  2896. /**
  2897. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2898. */
  2899. Matrix.prototype.multiplyToRef = function (other, result) {
  2900. this.multiplyToArray(other, result.m, 0);
  2901. return this;
  2902. };
  2903. /**
  2904. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2905. */
  2906. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2907. var tm0 = this.m[0];
  2908. var tm1 = this.m[1];
  2909. var tm2 = this.m[2];
  2910. var tm3 = this.m[3];
  2911. var tm4 = this.m[4];
  2912. var tm5 = this.m[5];
  2913. var tm6 = this.m[6];
  2914. var tm7 = this.m[7];
  2915. var tm8 = this.m[8];
  2916. var tm9 = this.m[9];
  2917. var tm10 = this.m[10];
  2918. var tm11 = this.m[11];
  2919. var tm12 = this.m[12];
  2920. var tm13 = this.m[13];
  2921. var tm14 = this.m[14];
  2922. var tm15 = this.m[15];
  2923. var om0 = other.m[0];
  2924. var om1 = other.m[1];
  2925. var om2 = other.m[2];
  2926. var om3 = other.m[3];
  2927. var om4 = other.m[4];
  2928. var om5 = other.m[5];
  2929. var om6 = other.m[6];
  2930. var om7 = other.m[7];
  2931. var om8 = other.m[8];
  2932. var om9 = other.m[9];
  2933. var om10 = other.m[10];
  2934. var om11 = other.m[11];
  2935. var om12 = other.m[12];
  2936. var om13 = other.m[13];
  2937. var om14 = other.m[14];
  2938. var om15 = other.m[15];
  2939. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2940. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2941. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2942. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2943. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2944. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2945. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2946. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2947. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2948. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2949. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2950. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2951. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2952. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2953. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2954. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2955. return this;
  2956. };
  2957. /**
  2958. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2959. */
  2960. Matrix.prototype.equals = function (value) {
  2961. return value &&
  2962. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2963. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2964. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2965. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2966. };
  2967. /**
  2968. * Returns a new Matrix from the current Matrix.
  2969. */
  2970. Matrix.prototype.clone = function () {
  2971. 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]);
  2972. };
  2973. /**
  2974. * Returns the string "Matrix"
  2975. */
  2976. Matrix.prototype.getClassName = function () {
  2977. return "Matrix";
  2978. };
  2979. /**
  2980. * Returns the Matrix hash code.
  2981. */
  2982. Matrix.prototype.getHashCode = function () {
  2983. var hash = this.m[0] || 0;
  2984. for (var i = 1; i < 16; i++) {
  2985. hash = (hash * 397) ^ (this.m[i] || 0);
  2986. }
  2987. return hash;
  2988. };
  2989. /**
  2990. * Decomposes the current Matrix into :
  2991. * - a scale vector3 passed as a reference to update,
  2992. * - a rotation quaternion passed as a reference to update,
  2993. * - a translation vector3 passed as a reference to update.
  2994. * Returns the boolean `true`.
  2995. */
  2996. Matrix.prototype.decompose = function (scale, rotation, translation) {
  2997. translation.x = this.m[12];
  2998. translation.y = this.m[13];
  2999. translation.z = this.m[14];
  3000. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3001. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3002. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3003. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3004. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3005. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3006. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3007. rotation.x = 0;
  3008. rotation.y = 0;
  3009. rotation.z = 0;
  3010. rotation.w = 1;
  3011. return false;
  3012. }
  3013. Matrix.FromValuesToRef(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, MathTmp.Matrix[0]);
  3014. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3015. return true;
  3016. };
  3017. /**
  3018. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3019. */
  3020. Matrix.prototype.getRotationMatrix = function () {
  3021. var result = Matrix.Identity();
  3022. this.getRotationMatrixToRef(result);
  3023. return result;
  3024. };
  3025. /**
  3026. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3027. * Returns the current Matrix.
  3028. */
  3029. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3030. var m = this.m;
  3031. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3032. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3033. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3034. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3035. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3036. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3037. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3038. return this;
  3039. };
  3040. // Statics
  3041. /**
  3042. * Returns a new Matrix set from the starting index of the passed array.
  3043. */
  3044. Matrix.FromArray = function (array, offset) {
  3045. var result = new Matrix();
  3046. if (!offset) {
  3047. offset = 0;
  3048. }
  3049. Matrix.FromArrayToRef(array, offset, result);
  3050. return result;
  3051. };
  3052. /**
  3053. * Sets the passed "result" matrix from the starting index of the passed array.
  3054. */
  3055. Matrix.FromArrayToRef = function (array, offset, result) {
  3056. for (var index = 0; index < 16; index++) {
  3057. result.m[index] = array[index + offset];
  3058. }
  3059. };
  3060. /**
  3061. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3062. */
  3063. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3064. for (var index = 0; index < 16; index++) {
  3065. result.m[index] = array[index + offset] * scale;
  3066. }
  3067. };
  3068. /**
  3069. * Sets the passed matrix "result" with the 16 passed floats.
  3070. */
  3071. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3072. result.m[0] = initialM11;
  3073. result.m[1] = initialM12;
  3074. result.m[2] = initialM13;
  3075. result.m[3] = initialM14;
  3076. result.m[4] = initialM21;
  3077. result.m[5] = initialM22;
  3078. result.m[6] = initialM23;
  3079. result.m[7] = initialM24;
  3080. result.m[8] = initialM31;
  3081. result.m[9] = initialM32;
  3082. result.m[10] = initialM33;
  3083. result.m[11] = initialM34;
  3084. result.m[12] = initialM41;
  3085. result.m[13] = initialM42;
  3086. result.m[14] = initialM43;
  3087. result.m[15] = initialM44;
  3088. };
  3089. /**
  3090. * Returns the index-th row of the current matrix as a new Vector4.
  3091. */
  3092. Matrix.prototype.getRow = function (index) {
  3093. if (index < 0 || index > 3) {
  3094. return null;
  3095. }
  3096. var i = index * 4;
  3097. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3098. };
  3099. /**
  3100. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3101. * Returns the updated Matrix.
  3102. */
  3103. Matrix.prototype.setRow = function (index, row) {
  3104. if (index < 0 || index > 3) {
  3105. return this;
  3106. }
  3107. var i = index * 4;
  3108. this.m[i + 0] = row.x;
  3109. this.m[i + 1] = row.y;
  3110. this.m[i + 2] = row.z;
  3111. this.m[i + 3] = row.w;
  3112. return this;
  3113. };
  3114. /**
  3115. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3116. * Returns the updated Matrix.
  3117. */
  3118. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3119. if (index < 0 || index > 3) {
  3120. return this;
  3121. }
  3122. var i = index * 4;
  3123. this.m[i + 0] = x;
  3124. this.m[i + 1] = y;
  3125. this.m[i + 2] = z;
  3126. this.m[i + 3] = w;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Matrix set from the 16 passed floats.
  3131. */
  3132. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3133. var result = new Matrix();
  3134. result.m[0] = initialM11;
  3135. result.m[1] = initialM12;
  3136. result.m[2] = initialM13;
  3137. result.m[3] = initialM14;
  3138. result.m[4] = initialM21;
  3139. result.m[5] = initialM22;
  3140. result.m[6] = initialM23;
  3141. result.m[7] = initialM24;
  3142. result.m[8] = initialM31;
  3143. result.m[9] = initialM32;
  3144. result.m[10] = initialM33;
  3145. result.m[11] = initialM34;
  3146. result.m[12] = initialM41;
  3147. result.m[13] = initialM42;
  3148. result.m[14] = initialM43;
  3149. result.m[15] = initialM44;
  3150. return result;
  3151. };
  3152. /**
  3153. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3154. */
  3155. Matrix.Compose = function (scale, rotation, translation) {
  3156. var result = Matrix.Identity();
  3157. Matrix.ComposeToRef(scale, rotation, translation, result);
  3158. return result;
  3159. };
  3160. /**
  3161. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3162. */
  3163. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3164. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3165. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3166. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3167. result.setTranslation(translation);
  3168. };
  3169. /**
  3170. * Returns a new indentity Matrix.
  3171. */
  3172. Matrix.Identity = function () {
  3173. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3174. };
  3175. /**
  3176. * Sets the passed "result" as an identity matrix.
  3177. */
  3178. Matrix.IdentityToRef = function (result) {
  3179. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3180. };
  3181. /**
  3182. * Returns a new zero Matrix.
  3183. */
  3184. Matrix.Zero = function () {
  3185. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3186. };
  3187. /**
  3188. * Returns a new rotation matrix for "angle" radians around the X axis.
  3189. */
  3190. Matrix.RotationX = function (angle) {
  3191. var result = new Matrix();
  3192. Matrix.RotationXToRef(angle, result);
  3193. return result;
  3194. };
  3195. /**
  3196. * Returns a new Matrix as the passed inverted one.
  3197. */
  3198. Matrix.Invert = function (source) {
  3199. var result = new Matrix();
  3200. source.invertToRef(result);
  3201. return result;
  3202. };
  3203. /**
  3204. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3205. */
  3206. Matrix.RotationXToRef = function (angle, result) {
  3207. var s = Math.sin(angle);
  3208. var c = Math.cos(angle);
  3209. result.m[0] = 1.0;
  3210. result.m[15] = 1.0;
  3211. result.m[5] = c;
  3212. result.m[10] = c;
  3213. result.m[9] = -s;
  3214. result.m[6] = s;
  3215. result.m[1] = 0.0;
  3216. result.m[2] = 0.0;
  3217. result.m[3] = 0.0;
  3218. result.m[4] = 0.0;
  3219. result.m[7] = 0.0;
  3220. result.m[8] = 0.0;
  3221. result.m[11] = 0.0;
  3222. result.m[12] = 0.0;
  3223. result.m[13] = 0.0;
  3224. result.m[14] = 0.0;
  3225. };
  3226. /**
  3227. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3228. */
  3229. Matrix.RotationY = function (angle) {
  3230. var result = new Matrix();
  3231. Matrix.RotationYToRef(angle, result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3236. */
  3237. Matrix.RotationYToRef = function (angle, result) {
  3238. var s = Math.sin(angle);
  3239. var c = Math.cos(angle);
  3240. result.m[5] = 1.0;
  3241. result.m[15] = 1.0;
  3242. result.m[0] = c;
  3243. result.m[2] = -s;
  3244. result.m[8] = s;
  3245. result.m[10] = c;
  3246. result.m[1] = 0.0;
  3247. result.m[3] = 0.0;
  3248. result.m[4] = 0.0;
  3249. result.m[6] = 0.0;
  3250. result.m[7] = 0.0;
  3251. result.m[9] = 0.0;
  3252. result.m[11] = 0.0;
  3253. result.m[12] = 0.0;
  3254. result.m[13] = 0.0;
  3255. result.m[14] = 0.0;
  3256. };
  3257. /**
  3258. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3259. */
  3260. Matrix.RotationZ = function (angle) {
  3261. var result = new Matrix();
  3262. Matrix.RotationZToRef(angle, result);
  3263. return result;
  3264. };
  3265. /**
  3266. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3267. */
  3268. Matrix.RotationZToRef = function (angle, result) {
  3269. var s = Math.sin(angle);
  3270. var c = Math.cos(angle);
  3271. result.m[10] = 1.0;
  3272. result.m[15] = 1.0;
  3273. result.m[0] = c;
  3274. result.m[1] = s;
  3275. result.m[4] = -s;
  3276. result.m[5] = c;
  3277. result.m[2] = 0.0;
  3278. result.m[3] = 0.0;
  3279. result.m[6] = 0.0;
  3280. result.m[7] = 0.0;
  3281. result.m[8] = 0.0;
  3282. result.m[9] = 0.0;
  3283. result.m[11] = 0.0;
  3284. result.m[12] = 0.0;
  3285. result.m[13] = 0.0;
  3286. result.m[14] = 0.0;
  3287. };
  3288. /**
  3289. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3290. */
  3291. Matrix.RotationAxis = function (axis, angle) {
  3292. var result = Matrix.Zero();
  3293. Matrix.RotationAxisToRef(axis, angle, result);
  3294. return result;
  3295. };
  3296. /**
  3297. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3298. */
  3299. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3300. var s = Math.sin(-angle);
  3301. var c = Math.cos(-angle);
  3302. var c1 = 1 - c;
  3303. axis.normalize();
  3304. result.m[0] = (axis.x * axis.x) * c1 + c;
  3305. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3306. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3307. result.m[3] = 0.0;
  3308. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3309. result.m[5] = (axis.y * axis.y) * c1 + c;
  3310. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3311. result.m[7] = 0.0;
  3312. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3313. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3314. result.m[10] = (axis.z * axis.z) * c1 + c;
  3315. result.m[11] = 0.0;
  3316. result.m[15] = 1.0;
  3317. };
  3318. /**
  3319. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3320. */
  3321. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3322. var result = new Matrix();
  3323. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3324. return result;
  3325. };
  3326. /**
  3327. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3328. */
  3329. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3330. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3331. this._tempQuaternion.toRotationMatrix(result);
  3332. };
  3333. /**
  3334. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3335. */
  3336. Matrix.Scaling = function (x, y, z) {
  3337. var result = Matrix.Zero();
  3338. Matrix.ScalingToRef(x, y, z, result);
  3339. return result;
  3340. };
  3341. /**
  3342. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3343. */
  3344. Matrix.ScalingToRef = function (x, y, z, result) {
  3345. result.m[0] = x;
  3346. result.m[1] = 0.0;
  3347. result.m[2] = 0.0;
  3348. result.m[3] = 0.0;
  3349. result.m[4] = 0.0;
  3350. result.m[5] = y;
  3351. result.m[6] = 0.0;
  3352. result.m[7] = 0.0;
  3353. result.m[8] = 0.0;
  3354. result.m[9] = 0.0;
  3355. result.m[10] = z;
  3356. result.m[11] = 0.0;
  3357. result.m[12] = 0.0;
  3358. result.m[13] = 0.0;
  3359. result.m[14] = 0.0;
  3360. result.m[15] = 1.0;
  3361. };
  3362. /**
  3363. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3364. */
  3365. Matrix.Translation = function (x, y, z) {
  3366. var result = Matrix.Identity();
  3367. Matrix.TranslationToRef(x, y, z, result);
  3368. return result;
  3369. };
  3370. /**
  3371. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3372. */
  3373. Matrix.TranslationToRef = function (x, y, z, result) {
  3374. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3375. };
  3376. /**
  3377. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3378. */
  3379. Matrix.Lerp = function (startValue, endValue, gradient) {
  3380. var result = Matrix.Zero();
  3381. for (var index = 0; index < 16; index++) {
  3382. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3383. }
  3384. return result;
  3385. };
  3386. /**
  3387. * Returns a new Matrix whose values are computed by :
  3388. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3389. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3390. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3391. */
  3392. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3393. var startScale = new Vector3(0, 0, 0);
  3394. var startRotation = new Quaternion();
  3395. var startTranslation = new Vector3(0, 0, 0);
  3396. startValue.decompose(startScale, startRotation, startTranslation);
  3397. var endScale = new Vector3(0, 0, 0);
  3398. var endRotation = new Quaternion();
  3399. var endTranslation = new Vector3(0, 0, 0);
  3400. endValue.decompose(endScale, endRotation, endTranslation);
  3401. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3402. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3403. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3404. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3405. };
  3406. /**
  3407. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3408. * This methods works for a Left-Handed system.
  3409. */
  3410. Matrix.LookAtLH = function (eye, target, up) {
  3411. var result = Matrix.Zero();
  3412. Matrix.LookAtLHToRef(eye, target, up, result);
  3413. return result;
  3414. };
  3415. /**
  3416. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3417. * This methods works for a Left-Handed system.
  3418. */
  3419. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3420. // Z axis
  3421. target.subtractToRef(eye, this._zAxis);
  3422. this._zAxis.normalize();
  3423. // X axis
  3424. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3425. if (this._xAxis.lengthSquared() === 0) {
  3426. this._xAxis.x = 1.0;
  3427. }
  3428. else {
  3429. this._xAxis.normalize();
  3430. }
  3431. // Y axis
  3432. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3433. this._yAxis.normalize();
  3434. // Eye angles
  3435. var ex = -Vector3.Dot(this._xAxis, eye);
  3436. var ey = -Vector3.Dot(this._yAxis, eye);
  3437. var ez = -Vector3.Dot(this._zAxis, eye);
  3438. 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);
  3439. };
  3440. /**
  3441. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3442. * This methods works for a Right-Handed system.
  3443. */
  3444. Matrix.LookAtRH = function (eye, target, up) {
  3445. var result = Matrix.Zero();
  3446. Matrix.LookAtRHToRef(eye, target, up, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3451. * This methods works for a Left-Handed system.
  3452. */
  3453. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3454. // Z axis
  3455. eye.subtractToRef(target, this._zAxis);
  3456. this._zAxis.normalize();
  3457. // X axis
  3458. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3459. if (this._xAxis.lengthSquared() === 0) {
  3460. this._xAxis.x = 1.0;
  3461. }
  3462. else {
  3463. this._xAxis.normalize();
  3464. }
  3465. // Y axis
  3466. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3467. this._yAxis.normalize();
  3468. // Eye angles
  3469. var ex = -Vector3.Dot(this._xAxis, eye);
  3470. var ey = -Vector3.Dot(this._yAxis, eye);
  3471. var ez = -Vector3.Dot(this._zAxis, eye);
  3472. 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);
  3473. };
  3474. /**
  3475. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3476. */
  3477. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3478. var matrix = Matrix.Zero();
  3479. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3480. return matrix;
  3481. };
  3482. /**
  3483. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3484. */
  3485. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3486. var n = znear;
  3487. var f = zfar;
  3488. var a = 2.0 / width;
  3489. var b = 2.0 / height;
  3490. var c = 2.0 / (f - n);
  3491. var d = -(f + n) / (f - n);
  3492. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3493. };
  3494. /**
  3495. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3496. */
  3497. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3498. var matrix = Matrix.Zero();
  3499. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3500. return matrix;
  3501. };
  3502. /**
  3503. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3504. */
  3505. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3506. var n = znear;
  3507. var f = zfar;
  3508. var a = 2.0 / (right - left);
  3509. var b = 2.0 / (top - bottom);
  3510. var c = 2.0 / (f - n);
  3511. var d = -(f + n) / (f - n);
  3512. var i0 = (left + right) / (left - right);
  3513. var i1 = (top + bottom) / (bottom - top);
  3514. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3515. };
  3516. /**
  3517. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3518. */
  3519. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3520. var matrix = Matrix.Zero();
  3521. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3522. return matrix;
  3523. };
  3524. /**
  3525. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3526. */
  3527. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3528. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3529. result.m[10] *= -1.0;
  3530. };
  3531. /**
  3532. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3533. */
  3534. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3535. var matrix = Matrix.Zero();
  3536. var n = znear;
  3537. var f = zfar;
  3538. var a = 2.0 * n / width;
  3539. var b = 2.0 * n / height;
  3540. var c = (f + n) / (f - n);
  3541. var d = -2.0 * f * n / (f - n);
  3542. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3543. return matrix;
  3544. };
  3545. /**
  3546. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3547. */
  3548. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3549. var matrix = Matrix.Zero();
  3550. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3551. return matrix;
  3552. };
  3553. /**
  3554. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3555. */
  3556. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3557. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3558. var n = znear;
  3559. var f = zfar;
  3560. var t = 1.0 / (Math.tan(fov * 0.5));
  3561. var a = isVerticalFovFixed ? (t / aspect) : t;
  3562. var b = isVerticalFovFixed ? t : (t * aspect);
  3563. var c = (f + n) / (f - n);
  3564. var d = -2.0 * f * n / (f - n);
  3565. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3566. };
  3567. /**
  3568. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3569. */
  3570. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3571. var matrix = Matrix.Zero();
  3572. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3573. return matrix;
  3574. };
  3575. /**
  3576. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3577. */
  3578. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3579. //alternatively this could be expressed as:
  3580. // m = PerspectiveFovLHToRef
  3581. // m[10] *= -1.0;
  3582. // m[11] *= -1.0;
  3583. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3584. var n = znear;
  3585. var f = zfar;
  3586. var t = 1.0 / (Math.tan(fov * 0.5));
  3587. var a = isVerticalFovFixed ? (t / aspect) : t;
  3588. var b = isVerticalFovFixed ? t : (t * aspect);
  3589. var c = -(f + n) / (f - n);
  3590. var d = -2 * f * n / (f - n);
  3591. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3595. */
  3596. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3597. if (rightHanded === void 0) { rightHanded = false; }
  3598. var rightHandedFactor = rightHanded ? -1 : 1;
  3599. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3600. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3601. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3602. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3603. var xScale = 2.0 / (leftTan + rightTan);
  3604. var yScale = 2.0 / (upTan + downTan);
  3605. result.m[0] = xScale;
  3606. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3607. result.m[5] = yScale;
  3608. result.m[6] = result.m[7] = 0.0;
  3609. result.m[8] = ((leftTan - rightTan) * xScale * 0.5) * rightHandedFactor;
  3610. result.m[9] = -((upTan - downTan) * yScale * 0.5) * rightHandedFactor;
  3611. result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3612. // result.m[10] = -zfar / (znear - zfar);
  3613. result.m[11] = 1.0 * rightHandedFactor;
  3614. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3615. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3616. // result.m[14] = (znear * zfar) / (znear - zfar);
  3617. };
  3618. /**
  3619. * Returns the final transformation matrix : world * view * projection * viewport
  3620. */
  3621. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3622. var cw = viewport.width;
  3623. var ch = viewport.height;
  3624. var cx = viewport.x;
  3625. var cy = viewport.y;
  3626. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3627. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3628. };
  3629. /**
  3630. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3631. */
  3632. Matrix.GetAsMatrix2x2 = function (matrix) {
  3633. return new Float32Array([
  3634. matrix.m[0], matrix.m[1],
  3635. matrix.m[4], matrix.m[5]
  3636. ]);
  3637. };
  3638. /**
  3639. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3640. */
  3641. Matrix.GetAsMatrix3x3 = function (matrix) {
  3642. return new Float32Array([
  3643. matrix.m[0], matrix.m[1], matrix.m[2],
  3644. matrix.m[4], matrix.m[5], matrix.m[6],
  3645. matrix.m[8], matrix.m[9], matrix.m[10]
  3646. ]);
  3647. };
  3648. /**
  3649. * Compute the transpose of the passed Matrix.
  3650. * Returns a new Matrix.
  3651. */
  3652. Matrix.Transpose = function (matrix) {
  3653. var result = new Matrix();
  3654. result.m[0] = matrix.m[0];
  3655. result.m[1] = matrix.m[4];
  3656. result.m[2] = matrix.m[8];
  3657. result.m[3] = matrix.m[12];
  3658. result.m[4] = matrix.m[1];
  3659. result.m[5] = matrix.m[5];
  3660. result.m[6] = matrix.m[9];
  3661. result.m[7] = matrix.m[13];
  3662. result.m[8] = matrix.m[2];
  3663. result.m[9] = matrix.m[6];
  3664. result.m[10] = matrix.m[10];
  3665. result.m[11] = matrix.m[14];
  3666. result.m[12] = matrix.m[3];
  3667. result.m[13] = matrix.m[7];
  3668. result.m[14] = matrix.m[11];
  3669. result.m[15] = matrix.m[15];
  3670. return result;
  3671. };
  3672. /**
  3673. * Returns a new Matrix as the reflection matrix across the passed plane.
  3674. */
  3675. Matrix.Reflection = function (plane) {
  3676. var matrix = new Matrix();
  3677. Matrix.ReflectionToRef(plane, matrix);
  3678. return matrix;
  3679. };
  3680. /**
  3681. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3682. */
  3683. Matrix.ReflectionToRef = function (plane, result) {
  3684. plane.normalize();
  3685. var x = plane.normal.x;
  3686. var y = plane.normal.y;
  3687. var z = plane.normal.z;
  3688. var temp = -2 * x;
  3689. var temp2 = -2 * y;
  3690. var temp3 = -2 * z;
  3691. result.m[0] = (temp * x) + 1;
  3692. result.m[1] = temp2 * x;
  3693. result.m[2] = temp3 * x;
  3694. result.m[3] = 0.0;
  3695. result.m[4] = temp * y;
  3696. result.m[5] = (temp2 * y) + 1;
  3697. result.m[6] = temp3 * y;
  3698. result.m[7] = 0.0;
  3699. result.m[8] = temp * z;
  3700. result.m[9] = temp2 * z;
  3701. result.m[10] = (temp3 * z) + 1;
  3702. result.m[11] = 0.0;
  3703. result.m[12] = temp * plane.d;
  3704. result.m[13] = temp2 * plane.d;
  3705. result.m[14] = temp3 * plane.d;
  3706. result.m[15] = 1.0;
  3707. };
  3708. /**
  3709. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3710. */
  3711. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  3712. mat.m[0] = xaxis.x;
  3713. mat.m[1] = xaxis.y;
  3714. mat.m[2] = xaxis.z;
  3715. mat.m[3] = 0.0;
  3716. mat.m[4] = yaxis.x;
  3717. mat.m[5] = yaxis.y;
  3718. mat.m[6] = yaxis.z;
  3719. mat.m[7] = 0.0;
  3720. mat.m[8] = zaxis.x;
  3721. mat.m[9] = zaxis.y;
  3722. mat.m[10] = zaxis.z;
  3723. mat.m[11] = 0.0;
  3724. mat.m[12] = 0.0;
  3725. mat.m[13] = 0.0;
  3726. mat.m[14] = 0.0;
  3727. mat.m[15] = 1.0;
  3728. };
  3729. /**
  3730. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3731. */
  3732. Matrix.FromQuaternionToRef = function (quat, result) {
  3733. var xx = quat.x * quat.x;
  3734. var yy = quat.y * quat.y;
  3735. var zz = quat.z * quat.z;
  3736. var xy = quat.x * quat.y;
  3737. var zw = quat.z * quat.w;
  3738. var zx = quat.z * quat.x;
  3739. var yw = quat.y * quat.w;
  3740. var yz = quat.y * quat.z;
  3741. var xw = quat.x * quat.w;
  3742. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3743. result.m[1] = 2.0 * (xy + zw);
  3744. result.m[2] = 2.0 * (zx - yw);
  3745. result.m[3] = 0.0;
  3746. result.m[4] = 2.0 * (xy - zw);
  3747. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3748. result.m[6] = 2.0 * (yz + xw);
  3749. result.m[7] = 0.0;
  3750. result.m[8] = 2.0 * (zx + yw);
  3751. result.m[9] = 2.0 * (yz - xw);
  3752. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3753. result.m[11] = 0.0;
  3754. result.m[12] = 0.0;
  3755. result.m[13] = 0.0;
  3756. result.m[14] = 0.0;
  3757. result.m[15] = 1.0;
  3758. };
  3759. return Matrix;
  3760. }());
  3761. Matrix._tempQuaternion = new Quaternion();
  3762. Matrix._xAxis = Vector3.Zero();
  3763. Matrix._yAxis = Vector3.Zero();
  3764. Matrix._zAxis = Vector3.Zero();
  3765. BABYLON.Matrix = Matrix;
  3766. var Plane = (function () {
  3767. /**
  3768. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3769. */
  3770. function Plane(a, b, c, d) {
  3771. this.normal = new Vector3(a, b, c);
  3772. this.d = d;
  3773. }
  3774. /**
  3775. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3776. */
  3777. Plane.prototype.asArray = function () {
  3778. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3779. };
  3780. // Methods
  3781. /**
  3782. * Returns a new plane copied from the current Plane.
  3783. */
  3784. Plane.prototype.clone = function () {
  3785. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3786. };
  3787. /**
  3788. * Returns the string "Plane".
  3789. */
  3790. Plane.prototype.getClassName = function () {
  3791. return "Plane";
  3792. };
  3793. /**
  3794. * Returns the Plane hash code.
  3795. */
  3796. Plane.prototype.getHashCode = function () {
  3797. var hash = this.normal.getHashCode();
  3798. hash = (hash * 397) ^ (this.d || 0);
  3799. return hash;
  3800. };
  3801. /**
  3802. * Normalize the current Plane in place.
  3803. * Returns the updated Plane.
  3804. */
  3805. Plane.prototype.normalize = function () {
  3806. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3807. var magnitude = 0.0;
  3808. if (norm !== 0) {
  3809. magnitude = 1.0 / norm;
  3810. }
  3811. this.normal.x *= magnitude;
  3812. this.normal.y *= magnitude;
  3813. this.normal.z *= magnitude;
  3814. this.d *= magnitude;
  3815. return this;
  3816. };
  3817. /**
  3818. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3819. */
  3820. Plane.prototype.transform = function (transformation) {
  3821. var transposedMatrix = Matrix.Transpose(transformation);
  3822. var x = this.normal.x;
  3823. var y = this.normal.y;
  3824. var z = this.normal.z;
  3825. var d = this.d;
  3826. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3827. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3828. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3829. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3830. return new Plane(normalX, normalY, normalZ, finalD);
  3831. };
  3832. /**
  3833. * Returns the dot product (float) of the point coordinates and the plane normal.
  3834. */
  3835. Plane.prototype.dotCoordinate = function (point) {
  3836. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3837. };
  3838. /**
  3839. * Updates the current Plane from the plane defined by the three passed points.
  3840. * Returns the updated Plane.
  3841. */
  3842. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3843. var x1 = point2.x - point1.x;
  3844. var y1 = point2.y - point1.y;
  3845. var z1 = point2.z - point1.z;
  3846. var x2 = point3.x - point1.x;
  3847. var y2 = point3.y - point1.y;
  3848. var z2 = point3.z - point1.z;
  3849. var yz = (y1 * z2) - (z1 * y2);
  3850. var xz = (z1 * x2) - (x1 * z2);
  3851. var xy = (x1 * y2) - (y1 * x2);
  3852. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3853. var invPyth;
  3854. if (pyth !== 0) {
  3855. invPyth = 1.0 / pyth;
  3856. }
  3857. else {
  3858. invPyth = 0.0;
  3859. }
  3860. this.normal.x = yz * invPyth;
  3861. this.normal.y = xz * invPyth;
  3862. this.normal.z = xy * invPyth;
  3863. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3864. return this;
  3865. };
  3866. /**
  3867. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3868. */
  3869. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3870. var dot = Vector3.Dot(this.normal, direction);
  3871. return (dot <= epsilon);
  3872. };
  3873. /**
  3874. * Returns the signed distance (float) from the passed point to the Plane.
  3875. */
  3876. Plane.prototype.signedDistanceTo = function (point) {
  3877. return Vector3.Dot(point, this.normal) + this.d;
  3878. };
  3879. // Statics
  3880. /**
  3881. * Returns a new Plane from the passed array.
  3882. */
  3883. Plane.FromArray = function (array) {
  3884. return new Plane(array[0], array[1], array[2], array[3]);
  3885. };
  3886. /**
  3887. * Returns a new Plane defined by the three passed points.
  3888. */
  3889. Plane.FromPoints = function (point1, point2, point3) {
  3890. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3891. result.copyFromPoints(point1, point2, point3);
  3892. return result;
  3893. };
  3894. /**
  3895. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3896. * Note : the vector "normal" is updated because normalized.
  3897. */
  3898. Plane.FromPositionAndNormal = function (origin, normal) {
  3899. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3900. normal.normalize();
  3901. result.normal = normal;
  3902. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3903. return result;
  3904. };
  3905. /**
  3906. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3907. */
  3908. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3909. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3910. return Vector3.Dot(point, normal) + d;
  3911. };
  3912. return Plane;
  3913. }());
  3914. BABYLON.Plane = Plane;
  3915. var Viewport = (function () {
  3916. /**
  3917. * Creates a Viewport object located at (x, y) and sized (width, height).
  3918. */
  3919. function Viewport(x, y, width, height) {
  3920. this.x = x;
  3921. this.y = y;
  3922. this.width = width;
  3923. this.height = height;
  3924. }
  3925. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3926. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3927. };
  3928. /**
  3929. * Returns a new Viewport copied from the current one.
  3930. */
  3931. Viewport.prototype.clone = function () {
  3932. return new Viewport(this.x, this.y, this.width, this.height);
  3933. };
  3934. return Viewport;
  3935. }());
  3936. BABYLON.Viewport = Viewport;
  3937. var Frustum = (function () {
  3938. function Frustum() {
  3939. }
  3940. /**
  3941. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3942. */
  3943. Frustum.GetPlanes = function (transform) {
  3944. var frustumPlanes = [];
  3945. for (var index = 0; index < 6; index++) {
  3946. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3947. }
  3948. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3949. return frustumPlanes;
  3950. };
  3951. /**
  3952. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3953. */
  3954. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3955. // Near
  3956. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3957. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3958. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3959. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3960. frustumPlanes[0].normalize();
  3961. // Far
  3962. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3963. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3964. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3965. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3966. frustumPlanes[1].normalize();
  3967. // Left
  3968. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  3969. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  3970. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  3971. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  3972. frustumPlanes[2].normalize();
  3973. // Right
  3974. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  3975. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  3976. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  3977. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  3978. frustumPlanes[3].normalize();
  3979. // Top
  3980. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  3981. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  3982. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  3983. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  3984. frustumPlanes[4].normalize();
  3985. // Bottom
  3986. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  3987. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  3988. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  3989. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  3990. frustumPlanes[5].normalize();
  3991. };
  3992. return Frustum;
  3993. }());
  3994. BABYLON.Frustum = Frustum;
  3995. var Space;
  3996. (function (Space) {
  3997. Space[Space["LOCAL"] = 0] = "LOCAL";
  3998. Space[Space["WORLD"] = 1] = "WORLD";
  3999. Space[Space["BONE"] = 2] = "BONE";
  4000. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4001. var Axis = (function () {
  4002. function Axis() {
  4003. }
  4004. return Axis;
  4005. }());
  4006. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4007. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4008. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4009. BABYLON.Axis = Axis;
  4010. ;
  4011. var BezierCurve = (function () {
  4012. function BezierCurve() {
  4013. }
  4014. /**
  4015. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4016. */
  4017. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4018. // Extract X (which is equal to time here)
  4019. var f0 = 1 - 3 * x2 + 3 * x1;
  4020. var f1 = 3 * x2 - 6 * x1;
  4021. var f2 = 3 * x1;
  4022. var refinedT = t;
  4023. for (var i = 0; i < 5; i++) {
  4024. var refinedT2 = refinedT * refinedT;
  4025. var refinedT3 = refinedT2 * refinedT;
  4026. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4027. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4028. refinedT -= (x - t) * slope;
  4029. refinedT = Math.min(1, Math.max(0, refinedT));
  4030. }
  4031. // Resolve cubic bezier for the given x
  4032. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4033. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4034. Math.pow(refinedT, 3);
  4035. };
  4036. return BezierCurve;
  4037. }());
  4038. BABYLON.BezierCurve = BezierCurve;
  4039. var Orientation;
  4040. (function (Orientation) {
  4041. Orientation[Orientation["CW"] = 0] = "CW";
  4042. Orientation[Orientation["CCW"] = 1] = "CCW";
  4043. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4044. var Angle = (function () {
  4045. /**
  4046. * Creates an Angle object of "radians" radians (float).
  4047. */
  4048. function Angle(radians) {
  4049. var _this = this;
  4050. /**
  4051. * Returns the Angle value in degrees (float).
  4052. */
  4053. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4054. /**
  4055. * Returns the Angle value in radians (float).
  4056. */
  4057. this.radians = function () { return _this._radians; };
  4058. this._radians = radians;
  4059. if (this._radians < 0.0)
  4060. this._radians += (2.0 * Math.PI);
  4061. }
  4062. /**
  4063. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4064. */
  4065. Angle.BetweenTwoPoints = function (a, b) {
  4066. var delta = b.subtract(a);
  4067. var theta = Math.atan2(delta.y, delta.x);
  4068. return new Angle(theta);
  4069. };
  4070. /**
  4071. * Returns a new Angle object from the passed float in radians.
  4072. */
  4073. Angle.FromRadians = function (radians) {
  4074. return new Angle(radians);
  4075. };
  4076. /**
  4077. * Returns a new Angle object from the passed float in degrees.
  4078. */
  4079. Angle.FromDegrees = function (degrees) {
  4080. return new Angle(degrees * Math.PI / 180.0);
  4081. };
  4082. return Angle;
  4083. }());
  4084. BABYLON.Angle = Angle;
  4085. var Arc2 = (function () {
  4086. /**
  4087. * Creates an Arc object from the three passed points : start, middle and end.
  4088. */
  4089. function Arc2(startPoint, midPoint, endPoint) {
  4090. this.startPoint = startPoint;
  4091. this.midPoint = midPoint;
  4092. this.endPoint = endPoint;
  4093. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4094. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4095. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4096. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4097. 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);
  4098. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4099. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4100. var a1 = this.startAngle.degrees();
  4101. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4102. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4103. // angles correction
  4104. if (a2 - a1 > +180.0)
  4105. a2 -= 360.0;
  4106. if (a2 - a1 < -180.0)
  4107. a2 += 360.0;
  4108. if (a3 - a2 > +180.0)
  4109. a3 -= 360.0;
  4110. if (a3 - a2 < -180.0)
  4111. a3 += 360.0;
  4112. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4113. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4114. }
  4115. return Arc2;
  4116. }());
  4117. BABYLON.Arc2 = Arc2;
  4118. var Path2 = (function () {
  4119. /**
  4120. * Creates a Path2 object from the starting 2D coordinates x and y.
  4121. */
  4122. function Path2(x, y) {
  4123. this._points = new Array();
  4124. this._length = 0.0;
  4125. this.closed = false;
  4126. this._points.push(new Vector2(x, y));
  4127. }
  4128. /**
  4129. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4130. * Returns the updated Path2.
  4131. */
  4132. Path2.prototype.addLineTo = function (x, y) {
  4133. if (closed) {
  4134. //Tools.Error("cannot add lines to closed paths");
  4135. return this;
  4136. }
  4137. var newPoint = new Vector2(x, y);
  4138. var previousPoint = this._points[this._points.length - 1];
  4139. this._points.push(newPoint);
  4140. this._length += newPoint.subtract(previousPoint).length();
  4141. return this;
  4142. };
  4143. /**
  4144. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4145. * Returns the updated Path2.
  4146. */
  4147. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4148. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4149. if (closed) {
  4150. //Tools.Error("cannot add arcs to closed paths");
  4151. return this;
  4152. }
  4153. var startPoint = this._points[this._points.length - 1];
  4154. var midPoint = new Vector2(midX, midY);
  4155. var endPoint = new Vector2(endX, endY);
  4156. var arc = new Arc2(startPoint, midPoint, endPoint);
  4157. var increment = arc.angle.radians() / numberOfSegments;
  4158. if (arc.orientation === Orientation.CW)
  4159. increment *= -1;
  4160. var currentAngle = arc.startAngle.radians() + increment;
  4161. for (var i = 0; i < numberOfSegments; i++) {
  4162. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4163. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4164. this.addLineTo(x, y);
  4165. currentAngle += increment;
  4166. }
  4167. return this;
  4168. };
  4169. /**
  4170. * Closes the Path2.
  4171. * Returns the Path2.
  4172. */
  4173. Path2.prototype.close = function () {
  4174. this.closed = true;
  4175. return this;
  4176. };
  4177. /**
  4178. * Returns the Path2 total length (float).
  4179. */
  4180. Path2.prototype.length = function () {
  4181. var result = this._length;
  4182. if (!this.closed) {
  4183. var lastPoint = this._points[this._points.length - 1];
  4184. var firstPoint = this._points[0];
  4185. result += (firstPoint.subtract(lastPoint).length());
  4186. }
  4187. return result;
  4188. };
  4189. /**
  4190. * Returns the Path2 internal array of points.
  4191. */
  4192. Path2.prototype.getPoints = function () {
  4193. return this._points;
  4194. };
  4195. /**
  4196. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4197. */
  4198. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4199. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4200. //Tools.Error("normalized length position should be between 0 and 1.");
  4201. return Vector2.Zero();
  4202. }
  4203. var lengthPosition = normalizedLengthPosition * this.length();
  4204. var previousOffset = 0;
  4205. for (var i = 0; i < this._points.length; i++) {
  4206. var j = (i + 1) % this._points.length;
  4207. var a = this._points[i];
  4208. var b = this._points[j];
  4209. var bToA = b.subtract(a);
  4210. var nextOffset = (bToA.length() + previousOffset);
  4211. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4212. var dir = bToA.normalize();
  4213. var localOffset = lengthPosition - previousOffset;
  4214. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4215. }
  4216. previousOffset = nextOffset;
  4217. }
  4218. //Tools.Error("internal error");
  4219. return Vector2.Zero();
  4220. };
  4221. /**
  4222. * Returns a new Path2 starting at the coordinates (x, y).
  4223. */
  4224. Path2.StartingAt = function (x, y) {
  4225. return new Path2(x, y);
  4226. };
  4227. return Path2;
  4228. }());
  4229. BABYLON.Path2 = Path2;
  4230. var Path3D = (function () {
  4231. /**
  4232. * new Path3D(path, normal, raw)
  4233. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4234. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4235. * path : an array of Vector3, the curve axis of the Path3D
  4236. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4237. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4238. */
  4239. function Path3D(path, firstNormal, raw) {
  4240. this.path = path;
  4241. this._curve = new Array();
  4242. this._distances = new Array();
  4243. this._tangents = new Array();
  4244. this._normals = new Array();
  4245. this._binormals = new Array();
  4246. for (var p = 0; p < path.length; p++) {
  4247. this._curve[p] = path[p].clone(); // hard copy
  4248. }
  4249. this._raw = raw || false;
  4250. this._compute(firstNormal);
  4251. }
  4252. /**
  4253. * Returns the Path3D array of successive Vector3 designing its curve.
  4254. */
  4255. Path3D.prototype.getCurve = function () {
  4256. return this._curve;
  4257. };
  4258. /**
  4259. * Returns an array populated with tangent vectors on each Path3D curve point.
  4260. */
  4261. Path3D.prototype.getTangents = function () {
  4262. return this._tangents;
  4263. };
  4264. /**
  4265. * Returns an array populated with normal vectors on each Path3D curve point.
  4266. */
  4267. Path3D.prototype.getNormals = function () {
  4268. return this._normals;
  4269. };
  4270. /**
  4271. * Returns an array populated with binormal vectors on each Path3D curve point.
  4272. */
  4273. Path3D.prototype.getBinormals = function () {
  4274. return this._binormals;
  4275. };
  4276. /**
  4277. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4278. */
  4279. Path3D.prototype.getDistances = function () {
  4280. return this._distances;
  4281. };
  4282. /**
  4283. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4284. * Returns the same object updated.
  4285. */
  4286. Path3D.prototype.update = function (path, firstNormal) {
  4287. for (var p = 0; p < path.length; p++) {
  4288. this._curve[p].x = path[p].x;
  4289. this._curve[p].y = path[p].y;
  4290. this._curve[p].z = path[p].z;
  4291. }
  4292. this._compute(firstNormal);
  4293. return this;
  4294. };
  4295. // private function compute() : computes tangents, normals and binormals
  4296. Path3D.prototype._compute = function (firstNormal) {
  4297. var l = this._curve.length;
  4298. // first and last tangents
  4299. this._tangents[0] = this._getFirstNonNullVector(0);
  4300. if (!this._raw) {
  4301. this._tangents[0].normalize();
  4302. }
  4303. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4304. if (!this._raw) {
  4305. this._tangents[l - 1].normalize();
  4306. }
  4307. // normals and binormals at first point : arbitrary vector with _normalVector()
  4308. var tg0 = this._tangents[0];
  4309. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4310. this._normals[0] = pp0;
  4311. if (!this._raw) {
  4312. this._normals[0].normalize();
  4313. }
  4314. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4315. if (!this._raw) {
  4316. this._binormals[0].normalize();
  4317. }
  4318. this._distances[0] = 0.0;
  4319. // normals and binormals : next points
  4320. var prev; // previous vector (segment)
  4321. var cur; // current vector (segment)
  4322. var curTang; // current tangent
  4323. // previous normal
  4324. var prevBinor; // previous binormal
  4325. for (var i = 1; i < l; i++) {
  4326. // tangents
  4327. prev = this._getLastNonNullVector(i);
  4328. if (i < l - 1) {
  4329. cur = this._getFirstNonNullVector(i);
  4330. this._tangents[i] = prev.add(cur);
  4331. this._tangents[i].normalize();
  4332. }
  4333. this._distances[i] = this._distances[i - 1] + prev.length();
  4334. // normals and binormals
  4335. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4336. curTang = this._tangents[i];
  4337. prevBinor = this._binormals[i - 1];
  4338. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4339. if (!this._raw) {
  4340. this._normals[i].normalize();
  4341. }
  4342. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4343. if (!this._raw) {
  4344. this._binormals[i].normalize();
  4345. }
  4346. }
  4347. };
  4348. // private function getFirstNonNullVector(index)
  4349. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4350. Path3D.prototype._getFirstNonNullVector = function (index) {
  4351. var i = 1;
  4352. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4353. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4354. i++;
  4355. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4356. }
  4357. return nNVector;
  4358. };
  4359. // private function getLastNonNullVector(index)
  4360. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4361. Path3D.prototype._getLastNonNullVector = function (index) {
  4362. var i = 1;
  4363. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4364. while (nLVector.length() === 0 && index > i + 1) {
  4365. i++;
  4366. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4367. }
  4368. return nLVector;
  4369. };
  4370. // private function normalVector(v0, vt, va) :
  4371. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4372. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4373. Path3D.prototype._normalVector = function (v0, vt, va) {
  4374. var normal0;
  4375. var tgl = vt.length();
  4376. if (tgl === 0.0) {
  4377. tgl = 1.0;
  4378. }
  4379. if (va === undefined || va === null) {
  4380. var point;
  4381. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4382. point = new Vector3(0.0, -1.0, 0.0);
  4383. }
  4384. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4385. point = new Vector3(1.0, 0.0, 0.0);
  4386. }
  4387. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4388. point = new Vector3(0.0, 0.0, 1.0);
  4389. }
  4390. normal0 = Vector3.Cross(vt, point);
  4391. }
  4392. else {
  4393. normal0 = Vector3.Cross(vt, va);
  4394. Vector3.CrossToRef(normal0, vt, normal0);
  4395. }
  4396. normal0.normalize();
  4397. return normal0;
  4398. };
  4399. return Path3D;
  4400. }());
  4401. BABYLON.Path3D = Path3D;
  4402. var Curve3 = (function () {
  4403. /**
  4404. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4405. * A Curve3 is designed from a series of successive Vector3.
  4406. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4407. */
  4408. function Curve3(points) {
  4409. this._length = 0.0;
  4410. this._points = points;
  4411. this._length = this._computeLength(points);
  4412. }
  4413. /**
  4414. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4415. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4416. * @param v1 (Vector3) the control point
  4417. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4418. * @param nbPoints (integer) the wanted number of points in the curve
  4419. */
  4420. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4421. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4422. var bez = new Array();
  4423. var equation = function (t, val0, val1, val2) {
  4424. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4425. return res;
  4426. };
  4427. for (var i = 0; i <= nbPoints; i++) {
  4428. 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)));
  4429. }
  4430. return new Curve3(bez);
  4431. };
  4432. /**
  4433. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4434. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4435. * @param v1 (Vector3) the first control point
  4436. * @param v2 (Vector3) the second control point
  4437. * @param v3 (Vector3) the end point of the Cubic Bezier
  4438. * @param nbPoints (integer) the wanted number of points in the curve
  4439. */
  4440. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4441. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4442. var bez = new Array();
  4443. var equation = function (t, val0, val1, val2, val3) {
  4444. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4445. return res;
  4446. };
  4447. for (var i = 0; i <= nbPoints; i++) {
  4448. 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)));
  4449. }
  4450. return new Curve3(bez);
  4451. };
  4452. /**
  4453. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4454. * @param p1 (Vector3) the origin point of the Hermite Spline
  4455. * @param t1 (Vector3) the tangent vector at the origin point
  4456. * @param p2 (Vector3) the end point of the Hermite Spline
  4457. * @param t2 (Vector3) the tangent vector at the end point
  4458. * @param nbPoints (integer) the wanted number of points in the curve
  4459. */
  4460. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4461. var hermite = new Array();
  4462. var step = 1.0 / nbPoints;
  4463. for (var i = 0; i <= nbPoints; i++) {
  4464. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4465. }
  4466. return new Curve3(hermite);
  4467. };
  4468. /**
  4469. * Returns a Curve3 object along a CatmullRom Spline curve :
  4470. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4471. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4472. */
  4473. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4474. var totalPoints = new Array();
  4475. totalPoints.push(points[0].clone());
  4476. Array.prototype.push.apply(totalPoints, points);
  4477. totalPoints.push(points[points.length - 1].clone());
  4478. var catmullRom = new Array();
  4479. var step = 1.0 / nbPoints;
  4480. for (var i = 0; i < totalPoints.length - 3; i++) {
  4481. var amount = 0.0;
  4482. for (var c = 0; c < nbPoints; c++) {
  4483. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4484. amount += step;
  4485. }
  4486. }
  4487. i--;
  4488. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4489. return new Curve3(catmullRom);
  4490. };
  4491. /**
  4492. * Returns the Curve3 stored array of successive Vector3
  4493. */
  4494. Curve3.prototype.getPoints = function () {
  4495. return this._points;
  4496. };
  4497. /**
  4498. * Returns the computed length (float) of the curve.
  4499. */
  4500. Curve3.prototype.length = function () {
  4501. return this._length;
  4502. };
  4503. /**
  4504. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4505. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4506. * curveA and curveB keep unchanged.
  4507. */
  4508. Curve3.prototype.continue = function (curve) {
  4509. var lastPoint = this._points[this._points.length - 1];
  4510. var continuedPoints = this._points.slice();
  4511. var curvePoints = curve.getPoints();
  4512. for (var i = 1; i < curvePoints.length; i++) {
  4513. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4514. }
  4515. var continuedCurve = new Curve3(continuedPoints);
  4516. return continuedCurve;
  4517. };
  4518. Curve3.prototype._computeLength = function (path) {
  4519. var l = 0;
  4520. for (var i = 1; i < path.length; i++) {
  4521. l += (path[i].subtract(path[i - 1])).length();
  4522. }
  4523. return l;
  4524. };
  4525. return Curve3;
  4526. }());
  4527. BABYLON.Curve3 = Curve3;
  4528. // SphericalHarmonics
  4529. var SphericalHarmonics = (function () {
  4530. function SphericalHarmonics() {
  4531. this.L00 = Vector3.Zero();
  4532. this.L1_1 = Vector3.Zero();
  4533. this.L10 = Vector3.Zero();
  4534. this.L11 = Vector3.Zero();
  4535. this.L2_2 = Vector3.Zero();
  4536. this.L2_1 = Vector3.Zero();
  4537. this.L20 = Vector3.Zero();
  4538. this.L21 = Vector3.Zero();
  4539. this.L22 = Vector3.Zero();
  4540. }
  4541. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4542. var colorVector = new Vector3(color.r, color.g, color.b);
  4543. var c = colorVector.scale(deltaSolidAngle);
  4544. this.L00 = this.L00.add(c.scale(0.282095));
  4545. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4546. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4547. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4548. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4549. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4550. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4551. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4552. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4553. };
  4554. SphericalHarmonics.prototype.scale = function (scale) {
  4555. this.L00 = this.L00.scale(scale);
  4556. this.L1_1 = this.L1_1.scale(scale);
  4557. this.L10 = this.L10.scale(scale);
  4558. this.L11 = this.L11.scale(scale);
  4559. this.L2_2 = this.L2_2.scale(scale);
  4560. this.L2_1 = this.L2_1.scale(scale);
  4561. this.L20 = this.L20.scale(scale);
  4562. this.L21 = this.L21.scale(scale);
  4563. this.L22 = this.L22.scale(scale);
  4564. };
  4565. return SphericalHarmonics;
  4566. }());
  4567. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4568. // SphericalPolynomial
  4569. var SphericalPolynomial = (function () {
  4570. function SphericalPolynomial() {
  4571. this.x = Vector3.Zero();
  4572. this.y = Vector3.Zero();
  4573. this.z = Vector3.Zero();
  4574. this.xx = Vector3.Zero();
  4575. this.yy = Vector3.Zero();
  4576. this.zz = Vector3.Zero();
  4577. this.xy = Vector3.Zero();
  4578. this.yz = Vector3.Zero();
  4579. this.zx = Vector3.Zero();
  4580. }
  4581. SphericalPolynomial.prototype.addAmbient = function (color) {
  4582. var colorVector = new Vector3(color.r, color.g, color.b);
  4583. this.xx = this.xx.add(colorVector);
  4584. this.yy = this.yy.add(colorVector);
  4585. this.zz = this.zz.add(colorVector);
  4586. };
  4587. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4588. var result = new SphericalPolynomial();
  4589. result.x = harmonics.L11.scale(1.02333);
  4590. result.y = harmonics.L1_1.scale(1.02333);
  4591. result.z = harmonics.L10.scale(1.02333);
  4592. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4593. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4594. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4595. result.yz = harmonics.L2_1.scale(0.858086);
  4596. result.zx = harmonics.L21.scale(0.858086);
  4597. result.xy = harmonics.L2_2.scale(0.858086);
  4598. return result;
  4599. };
  4600. return SphericalPolynomial;
  4601. }());
  4602. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4603. // Vertex formats
  4604. var PositionNormalVertex = (function () {
  4605. function PositionNormalVertex(position, normal) {
  4606. if (position === void 0) { position = Vector3.Zero(); }
  4607. if (normal === void 0) { normal = Vector3.Up(); }
  4608. this.position = position;
  4609. this.normal = normal;
  4610. }
  4611. PositionNormalVertex.prototype.clone = function () {
  4612. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4613. };
  4614. return PositionNormalVertex;
  4615. }());
  4616. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4617. var PositionNormalTextureVertex = (function () {
  4618. function PositionNormalTextureVertex(position, normal, uv) {
  4619. if (position === void 0) { position = Vector3.Zero(); }
  4620. if (normal === void 0) { normal = Vector3.Up(); }
  4621. if (uv === void 0) { uv = Vector2.Zero(); }
  4622. this.position = position;
  4623. this.normal = normal;
  4624. this.uv = uv;
  4625. }
  4626. PositionNormalTextureVertex.prototype.clone = function () {
  4627. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4628. };
  4629. return PositionNormalTextureVertex;
  4630. }());
  4631. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4632. // Temporary pre-allocated objects for engine internal use
  4633. // usage in any internal function :
  4634. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4635. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4636. var Tmp = (function () {
  4637. function Tmp() {
  4638. }
  4639. return Tmp;
  4640. }());
  4641. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4642. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4643. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4644. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4645. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4646. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4647. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4648. Matrix.Zero(), Matrix.Zero(),
  4649. Matrix.Zero(), Matrix.Zero(),
  4650. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4651. BABYLON.Tmp = Tmp;
  4652. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4653. var MathTmp = (function () {
  4654. function MathTmp() {
  4655. }
  4656. return MathTmp;
  4657. }());
  4658. MathTmp.Vector3 = [Vector3.Zero()];
  4659. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4660. MathTmp.Quaternion = [Quaternion.Zero()];
  4661. })(BABYLON || (BABYLON = {}));
  4662. //# sourceMappingURL=babylon.math.js.map
  4663. //# sourceMappingURL=babylon.mixins.js.map
  4664. var BABYLON;
  4665. (function (BABYLON) {
  4666. function generateSerializableMember(type, sourceName) {
  4667. return function (target, propertyKey) {
  4668. if (!target.__serializableMembers) {
  4669. target.__serializableMembers = {};
  4670. }
  4671. if (!target.__serializableMembers[propertyKey]) {
  4672. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4673. }
  4674. };
  4675. }
  4676. function serialize(sourceName) {
  4677. return generateSerializableMember(0, sourceName); // value member
  4678. }
  4679. BABYLON.serialize = serialize;
  4680. function serializeAsTexture(sourceName) {
  4681. return generateSerializableMember(1, sourceName); // texture member
  4682. }
  4683. BABYLON.serializeAsTexture = serializeAsTexture;
  4684. function serializeAsColor3(sourceName) {
  4685. return generateSerializableMember(2, sourceName); // color3 member
  4686. }
  4687. BABYLON.serializeAsColor3 = serializeAsColor3;
  4688. function serializeAsFresnelParameters(sourceName) {
  4689. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4690. }
  4691. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4692. function serializeAsVector2(sourceName) {
  4693. return generateSerializableMember(4, sourceName); // vector2 member
  4694. }
  4695. BABYLON.serializeAsVector2 = serializeAsVector2;
  4696. function serializeAsVector3(sourceName) {
  4697. return generateSerializableMember(5, sourceName); // vector3 member
  4698. }
  4699. BABYLON.serializeAsVector3 = serializeAsVector3;
  4700. function serializeAsMeshReference(sourceName) {
  4701. return generateSerializableMember(6, sourceName); // mesh reference member
  4702. }
  4703. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4704. function serializeAsColorCurves(sourceName) {
  4705. return generateSerializableMember(7, sourceName); // color curves
  4706. }
  4707. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4708. var SerializationHelper = (function () {
  4709. function SerializationHelper() {
  4710. }
  4711. SerializationHelper.Serialize = function (entity, serializationObject) {
  4712. if (!serializationObject) {
  4713. serializationObject = {};
  4714. }
  4715. // Tags
  4716. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4717. // Properties
  4718. for (var property in entity.__serializableMembers) {
  4719. var propertyDescriptor = entity.__serializableMembers[property];
  4720. var targetPropertyName = propertyDescriptor.sourceName || property;
  4721. var propertyType = propertyDescriptor.type;
  4722. var sourceProperty = entity[property];
  4723. if (sourceProperty !== undefined && sourceProperty !== null) {
  4724. switch (propertyType) {
  4725. case 0:
  4726. serializationObject[targetPropertyName] = sourceProperty;
  4727. break;
  4728. case 1:
  4729. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4730. break;
  4731. case 2:
  4732. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4733. break;
  4734. case 3:
  4735. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4736. break;
  4737. case 4:
  4738. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4739. break;
  4740. case 5:
  4741. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4742. break;
  4743. case 6:
  4744. serializationObject[targetPropertyName] = sourceProperty.id;
  4745. break;
  4746. case 7:
  4747. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4748. break;
  4749. }
  4750. }
  4751. }
  4752. return serializationObject;
  4753. };
  4754. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4755. var destination = creationFunction();
  4756. // Tags
  4757. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4758. // Properties
  4759. for (var property in destination.__serializableMembers) {
  4760. var propertyDescriptor = destination.__serializableMembers[property];
  4761. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4762. var propertyType = propertyDescriptor.type;
  4763. if (sourceProperty !== undefined && sourceProperty !== null) {
  4764. switch (propertyType) {
  4765. case 0:
  4766. destination[property] = sourceProperty;
  4767. break;
  4768. case 1:
  4769. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4770. break;
  4771. case 2:
  4772. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4773. break;
  4774. case 3:
  4775. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4776. break;
  4777. case 4:
  4778. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4779. break;
  4780. case 5:
  4781. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4782. break;
  4783. case 6:
  4784. destination[property] = scene.getLastMeshByID(sourceProperty);
  4785. break;
  4786. case 7:
  4787. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4788. break;
  4789. }
  4790. }
  4791. }
  4792. return destination;
  4793. };
  4794. SerializationHelper.Clone = function (creationFunction, source) {
  4795. var destination = creationFunction();
  4796. // Tags
  4797. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4798. // Properties
  4799. for (var property in destination.__serializableMembers) {
  4800. var propertyDescriptor = destination.__serializableMembers[property];
  4801. var sourceProperty = source[property];
  4802. var propertyType = propertyDescriptor.type;
  4803. if (sourceProperty !== undefined && sourceProperty !== null) {
  4804. switch (propertyType) {
  4805. case 0: // Value
  4806. case 6:
  4807. destination[property] = sourceProperty;
  4808. break;
  4809. case 1: // Texture
  4810. case 2: // Color3
  4811. case 3: // FresnelParameters
  4812. case 4: // Vector2
  4813. case 5: // Vector3
  4814. case 7:
  4815. destination[property] = sourceProperty.clone();
  4816. break;
  4817. }
  4818. }
  4819. }
  4820. return destination;
  4821. };
  4822. return SerializationHelper;
  4823. }());
  4824. BABYLON.SerializationHelper = SerializationHelper;
  4825. })(BABYLON || (BABYLON = {}));
  4826. //# sourceMappingURL=babylon.decorators.js.map
  4827. var BABYLON;
  4828. (function (BABYLON) {
  4829. /**
  4830. * A class serves as a medium between the observable and its observers
  4831. */
  4832. var EventState = (function () {
  4833. /**
  4834. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4835. */
  4836. function EventState(mask, skipNextObservers) {
  4837. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4838. this.initalize(mask, skipNextObservers);
  4839. }
  4840. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4841. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4842. this.mask = mask;
  4843. this.skipNextObservers = skipNextObservers;
  4844. return this;
  4845. };
  4846. return EventState;
  4847. }());
  4848. BABYLON.EventState = EventState;
  4849. /**
  4850. * Represent an Observer registered to a given Observable object.
  4851. */
  4852. var Observer = (function () {
  4853. function Observer(callback, mask) {
  4854. this.callback = callback;
  4855. this.mask = mask;
  4856. }
  4857. return Observer;
  4858. }());
  4859. BABYLON.Observer = Observer;
  4860. /**
  4861. * The Observable class is a simple implementation of the Observable pattern.
  4862. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  4863. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4864. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  4865. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  4866. */
  4867. var Observable = (function () {
  4868. function Observable() {
  4869. this._observers = new Array();
  4870. this._eventState = new EventState(0);
  4871. }
  4872. /**
  4873. * Create a new Observer with the specified callback
  4874. * @param callback the callback that will be executed for that Observer
  4875. * @param mask the mask used to filter observers
  4876. * @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.
  4877. */
  4878. Observable.prototype.add = function (callback, mask, insertFirst) {
  4879. if (mask === void 0) { mask = -1; }
  4880. if (insertFirst === void 0) { insertFirst = false; }
  4881. if (!callback) {
  4882. return null;
  4883. }
  4884. var observer = new Observer(callback, mask);
  4885. if (insertFirst) {
  4886. this._observers.unshift(observer);
  4887. }
  4888. else {
  4889. this._observers.push(observer);
  4890. }
  4891. return observer;
  4892. };
  4893. /**
  4894. * Remove an Observer from the Observable object
  4895. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4896. */
  4897. Observable.prototype.remove = function (observer) {
  4898. var index = this._observers.indexOf(observer);
  4899. if (index !== -1) {
  4900. this._observers.splice(index, 1);
  4901. return true;
  4902. }
  4903. return false;
  4904. };
  4905. /**
  4906. * Remove a callback from the Observable object
  4907. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4908. */
  4909. Observable.prototype.removeCallback = function (callback) {
  4910. for (var index = 0; index < this._observers.length; index++) {
  4911. if (this._observers[index].callback === callback) {
  4912. this._observers.splice(index, 1);
  4913. return true;
  4914. }
  4915. }
  4916. return false;
  4917. };
  4918. /**
  4919. * Notify all Observers by calling their respective callback with the given data
  4920. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4921. * @param eventData
  4922. * @param mask
  4923. */
  4924. Observable.prototype.notifyObservers = function (eventData, mask) {
  4925. if (mask === void 0) { mask = -1; }
  4926. var state = this._eventState;
  4927. state.mask = mask;
  4928. state.skipNextObservers = false;
  4929. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4930. var obs = _a[_i];
  4931. if (obs.mask & mask) {
  4932. obs.callback(eventData, state);
  4933. }
  4934. if (state.skipNextObservers) {
  4935. return false;
  4936. }
  4937. }
  4938. return true;
  4939. };
  4940. /**
  4941. * return true is the Observable has at least one Observer registered
  4942. */
  4943. Observable.prototype.hasObservers = function () {
  4944. return this._observers.length > 0;
  4945. };
  4946. /**
  4947. * Clear the list of observers
  4948. */
  4949. Observable.prototype.clear = function () {
  4950. this._observers = new Array();
  4951. };
  4952. /**
  4953. * Clone the current observable
  4954. */
  4955. Observable.prototype.clone = function () {
  4956. var result = new Observable();
  4957. result._observers = this._observers.slice(0);
  4958. return result;
  4959. };
  4960. /**
  4961. * Does this observable handles observer registered with a given mask
  4962. * @param {number} trigger - the mask to be tested
  4963. * @return {boolean} whether or not one observer registered with the given mask is handeled
  4964. **/
  4965. Observable.prototype.hasSpecificMask = function (mask) {
  4966. if (mask === void 0) { mask = -1; }
  4967. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4968. var obs = _a[_i];
  4969. if (obs.mask & mask && obs.mask === mask) {
  4970. return true;
  4971. }
  4972. }
  4973. return false;
  4974. };
  4975. return Observable;
  4976. }());
  4977. BABYLON.Observable = Observable;
  4978. })(BABYLON || (BABYLON = {}));
  4979. //# sourceMappingURL=babylon.observable.js.map
  4980. var BABYLON;
  4981. (function (BABYLON) {
  4982. var Database = (function () {
  4983. function Database(urlToScene, callbackManifestChecked) {
  4984. // Handling various flavors of prefixed version of IndexedDB
  4985. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  4986. this.callbackManifestChecked = callbackManifestChecked;
  4987. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  4988. this.db = null;
  4989. this.enableSceneOffline = false;
  4990. this.enableTexturesOffline = false;
  4991. this.manifestVersionFound = 0;
  4992. this.mustUpdateRessources = false;
  4993. this.hasReachedQuota = false;
  4994. if (!Database.IDBStorageEnabled) {
  4995. this.callbackManifestChecked(true);
  4996. }
  4997. else {
  4998. this.checkManifestFile();
  4999. }
  5000. }
  5001. Database.prototype.checkManifestFile = function () {
  5002. var _this = this;
  5003. function noManifestFile() {
  5004. that.enableSceneOffline = false;
  5005. that.enableTexturesOffline = false;
  5006. that.callbackManifestChecked(false);
  5007. }
  5008. var that = this;
  5009. var timeStampUsed = false;
  5010. var manifestURL = this.currentSceneUrl + ".manifest";
  5011. var xhr = new XMLHttpRequest();
  5012. if (navigator.onLine) {
  5013. // Adding a timestamp to by-pass browsers' cache
  5014. timeStampUsed = true;
  5015. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  5016. }
  5017. xhr.open("GET", manifestURL, true);
  5018. xhr.addEventListener("load", function () {
  5019. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  5020. try {
  5021. var manifestFile = JSON.parse(xhr.response);
  5022. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  5023. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  5024. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  5025. _this.manifestVersionFound = manifestFile.version;
  5026. }
  5027. if (_this.callbackManifestChecked) {
  5028. _this.callbackManifestChecked(true);
  5029. }
  5030. }
  5031. catch (ex) {
  5032. noManifestFile();
  5033. }
  5034. }
  5035. else {
  5036. noManifestFile();
  5037. }
  5038. }, false);
  5039. xhr.addEventListener("error", function (event) {
  5040. if (timeStampUsed) {
  5041. timeStampUsed = false;
  5042. // Let's retry without the timeStamp
  5043. // It could fail when coupled with HTML5 Offline API
  5044. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  5045. xhr.open("GET", retryManifestURL, true);
  5046. xhr.send();
  5047. }
  5048. else {
  5049. noManifestFile();
  5050. }
  5051. }, false);
  5052. try {
  5053. xhr.send();
  5054. }
  5055. catch (ex) {
  5056. BABYLON.Tools.Error("Error on XHR send request.");
  5057. that.callbackManifestChecked(false);
  5058. }
  5059. };
  5060. Database.prototype.openAsync = function (successCallback, errorCallback) {
  5061. var _this = this;
  5062. function handleError() {
  5063. that.isSupported = false;
  5064. if (errorCallback)
  5065. errorCallback();
  5066. }
  5067. var that = this;
  5068. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  5069. // Your browser doesn't support IndexedDB
  5070. this.isSupported = false;
  5071. if (errorCallback)
  5072. errorCallback();
  5073. }
  5074. else {
  5075. // If the DB hasn't been opened or created yet
  5076. if (!this.db) {
  5077. this.hasReachedQuota = false;
  5078. this.isSupported = true;
  5079. var request = this.idbFactory.open("babylonjs", 1);
  5080. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  5081. request.onerror = function (event) {
  5082. handleError();
  5083. };
  5084. // executes when a version change transaction cannot complete due to other active transactions
  5085. request.onblocked = function (event) {
  5086. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  5087. handleError();
  5088. };
  5089. // DB has been opened successfully
  5090. request.onsuccess = function (event) {
  5091. _this.db = request.result;
  5092. successCallback();
  5093. };
  5094. // Initialization of the DB. Creating Scenes & Textures stores
  5095. request.onupgradeneeded = function (event) {
  5096. _this.db = (event.target).result;
  5097. try {
  5098. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  5099. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  5100. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  5101. }
  5102. catch (ex) {
  5103. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  5104. handleError();
  5105. }
  5106. };
  5107. }
  5108. else {
  5109. if (successCallback)
  5110. successCallback();
  5111. }
  5112. }
  5113. };
  5114. Database.prototype.loadImageFromDB = function (url, image) {
  5115. var _this = this;
  5116. var completeURL = Database.ReturnFullUrlLocation(url);
  5117. var saveAndLoadImage = function () {
  5118. if (!_this.hasReachedQuota && _this.db !== null) {
  5119. // the texture is not yet in the DB, let's try to save it
  5120. _this._saveImageIntoDBAsync(completeURL, image);
  5121. }
  5122. else {
  5123. image.src = url;
  5124. }
  5125. };
  5126. if (!this.mustUpdateRessources) {
  5127. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  5128. }
  5129. else {
  5130. saveAndLoadImage();
  5131. }
  5132. };
  5133. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  5134. if (this.isSupported && this.db !== null) {
  5135. var texture;
  5136. var transaction = this.db.transaction(["textures"]);
  5137. transaction.onabort = function (event) {
  5138. image.src = url;
  5139. };
  5140. transaction.oncomplete = function (event) {
  5141. var blobTextureURL;
  5142. if (texture) {
  5143. var URL = window.URL || window.webkitURL;
  5144. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  5145. image.onerror = function () {
  5146. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  5147. image.src = url;
  5148. };
  5149. image.src = blobTextureURL;
  5150. }
  5151. else {
  5152. notInDBCallback();
  5153. }
  5154. };
  5155. var getRequest = transaction.objectStore("textures").get(url);
  5156. getRequest.onsuccess = function (event) {
  5157. texture = (event.target).result;
  5158. };
  5159. getRequest.onerror = function (event) {
  5160. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  5161. image.src = url;
  5162. };
  5163. }
  5164. else {
  5165. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5166. image.src = url;
  5167. }
  5168. };
  5169. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  5170. var _this = this;
  5171. if (this.isSupported) {
  5172. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  5173. var generateBlobUrl = function () {
  5174. var blobTextureURL;
  5175. if (blob) {
  5176. var URL = window.URL || window.webkitURL;
  5177. try {
  5178. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  5179. }
  5180. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  5181. catch (ex) {
  5182. blobTextureURL = URL.createObjectURL(blob);
  5183. }
  5184. }
  5185. image.src = blobTextureURL;
  5186. };
  5187. if (Database.IsUASupportingBlobStorage) {
  5188. var xhr = new XMLHttpRequest(), blob;
  5189. xhr.open("GET", url, true);
  5190. xhr.responseType = "blob";
  5191. xhr.addEventListener("load", function () {
  5192. if (xhr.status === 200) {
  5193. // Blob as response (XHR2)
  5194. blob = xhr.response;
  5195. var transaction = _this.db.transaction(["textures"], "readwrite");
  5196. // the transaction could abort because of a QuotaExceededError error
  5197. transaction.onabort = function (event) {
  5198. try {
  5199. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5200. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5201. _this.hasReachedQuota = true;
  5202. }
  5203. }
  5204. catch (ex) { }
  5205. generateBlobUrl();
  5206. };
  5207. transaction.oncomplete = function (event) {
  5208. generateBlobUrl();
  5209. };
  5210. var newTexture = { textureUrl: url, data: blob };
  5211. try {
  5212. // Put the blob into the dabase
  5213. var addRequest = transaction.objectStore("textures").put(newTexture);
  5214. addRequest.onsuccess = function (event) {
  5215. };
  5216. addRequest.onerror = function (event) {
  5217. generateBlobUrl();
  5218. };
  5219. }
  5220. catch (ex) {
  5221. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  5222. if (ex.code === 25) {
  5223. Database.IsUASupportingBlobStorage = false;
  5224. }
  5225. image.src = url;
  5226. }
  5227. }
  5228. else {
  5229. image.src = url;
  5230. }
  5231. }, false);
  5232. xhr.addEventListener("error", function (event) {
  5233. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  5234. image.src = url;
  5235. }, false);
  5236. xhr.send();
  5237. }
  5238. else {
  5239. image.src = url;
  5240. }
  5241. }
  5242. else {
  5243. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5244. image.src = url;
  5245. }
  5246. };
  5247. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  5248. var _this = this;
  5249. var updateVersion = function (event) {
  5250. // the version is not yet in the DB or we need to update it
  5251. _this._saveVersionIntoDBAsync(url, versionLoaded);
  5252. };
  5253. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  5254. };
  5255. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  5256. var _this = this;
  5257. if (this.isSupported) {
  5258. var version;
  5259. try {
  5260. var transaction = this.db.transaction(["versions"]);
  5261. transaction.oncomplete = function (event) {
  5262. if (version) {
  5263. // If the version in the JSON file is > than the version in DB
  5264. if (_this.manifestVersionFound > version.data) {
  5265. _this.mustUpdateRessources = true;
  5266. updateInDBCallback();
  5267. }
  5268. else {
  5269. callback(version.data);
  5270. }
  5271. }
  5272. else {
  5273. _this.mustUpdateRessources = true;
  5274. updateInDBCallback();
  5275. }
  5276. };
  5277. transaction.onabort = function (event) {
  5278. callback(-1);
  5279. };
  5280. var getRequest = transaction.objectStore("versions").get(url);
  5281. getRequest.onsuccess = function (event) {
  5282. version = (event.target).result;
  5283. };
  5284. getRequest.onerror = function (event) {
  5285. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  5286. callback(-1);
  5287. };
  5288. }
  5289. catch (ex) {
  5290. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  5291. callback(-1);
  5292. }
  5293. }
  5294. else {
  5295. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5296. callback(-1);
  5297. }
  5298. };
  5299. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  5300. var _this = this;
  5301. if (this.isSupported && !this.hasReachedQuota) {
  5302. try {
  5303. // Open a transaction to the database
  5304. var transaction = this.db.transaction(["versions"], "readwrite");
  5305. // the transaction could abort because of a QuotaExceededError error
  5306. transaction.onabort = function (event) {
  5307. try {
  5308. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5309. _this.hasReachedQuota = true;
  5310. }
  5311. }
  5312. catch (ex) { }
  5313. callback(-1);
  5314. };
  5315. transaction.oncomplete = function (event) {
  5316. callback(_this.manifestVersionFound);
  5317. };
  5318. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  5319. // Put the scene into the database
  5320. var addRequest = transaction.objectStore("versions").put(newVersion);
  5321. addRequest.onsuccess = function (event) {
  5322. };
  5323. addRequest.onerror = function (event) {
  5324. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  5325. };
  5326. }
  5327. catch (ex) {
  5328. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  5329. callback(-1);
  5330. }
  5331. }
  5332. else {
  5333. callback(-1);
  5334. }
  5335. };
  5336. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  5337. var _this = this;
  5338. var completeUrl = Database.ReturnFullUrlLocation(url);
  5339. var saveAndLoadFile = function (event) {
  5340. // the scene is not yet in the DB, let's try to save it
  5341. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  5342. };
  5343. this._checkVersionFromDB(completeUrl, function (version) {
  5344. if (version !== -1) {
  5345. if (!_this.mustUpdateRessources) {
  5346. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  5347. }
  5348. else {
  5349. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  5350. }
  5351. }
  5352. else {
  5353. errorCallback();
  5354. }
  5355. });
  5356. };
  5357. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  5358. if (this.isSupported) {
  5359. var targetStore;
  5360. if (url.indexOf(".babylon") !== -1) {
  5361. targetStore = "scenes";
  5362. }
  5363. else {
  5364. targetStore = "textures";
  5365. }
  5366. var file;
  5367. var transaction = this.db.transaction([targetStore]);
  5368. transaction.oncomplete = function (event) {
  5369. if (file) {
  5370. callback(file.data);
  5371. }
  5372. else {
  5373. notInDBCallback();
  5374. }
  5375. };
  5376. transaction.onabort = function (event) {
  5377. notInDBCallback();
  5378. };
  5379. var getRequest = transaction.objectStore(targetStore).get(url);
  5380. getRequest.onsuccess = function (event) {
  5381. file = (event.target).result;
  5382. };
  5383. getRequest.onerror = function (event) {
  5384. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  5385. notInDBCallback();
  5386. };
  5387. }
  5388. else {
  5389. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5390. callback();
  5391. }
  5392. };
  5393. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  5394. var _this = this;
  5395. if (this.isSupported) {
  5396. var targetStore;
  5397. if (url.indexOf(".babylon") !== -1) {
  5398. targetStore = "scenes";
  5399. }
  5400. else {
  5401. targetStore = "textures";
  5402. }
  5403. // Create XHR
  5404. var xhr = new XMLHttpRequest(), fileData;
  5405. xhr.open("GET", url, true);
  5406. if (useArrayBuffer) {
  5407. xhr.responseType = "arraybuffer";
  5408. }
  5409. xhr.onprogress = progressCallback;
  5410. xhr.addEventListener("load", function () {
  5411. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  5412. // Blob as response (XHR2)
  5413. //fileData = xhr.responseText;
  5414. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  5415. if (!_this.hasReachedQuota) {
  5416. // Open a transaction to the database
  5417. var transaction = _this.db.transaction([targetStore], "readwrite");
  5418. // the transaction could abort because of a QuotaExceededError error
  5419. transaction.onabort = function (event) {
  5420. try {
  5421. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5422. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5423. _this.hasReachedQuota = true;
  5424. }
  5425. }
  5426. catch (ex) { }
  5427. callback(fileData);
  5428. };
  5429. transaction.oncomplete = function (event) {
  5430. callback(fileData);
  5431. };
  5432. var newFile;
  5433. if (targetStore === "scenes") {
  5434. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  5435. }
  5436. else {
  5437. newFile = { textureUrl: url, data: fileData };
  5438. }
  5439. try {
  5440. // Put the scene into the database
  5441. var addRequest = transaction.objectStore(targetStore).put(newFile);
  5442. addRequest.onsuccess = function (event) {
  5443. };
  5444. addRequest.onerror = function (event) {
  5445. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  5446. };
  5447. }
  5448. catch (ex) {
  5449. callback(fileData);
  5450. }
  5451. }
  5452. else {
  5453. callback(fileData);
  5454. }
  5455. }
  5456. else {
  5457. callback();
  5458. }
  5459. }, false);
  5460. xhr.addEventListener("error", function (event) {
  5461. BABYLON.Tools.Error("error on XHR request.");
  5462. callback();
  5463. }, false);
  5464. xhr.send();
  5465. }
  5466. else {
  5467. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5468. callback();
  5469. }
  5470. };
  5471. return Database;
  5472. }());
  5473. Database.IsUASupportingBlobStorage = true;
  5474. Database.IDBStorageEnabled = true;
  5475. Database.parseURL = function (url) {
  5476. var a = document.createElement('a');
  5477. a.href = url;
  5478. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  5479. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  5480. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  5481. return absLocation;
  5482. };
  5483. Database.ReturnFullUrlLocation = function (url) {
  5484. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  5485. return (Database.parseURL(window.location.href) + url);
  5486. }
  5487. else {
  5488. return url;
  5489. }
  5490. };
  5491. BABYLON.Database = Database;
  5492. })(BABYLON || (BABYLON = {}));
  5493. //# sourceMappingURL=babylon.database.js.map
  5494. var BABYLON;
  5495. (function (BABYLON) {
  5496. var Internals;
  5497. (function (Internals) {
  5498. /*
  5499. * Based on jsTGALoader - Javascript loader for TGA file
  5500. * By Vincent Thibault
  5501. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  5502. */
  5503. var TGATools = (function () {
  5504. function TGATools() {
  5505. }
  5506. TGATools.GetTGAHeader = function (data) {
  5507. var offset = 0;
  5508. var header = {
  5509. id_length: data[offset++],
  5510. colormap_type: data[offset++],
  5511. image_type: data[offset++],
  5512. colormap_index: data[offset++] | data[offset++] << 8,
  5513. colormap_length: data[offset++] | data[offset++] << 8,
  5514. colormap_size: data[offset++],
  5515. origin: [
  5516. data[offset++] | data[offset++] << 8,
  5517. data[offset++] | data[offset++] << 8
  5518. ],
  5519. width: data[offset++] | data[offset++] << 8,
  5520. height: data[offset++] | data[offset++] << 8,
  5521. pixel_size: data[offset++],
  5522. flags: data[offset++]
  5523. };
  5524. return header;
  5525. };
  5526. TGATools.UploadContent = function (gl, data) {
  5527. // Not enough data to contain header ?
  5528. if (data.length < 19) {
  5529. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  5530. return;
  5531. }
  5532. // Read Header
  5533. var offset = 18;
  5534. var header = TGATools.GetTGAHeader(data);
  5535. // Assume it's a valid Targa file.
  5536. if (header.id_length + offset > data.length) {
  5537. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  5538. return;
  5539. }
  5540. // Skip not needed data
  5541. offset += header.id_length;
  5542. var use_rle = false;
  5543. var use_pal = false;
  5544. var use_rgb = false;
  5545. var use_grey = false;
  5546. // Get some informations.
  5547. switch (header.image_type) {
  5548. case TGATools._TYPE_RLE_INDEXED:
  5549. use_rle = true;
  5550. case TGATools._TYPE_INDEXED:
  5551. use_pal = true;
  5552. break;
  5553. case TGATools._TYPE_RLE_RGB:
  5554. use_rle = true;
  5555. case TGATools._TYPE_RGB:
  5556. use_rgb = true;
  5557. break;
  5558. case TGATools._TYPE_RLE_GREY:
  5559. use_rle = true;
  5560. case TGATools._TYPE_GREY:
  5561. use_grey = true;
  5562. break;
  5563. }
  5564. var pixel_data;
  5565. var numAlphaBits = header.flags & 0xf;
  5566. var pixel_size = header.pixel_size >> 3;
  5567. var pixel_total = header.width * header.height * pixel_size;
  5568. // Read palettes
  5569. var palettes;
  5570. if (use_pal) {
  5571. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  5572. }
  5573. // Read LRE
  5574. if (use_rle) {
  5575. pixel_data = new Uint8Array(pixel_total);
  5576. var c, count, i;
  5577. var localOffset = 0;
  5578. var pixels = new Uint8Array(pixel_size);
  5579. while (offset < pixel_total && localOffset < pixel_total) {
  5580. c = data[offset++];
  5581. count = (c & 0x7f) + 1;
  5582. // RLE pixels
  5583. if (c & 0x80) {
  5584. // Bind pixel tmp array
  5585. for (i = 0; i < pixel_size; ++i) {
  5586. pixels[i] = data[offset++];
  5587. }
  5588. // Copy pixel array
  5589. for (i = 0; i < count; ++i) {
  5590. pixel_data.set(pixels, localOffset + i * pixel_size);
  5591. }
  5592. localOffset += pixel_size * count;
  5593. }
  5594. else {
  5595. count *= pixel_size;
  5596. for (i = 0; i < count; ++i) {
  5597. pixel_data[localOffset + i] = data[offset++];
  5598. }
  5599. localOffset += count;
  5600. }
  5601. }
  5602. }
  5603. else {
  5604. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  5605. }
  5606. // Load to texture
  5607. var x_start, y_start, x_step, y_step, y_end, x_end;
  5608. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  5609. default:
  5610. case TGATools._ORIGIN_UL:
  5611. x_start = 0;
  5612. x_step = 1;
  5613. x_end = header.width;
  5614. y_start = 0;
  5615. y_step = 1;
  5616. y_end = header.height;
  5617. break;
  5618. case TGATools._ORIGIN_BL:
  5619. x_start = 0;
  5620. x_step = 1;
  5621. x_end = header.width;
  5622. y_start = header.height - 1;
  5623. y_step = -1;
  5624. y_end = -1;
  5625. break;
  5626. case TGATools._ORIGIN_UR:
  5627. x_start = header.width - 1;
  5628. x_step = -1;
  5629. x_end = -1;
  5630. y_start = 0;
  5631. y_step = 1;
  5632. y_end = header.height;
  5633. break;
  5634. case TGATools._ORIGIN_BR:
  5635. x_start = header.width - 1;
  5636. x_step = -1;
  5637. x_end = -1;
  5638. y_start = header.height - 1;
  5639. y_step = -1;
  5640. y_end = -1;
  5641. break;
  5642. }
  5643. // Load the specify method
  5644. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  5645. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  5646. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  5647. };
  5648. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5649. var image = pixel_data, colormap = palettes;
  5650. var width = header.width, height = header.height;
  5651. var color, i = 0, x, y;
  5652. var imageData = new Uint8Array(width * height * 4);
  5653. for (y = y_start; y !== y_end; y += y_step) {
  5654. for (x = x_start; x !== x_end; x += x_step, i++) {
  5655. color = image[i];
  5656. imageData[(x + width * y) * 4 + 3] = 255;
  5657. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  5658. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  5659. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  5660. }
  5661. }
  5662. return imageData;
  5663. };
  5664. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5665. var image = pixel_data;
  5666. var width = header.width, height = header.height;
  5667. var color, i = 0, x, y;
  5668. var imageData = new Uint8Array(width * height * 4);
  5669. for (y = y_start; y !== y_end; y += y_step) {
  5670. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5671. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  5672. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  5673. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  5674. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  5675. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  5676. }
  5677. }
  5678. return imageData;
  5679. };
  5680. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5681. var image = pixel_data;
  5682. var width = header.width, height = header.height;
  5683. var i = 0, x, y;
  5684. var imageData = new Uint8Array(width * height * 4);
  5685. for (y = y_start; y !== y_end; y += y_step) {
  5686. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  5687. imageData[(x + width * y) * 4 + 3] = 255;
  5688. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5689. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5690. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5691. }
  5692. }
  5693. return imageData;
  5694. };
  5695. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5696. var image = pixel_data;
  5697. var width = header.width, height = header.height;
  5698. var i = 0, x, y;
  5699. var imageData = new Uint8Array(width * height * 4);
  5700. for (y = y_start; y !== y_end; y += y_step) {
  5701. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  5702. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5703. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5704. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5705. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  5706. }
  5707. }
  5708. return imageData;
  5709. };
  5710. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5711. var image = pixel_data;
  5712. var width = header.width, height = header.height;
  5713. var color, i = 0, x, y;
  5714. var imageData = new Uint8Array(width * height * 4);
  5715. for (y = y_start; y !== y_end; y += y_step) {
  5716. for (x = x_start; x !== x_end; x += x_step, i++) {
  5717. color = image[i];
  5718. imageData[(x + width * y) * 4 + 0] = color;
  5719. imageData[(x + width * y) * 4 + 1] = color;
  5720. imageData[(x + width * y) * 4 + 2] = color;
  5721. imageData[(x + width * y) * 4 + 3] = 255;
  5722. }
  5723. }
  5724. return imageData;
  5725. };
  5726. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5727. var image = pixel_data;
  5728. var width = header.width, height = header.height;
  5729. var i = 0, x, y;
  5730. var imageData = new Uint8Array(width * height * 4);
  5731. for (y = y_start; y !== y_end; y += y_step) {
  5732. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5733. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  5734. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  5735. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5736. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  5737. }
  5738. }
  5739. return imageData;
  5740. };
  5741. return TGATools;
  5742. }());
  5743. TGATools._TYPE_NO_DATA = 0;
  5744. TGATools._TYPE_INDEXED = 1;
  5745. TGATools._TYPE_RGB = 2;
  5746. TGATools._TYPE_GREY = 3;
  5747. TGATools._TYPE_RLE_INDEXED = 9;
  5748. TGATools._TYPE_RLE_RGB = 10;
  5749. TGATools._TYPE_RLE_GREY = 11;
  5750. TGATools._ORIGIN_MASK = 0x30;
  5751. TGATools._ORIGIN_SHIFT = 0x04;
  5752. TGATools._ORIGIN_BL = 0x00;
  5753. TGATools._ORIGIN_BR = 0x01;
  5754. TGATools._ORIGIN_UL = 0x02;
  5755. TGATools._ORIGIN_UR = 0x03;
  5756. Internals.TGATools = TGATools;
  5757. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5758. })(BABYLON || (BABYLON = {}));
  5759. //# sourceMappingURL=babylon.tools.tga.js.map
  5760. var BABYLON;
  5761. (function (BABYLON) {
  5762. var SmartArray = (function () {
  5763. function SmartArray(capacity) {
  5764. this.length = 0;
  5765. this._duplicateId = 0;
  5766. this.data = new Array(capacity);
  5767. this._id = SmartArray._GlobalId++;
  5768. }
  5769. SmartArray.prototype.push = function (value) {
  5770. this.data[this.length++] = value;
  5771. if (this.length > this.data.length) {
  5772. this.data.length *= 2;
  5773. }
  5774. if (!value.__smartArrayFlags) {
  5775. value.__smartArrayFlags = {};
  5776. }
  5777. value.__smartArrayFlags[this._id] = this._duplicateId;
  5778. };
  5779. SmartArray.prototype.forEach = function (func) {
  5780. for (var index = 0; index < this.length; index++) {
  5781. func(this.data[index]);
  5782. }
  5783. };
  5784. SmartArray.prototype.pushNoDuplicate = function (value) {
  5785. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5786. return false;
  5787. }
  5788. this.push(value);
  5789. return true;
  5790. };
  5791. SmartArray.prototype.sort = function (compareFn) {
  5792. this.data.sort(compareFn);
  5793. };
  5794. SmartArray.prototype.reset = function () {
  5795. this.length = 0;
  5796. this._duplicateId++;
  5797. };
  5798. SmartArray.prototype.dispose = function () {
  5799. this.reset();
  5800. this.data.length = 0;
  5801. };
  5802. SmartArray.prototype.concat = function (array) {
  5803. if (array.length === 0) {
  5804. return;
  5805. }
  5806. if (this.length + array.length > this.data.length) {
  5807. this.data.length = (this.length + array.length) * 2;
  5808. }
  5809. for (var index = 0; index < array.length; index++) {
  5810. this.data[this.length++] = (array.data || array)[index];
  5811. }
  5812. };
  5813. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5814. if (array.length === 0) {
  5815. return;
  5816. }
  5817. if (this.length + array.length > this.data.length) {
  5818. this.data.length = (this.length + array.length) * 2;
  5819. }
  5820. for (var index = 0; index < array.length; index++) {
  5821. var item = (array.data || array)[index];
  5822. this.pushNoDuplicate(item);
  5823. }
  5824. };
  5825. SmartArray.prototype.indexOf = function (value) {
  5826. var position = this.data.indexOf(value);
  5827. if (position >= this.length) {
  5828. return -1;
  5829. }
  5830. return position;
  5831. };
  5832. return SmartArray;
  5833. }());
  5834. // Statics
  5835. SmartArray._GlobalId = 0;
  5836. BABYLON.SmartArray = SmartArray;
  5837. })(BABYLON || (BABYLON = {}));
  5838. //# sourceMappingURL=babylon.smartArray.js.map
  5839. var BABYLON;
  5840. (function (BABYLON) {
  5841. /**
  5842. * This class implement a typical dictionary using a string as key and the generic type T as value.
  5843. * The underlying implementation relies on an associative array to ensure the best performances.
  5844. * The value can be anything including 'null' but except 'undefined'
  5845. */
  5846. var StringDictionary = (function () {
  5847. function StringDictionary() {
  5848. this._count = 0;
  5849. this._data = {};
  5850. }
  5851. /**
  5852. * This will clear this dictionary and copy the content from the 'source' one.
  5853. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  5854. * @param source the dictionary to take the content from and copy to this dictionary
  5855. */
  5856. StringDictionary.prototype.copyFrom = function (source) {
  5857. var _this = this;
  5858. this.clear();
  5859. source.forEach(function (t, v) { return _this.add(t, v); });
  5860. };
  5861. /**
  5862. * Get a value based from its key
  5863. * @param key the given key to get the matching value from
  5864. * @return the value if found, otherwise undefined is returned
  5865. */
  5866. StringDictionary.prototype.get = function (key) {
  5867. var val = this._data[key];
  5868. if (val !== undefined) {
  5869. return val;
  5870. }
  5871. return undefined;
  5872. };
  5873. /**
  5874. * Get a value from its key or add it if it doesn't exist.
  5875. * This method will ensure you that a given key/data will be present in the dictionary.
  5876. * @param key the given key to get the matching value from
  5877. * @param factory the factory that will create the value if the key is not present in the dictionary.
  5878. * The factory will only be invoked if there's no data for the given key.
  5879. * @return the value corresponding to the key.
  5880. */
  5881. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  5882. var val = this.get(key);
  5883. if (val !== undefined) {
  5884. return val;
  5885. }
  5886. val = factory(key);
  5887. if (val) {
  5888. this.add(key, val);
  5889. }
  5890. return val;
  5891. };
  5892. /**
  5893. * Get a value from its key if present in the dictionary otherwise add it
  5894. * @param key the key to get the value from
  5895. * @param val if there's no such key/value pair in the dictionary add it with this value
  5896. * @return the value corresponding to the key
  5897. */
  5898. StringDictionary.prototype.getOrAdd = function (key, val) {
  5899. var curVal = this.get(key);
  5900. if (curVal !== undefined) {
  5901. return curVal;
  5902. }
  5903. this.add(key, val);
  5904. return val;
  5905. };
  5906. /**
  5907. * Check if there's a given key in the dictionary
  5908. * @param key the key to check for
  5909. * @return true if the key is present, false otherwise
  5910. */
  5911. StringDictionary.prototype.contains = function (key) {
  5912. return this._data[key] !== undefined;
  5913. };
  5914. /**
  5915. * Add a new key and its corresponding value
  5916. * @param key the key to add
  5917. * @param value the value corresponding to the key
  5918. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  5919. */
  5920. StringDictionary.prototype.add = function (key, value) {
  5921. if (this._data[key] !== undefined) {
  5922. return false;
  5923. }
  5924. this._data[key] = value;
  5925. ++this._count;
  5926. return true;
  5927. };
  5928. StringDictionary.prototype.set = function (key, value) {
  5929. if (this._data[key] === undefined) {
  5930. return false;
  5931. }
  5932. this._data[key] = value;
  5933. return true;
  5934. };
  5935. /**
  5936. * Get the element of the given key and remove it from the dictionary
  5937. * @param key
  5938. */
  5939. StringDictionary.prototype.getAndRemove = function (key) {
  5940. var val = this.get(key);
  5941. if (val !== undefined) {
  5942. delete this._data[key];
  5943. --this._count;
  5944. return val;
  5945. }
  5946. return null;
  5947. };
  5948. /**
  5949. * Remove a key/value from the dictionary.
  5950. * @param key the key to remove
  5951. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  5952. */
  5953. StringDictionary.prototype.remove = function (key) {
  5954. if (this.contains(key)) {
  5955. delete this._data[key];
  5956. --this._count;
  5957. return true;
  5958. }
  5959. return false;
  5960. };
  5961. /**
  5962. * Clear the whole content of the dictionary
  5963. */
  5964. StringDictionary.prototype.clear = function () {
  5965. this._data = {};
  5966. this._count = 0;
  5967. };
  5968. Object.defineProperty(StringDictionary.prototype, "count", {
  5969. get: function () {
  5970. return this._count;
  5971. },
  5972. enumerable: true,
  5973. configurable: true
  5974. });
  5975. /**
  5976. * Execute a callback on each key/val of the dictionary.
  5977. * Note that you can remove any element in this dictionary in the callback implementation
  5978. * @param callback the callback to execute on a given key/value pair
  5979. */
  5980. StringDictionary.prototype.forEach = function (callback) {
  5981. for (var cur in this._data) {
  5982. var val = this._data[cur];
  5983. callback(cur, val);
  5984. }
  5985. };
  5986. /**
  5987. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  5988. * If the callback returns null or undefined the method will iterate to the next key/value pair
  5989. * Note that you can remove any element in this dictionary in the callback implementation
  5990. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  5991. */
  5992. StringDictionary.prototype.first = function (callback) {
  5993. for (var cur in this._data) {
  5994. var val = this._data[cur];
  5995. var res = callback(cur, val);
  5996. if (res) {
  5997. return res;
  5998. }
  5999. }
  6000. return null;
  6001. };
  6002. return StringDictionary;
  6003. }());
  6004. BABYLON.StringDictionary = StringDictionary;
  6005. })(BABYLON || (BABYLON = {}));
  6006. //# sourceMappingURL=babylon.stringDictionary.js.map
  6007. var BABYLON;
  6008. (function (BABYLON) {
  6009. // Screenshots
  6010. var screenshotCanvas;
  6011. var cloneValue = function (source, destinationObject) {
  6012. if (!source)
  6013. return null;
  6014. if (source instanceof BABYLON.Mesh) {
  6015. return null;
  6016. }
  6017. if (source instanceof BABYLON.SubMesh) {
  6018. return source.clone(destinationObject);
  6019. }
  6020. else if (source.clone) {
  6021. return source.clone();
  6022. }
  6023. return null;
  6024. };
  6025. var Tools = (function () {
  6026. function Tools() {
  6027. }
  6028. ;
  6029. Tools.Instantiate = function (className) {
  6030. var arr = className.split(".");
  6031. var fn = (window || this);
  6032. for (var i = 0, len = arr.length; i < len; i++) {
  6033. fn = fn[arr[i]];
  6034. }
  6035. if (typeof fn !== "function") {
  6036. return null;
  6037. }
  6038. return fn;
  6039. };
  6040. Tools.SetImmediate = function (action) {
  6041. if (window.setImmediate) {
  6042. window.setImmediate(action);
  6043. }
  6044. else {
  6045. setTimeout(action, 1);
  6046. }
  6047. };
  6048. Tools.IsExponentOfTwo = function (value) {
  6049. var count = 1;
  6050. do {
  6051. count *= 2;
  6052. } while (count < value);
  6053. return count === value;
  6054. };
  6055. Tools.GetExponentOfTwo = function (value, max) {
  6056. var count = 1;
  6057. do {
  6058. count *= 2;
  6059. } while (count < value);
  6060. if (count > max)
  6061. count = max;
  6062. return count;
  6063. };
  6064. Tools.GetFilename = function (path) {
  6065. var index = path.lastIndexOf("/");
  6066. if (index < 0)
  6067. return path;
  6068. return path.substring(index + 1);
  6069. };
  6070. Tools.GetDOMTextContent = function (element) {
  6071. var result = "";
  6072. var child = element.firstChild;
  6073. while (child) {
  6074. if (child.nodeType === 3) {
  6075. result += child.textContent;
  6076. }
  6077. child = child.nextSibling;
  6078. }
  6079. return result;
  6080. };
  6081. Tools.ToDegrees = function (angle) {
  6082. return angle * 180 / Math.PI;
  6083. };
  6084. Tools.ToRadians = function (angle) {
  6085. return angle * Math.PI / 180;
  6086. };
  6087. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6088. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6089. var output = "";
  6090. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6091. var i = 0;
  6092. var bytes = new Uint8Array(buffer);
  6093. while (i < bytes.length) {
  6094. chr1 = bytes[i++];
  6095. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6096. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6097. enc1 = chr1 >> 2;
  6098. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6099. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6100. enc4 = chr3 & 63;
  6101. if (isNaN(chr2)) {
  6102. enc3 = enc4 = 64;
  6103. }
  6104. else if (isNaN(chr3)) {
  6105. enc4 = 64;
  6106. }
  6107. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6108. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6109. }
  6110. return "data:image/png;base64," + output;
  6111. };
  6112. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6113. if (bias === void 0) { bias = null; }
  6114. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6115. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6116. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6117. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6118. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6119. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6120. }
  6121. if (bias) {
  6122. minimum.x -= minimum.x * bias.x + bias.y;
  6123. minimum.y -= minimum.y * bias.x + bias.y;
  6124. minimum.z -= minimum.z * bias.x + bias.y;
  6125. maximum.x += maximum.x * bias.x + bias.y;
  6126. maximum.y += maximum.y * bias.x + bias.y;
  6127. maximum.z += maximum.z * bias.x + bias.y;
  6128. }
  6129. return {
  6130. minimum: minimum,
  6131. maximum: maximum
  6132. };
  6133. };
  6134. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6135. if (bias === void 0) { bias = null; }
  6136. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6137. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6138. if (!stride) {
  6139. stride = 3;
  6140. }
  6141. for (var index = start; index < start + count; index++) {
  6142. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6143. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6144. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6145. }
  6146. if (bias) {
  6147. minimum.x -= minimum.x * bias.x + bias.y;
  6148. minimum.y -= minimum.y * bias.x + bias.y;
  6149. minimum.z -= minimum.z * bias.x + bias.y;
  6150. maximum.x += maximum.x * bias.x + bias.y;
  6151. maximum.y += maximum.y * bias.x + bias.y;
  6152. maximum.z += maximum.z * bias.x + bias.y;
  6153. }
  6154. return {
  6155. minimum: minimum,
  6156. maximum: maximum
  6157. };
  6158. };
  6159. Tools.Vector2ArrayFeeder = function (array) {
  6160. return function (index) {
  6161. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6162. var length = isFloatArray ? array.length / 2 : array.length;
  6163. if (index >= length) {
  6164. return null;
  6165. }
  6166. if (isFloatArray) {
  6167. var fa = array;
  6168. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6169. }
  6170. var a = array;
  6171. return a[index];
  6172. };
  6173. };
  6174. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6175. if (bias === void 0) { bias = null; }
  6176. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6177. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6178. var i = 0;
  6179. var cur = feeder(i++);
  6180. while (cur) {
  6181. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6182. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6183. cur = feeder(i++);
  6184. }
  6185. if (bias) {
  6186. minimum.x -= minimum.x * bias.x + bias.y;
  6187. minimum.y -= minimum.y * bias.x + bias.y;
  6188. maximum.x += maximum.x * bias.x + bias.y;
  6189. maximum.y += maximum.y * bias.x + bias.y;
  6190. }
  6191. return {
  6192. minimum: minimum,
  6193. maximum: maximum
  6194. };
  6195. };
  6196. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6197. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6198. return undefined;
  6199. return Array.isArray(obj) ? obj : [obj];
  6200. };
  6201. // Misc.
  6202. Tools.GetPointerPrefix = function () {
  6203. var eventPrefix = "pointer";
  6204. // Check if pointer events are supported
  6205. if (!window.PointerEvent && !navigator.pointerEnabled) {
  6206. eventPrefix = "mouse";
  6207. }
  6208. return eventPrefix;
  6209. };
  6210. /**
  6211. * @param func - the function to be called
  6212. * @param requester - the object that will request the next frame. Falls back to window.
  6213. */
  6214. Tools.QueueNewFrame = function (func, requester) {
  6215. if (requester === void 0) { requester = window; }
  6216. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  6217. /*if(requester.isPresenting) {
  6218. return;
  6219. } else*/ if (requester.requestAnimationFrame)
  6220. requester.requestAnimationFrame(func);
  6221. else if (requester.msRequestAnimationFrame)
  6222. requester.msRequestAnimationFrame(func);
  6223. else if (requester.webkitRequestAnimationFrame)
  6224. requester.webkitRequestAnimationFrame(func);
  6225. else if (requester.mozRequestAnimationFrame)
  6226. requester.mozRequestAnimationFrame(func);
  6227. else if (requester.oRequestAnimationFrame)
  6228. requester.oRequestAnimationFrame(func);
  6229. else {
  6230. window.setTimeout(func, 16);
  6231. }
  6232. };
  6233. Tools.RequestFullscreen = function (element) {
  6234. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6235. if (!requestFunction)
  6236. return;
  6237. requestFunction.call(element);
  6238. };
  6239. Tools.ExitFullscreen = function () {
  6240. if (document.exitFullscreen) {
  6241. document.exitFullscreen();
  6242. }
  6243. else if (document.mozCancelFullScreen) {
  6244. document.mozCancelFullScreen();
  6245. }
  6246. else if (document.webkitCancelFullScreen) {
  6247. document.webkitCancelFullScreen();
  6248. }
  6249. else if (document.msCancelFullScreen) {
  6250. document.msCancelFullScreen();
  6251. }
  6252. };
  6253. Tools.SetCorsBehavior = function (url, img) {
  6254. if (Tools.CorsBehavior) {
  6255. switch (typeof (Tools.CorsBehavior)) {
  6256. case "function":
  6257. var result = Tools.CorsBehavior(url);
  6258. if (result) {
  6259. img.crossOrigin = result;
  6260. }
  6261. break;
  6262. case "string":
  6263. default:
  6264. img.crossOrigin = Tools.CorsBehavior;
  6265. break;
  6266. }
  6267. }
  6268. };
  6269. // External files
  6270. Tools.CleanUrl = function (url) {
  6271. url = url.replace(/#/mg, "%23");
  6272. return url;
  6273. };
  6274. Tools.LoadImage = function (url, onload, onerror, database) {
  6275. if (url instanceof ArrayBuffer) {
  6276. url = Tools.EncodeArrayBufferTobase64(url);
  6277. }
  6278. url = Tools.CleanUrl(url);
  6279. var img = new Image();
  6280. if (url.substr(0, 5) !== "data:") {
  6281. Tools.SetCorsBehavior(url, img);
  6282. }
  6283. img.onload = function () {
  6284. onload(img);
  6285. };
  6286. img.onerror = function (err) {
  6287. Tools.Error("Error while trying to load image: " + url);
  6288. if (Tools.UseFallbackTexture) {
  6289. img.src = Tools.fallbackTexture;
  6290. onload(img);
  6291. }
  6292. else {
  6293. onerror();
  6294. }
  6295. };
  6296. var noIndexedDB = function () {
  6297. img.src = url;
  6298. };
  6299. var loadFromIndexedDB = function () {
  6300. database.loadImageFromDB(url, img);
  6301. };
  6302. //ANY database to do!
  6303. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6304. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6305. }
  6306. else {
  6307. if (url.indexOf("file:") === -1) {
  6308. noIndexedDB();
  6309. }
  6310. else {
  6311. var textureName = url.substring(5).toLowerCase();
  6312. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  6313. try {
  6314. var blobURL;
  6315. try {
  6316. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  6317. }
  6318. catch (ex) {
  6319. // Chrome doesn't support oneTimeOnly parameter
  6320. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  6321. }
  6322. img.src = blobURL;
  6323. }
  6324. catch (e) {
  6325. img.src = null;
  6326. }
  6327. }
  6328. else {
  6329. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6330. img.src = Tools.fallbackTexture;
  6331. }
  6332. }
  6333. }
  6334. return img;
  6335. };
  6336. //ANY
  6337. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6338. url = Tools.CleanUrl(url);
  6339. var noIndexedDB = function () {
  6340. var request = new XMLHttpRequest();
  6341. var loadUrl = Tools.BaseUrl + url;
  6342. request.open('GET', loadUrl, true);
  6343. if (useArrayBuffer) {
  6344. request.responseType = "arraybuffer";
  6345. }
  6346. request.onprogress = progressCallBack;
  6347. request.onreadystatechange = function () {
  6348. if (request.readyState === 4) {
  6349. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6350. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  6351. callback(!useArrayBuffer ? request.responseText : request.response);
  6352. }
  6353. else {
  6354. if (onError) {
  6355. onError();
  6356. }
  6357. else {
  6358. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6359. }
  6360. }
  6361. }
  6362. };
  6363. request.send(null);
  6364. };
  6365. var loadFromIndexedDB = function () {
  6366. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6367. };
  6368. if (url.indexOf("file:") !== -1) {
  6369. var fileName = url.substring(5).toLowerCase();
  6370. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6371. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6372. }
  6373. else {
  6374. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  6375. }
  6376. }
  6377. else {
  6378. // Caching all files
  6379. if (database && database.enableSceneOffline) {
  6380. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6381. }
  6382. else {
  6383. noIndexedDB();
  6384. }
  6385. }
  6386. };
  6387. /**
  6388. * Load a script (identified by an url). When the url returns, the
  6389. * content of this file is added into a new script element, attached to the DOM (body element)
  6390. */
  6391. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6392. var head = document.getElementsByTagName('head')[0];
  6393. var script = document.createElement('script');
  6394. script.type = 'text/javascript';
  6395. script.src = scriptUrl;
  6396. var self = this;
  6397. script.onload = function () {
  6398. if (onSuccess) {
  6399. onSuccess();
  6400. }
  6401. };
  6402. script.onerror = function () {
  6403. if (onError) {
  6404. onError();
  6405. }
  6406. };
  6407. head.appendChild(script);
  6408. };
  6409. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6410. var reader = new FileReader();
  6411. reader.onload = function (e) {
  6412. //target doesn't have result from ts 1.3
  6413. callback(e.target['result']);
  6414. };
  6415. reader.onprogress = progressCallback;
  6416. reader.readAsDataURL(fileToLoad);
  6417. };
  6418. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6419. var reader = new FileReader();
  6420. reader.onerror = function (e) {
  6421. Tools.Log("Error while reading file: " + fileToLoad.name);
  6422. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6423. };
  6424. reader.onload = function (e) {
  6425. //target doesn't have result from ts 1.3
  6426. callback(e.target['result']);
  6427. };
  6428. reader.onprogress = progressCallBack;
  6429. if (!useArrayBuffer) {
  6430. // Asynchronous read
  6431. reader.readAsText(fileToLoad);
  6432. }
  6433. else {
  6434. reader.readAsArrayBuffer(fileToLoad);
  6435. }
  6436. };
  6437. //returns a downloadable url to a file content.
  6438. Tools.FileAsURL = function (content) {
  6439. var fileBlob = new Blob([content]);
  6440. var url = window.URL || window.webkitURL;
  6441. var link = url.createObjectURL(fileBlob);
  6442. return link;
  6443. };
  6444. // Misc.
  6445. Tools.Format = function (value, decimals) {
  6446. if (decimals === void 0) { decimals = 2; }
  6447. return value.toFixed(decimals);
  6448. };
  6449. Tools.CheckExtends = function (v, min, max) {
  6450. if (v.x < min.x)
  6451. min.x = v.x;
  6452. if (v.y < min.y)
  6453. min.y = v.y;
  6454. if (v.z < min.z)
  6455. min.z = v.z;
  6456. if (v.x > max.x)
  6457. max.x = v.x;
  6458. if (v.y > max.y)
  6459. max.y = v.y;
  6460. if (v.z > max.z)
  6461. max.z = v.z;
  6462. };
  6463. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6464. for (var prop in source) {
  6465. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6466. continue;
  6467. }
  6468. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6469. continue;
  6470. }
  6471. var sourceValue = source[prop];
  6472. var typeOfSourceValue = typeof sourceValue;
  6473. if (typeOfSourceValue === "function") {
  6474. continue;
  6475. }
  6476. if (typeOfSourceValue === "object") {
  6477. if (sourceValue instanceof Array) {
  6478. destination[prop] = [];
  6479. if (sourceValue.length > 0) {
  6480. if (typeof sourceValue[0] == "object") {
  6481. for (var index = 0; index < sourceValue.length; index++) {
  6482. var clonedValue = cloneValue(sourceValue[index], destination);
  6483. if (destination[prop].indexOf(clonedValue) === -1) {
  6484. destination[prop].push(clonedValue);
  6485. }
  6486. }
  6487. }
  6488. else {
  6489. destination[prop] = sourceValue.slice(0);
  6490. }
  6491. }
  6492. }
  6493. else {
  6494. destination[prop] = cloneValue(sourceValue, destination);
  6495. }
  6496. }
  6497. else {
  6498. destination[prop] = sourceValue;
  6499. }
  6500. }
  6501. };
  6502. Tools.IsEmpty = function (obj) {
  6503. for (var i in obj) {
  6504. return false;
  6505. }
  6506. return true;
  6507. };
  6508. Tools.RegisterTopRootEvents = function (events) {
  6509. for (var index = 0; index < events.length; index++) {
  6510. var event = events[index];
  6511. window.addEventListener(event.name, event.handler, false);
  6512. try {
  6513. if (window.parent) {
  6514. window.parent.addEventListener(event.name, event.handler, false);
  6515. }
  6516. }
  6517. catch (e) {
  6518. }
  6519. }
  6520. };
  6521. Tools.UnregisterTopRootEvents = function (events) {
  6522. for (var index = 0; index < events.length; index++) {
  6523. var event = events[index];
  6524. window.removeEventListener(event.name, event.handler);
  6525. try {
  6526. if (window.parent) {
  6527. window.parent.removeEventListener(event.name, event.handler);
  6528. }
  6529. }
  6530. catch (e) {
  6531. }
  6532. }
  6533. };
  6534. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6535. if (mimeType === void 0) { mimeType = "image/png"; }
  6536. // Read the contents of the framebuffer
  6537. var numberOfChannelsByLine = width * 4;
  6538. var halfHeight = height / 2;
  6539. //Reading datas from WebGL
  6540. var data = engine.readPixels(0, 0, width, height);
  6541. //To flip image on Y axis.
  6542. for (var i = 0; i < halfHeight; i++) {
  6543. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6544. var currentCell = j + i * numberOfChannelsByLine;
  6545. var targetLine = height - i - 1;
  6546. var targetCell = j + targetLine * numberOfChannelsByLine;
  6547. var temp = data[currentCell];
  6548. data[currentCell] = data[targetCell];
  6549. data[targetCell] = temp;
  6550. }
  6551. }
  6552. // Create a 2D canvas to store the result
  6553. if (!screenshotCanvas) {
  6554. screenshotCanvas = document.createElement('canvas');
  6555. }
  6556. screenshotCanvas.width = width;
  6557. screenshotCanvas.height = height;
  6558. var context = screenshotCanvas.getContext('2d');
  6559. // Copy the pixels to a 2D canvas
  6560. var imageData = context.createImageData(width, height);
  6561. var castData = (imageData.data);
  6562. castData.set(data);
  6563. context.putImageData(imageData, 0, 0);
  6564. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6565. };
  6566. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6567. if (mimeType === void 0) { mimeType = "image/png"; }
  6568. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6569. if (successCallback) {
  6570. successCallback(base64Image);
  6571. }
  6572. else {
  6573. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6574. if (("download" in document.createElement("a"))) {
  6575. var a = window.document.createElement("a");
  6576. a.href = base64Image;
  6577. var date = new Date();
  6578. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6579. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6580. window.document.body.appendChild(a);
  6581. a.addEventListener("click", function () {
  6582. a.parentElement.removeChild(a);
  6583. });
  6584. a.click();
  6585. }
  6586. else {
  6587. var newWindow = window.open("");
  6588. var img = newWindow.document.createElement("img");
  6589. img.src = base64Image;
  6590. newWindow.document.body.appendChild(img);
  6591. }
  6592. }
  6593. };
  6594. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6595. if (mimeType === void 0) { mimeType = "image/png"; }
  6596. var width;
  6597. var height;
  6598. // If a precision value is specified
  6599. if (size.precision) {
  6600. width = Math.round(engine.getRenderWidth() * size.precision);
  6601. height = Math.round(width / engine.getAspectRatio(camera));
  6602. }
  6603. else if (size.width && size.height) {
  6604. width = size.width;
  6605. height = size.height;
  6606. }
  6607. else if (size.width && !size.height) {
  6608. width = size.width;
  6609. height = Math.round(width / engine.getAspectRatio(camera));
  6610. }
  6611. else if (size.height && !size.width) {
  6612. height = size.height;
  6613. width = Math.round(height * engine.getAspectRatio(camera));
  6614. }
  6615. else if (!isNaN(size)) {
  6616. height = size;
  6617. width = size;
  6618. }
  6619. else {
  6620. Tools.Error("Invalid 'size' parameter !");
  6621. return;
  6622. }
  6623. if (!screenshotCanvas) {
  6624. screenshotCanvas = document.createElement('canvas');
  6625. }
  6626. screenshotCanvas.width = width;
  6627. screenshotCanvas.height = height;
  6628. var renderContext = screenshotCanvas.getContext("2d");
  6629. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6630. var newWidth = width;
  6631. var newHeight = newWidth / ratio;
  6632. if (newHeight > height) {
  6633. newHeight = height;
  6634. newWidth = newHeight * ratio;
  6635. }
  6636. var offsetX = Math.max(0, width - newWidth) / 2;
  6637. var offsetY = Math.max(0, height - newHeight) / 2;
  6638. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6639. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6640. };
  6641. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6642. if (mimeType === void 0) { mimeType = "image/png"; }
  6643. if (samples === void 0) { samples = 1; }
  6644. var width;
  6645. var height;
  6646. //If a precision value is specified
  6647. if (size.precision) {
  6648. width = Math.round(engine.getRenderWidth() * size.precision);
  6649. height = Math.round(width / engine.getAspectRatio(camera));
  6650. size = { width: width, height: height };
  6651. }
  6652. else if (size.width && size.height) {
  6653. width = size.width;
  6654. height = size.height;
  6655. }
  6656. else if (size.width && !size.height) {
  6657. width = size.width;
  6658. height = Math.round(width / engine.getAspectRatio(camera));
  6659. size = { width: width, height: height };
  6660. }
  6661. else if (size.height && !size.width) {
  6662. height = size.height;
  6663. width = Math.round(height * engine.getAspectRatio(camera));
  6664. size = { width: width, height: height };
  6665. }
  6666. else if (!isNaN(size)) {
  6667. height = size;
  6668. width = size;
  6669. }
  6670. else {
  6671. Tools.Error("Invalid 'size' parameter !");
  6672. return;
  6673. }
  6674. var scene = camera.getScene();
  6675. var previousCamera = null;
  6676. if (scene.activeCamera !== camera) {
  6677. previousCamera = scene.activeCamera;
  6678. scene.activeCamera = camera;
  6679. }
  6680. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6681. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6682. texture.renderList = scene.meshes;
  6683. texture.samples = samples;
  6684. texture.onAfterRenderObservable.add(function () {
  6685. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6686. });
  6687. scene.incrementRenderId();
  6688. scene.resetCachedMaterial();
  6689. texture.render(true);
  6690. texture.dispose();
  6691. if (previousCamera) {
  6692. scene.activeCamera = previousCamera;
  6693. }
  6694. camera.getProjectionMatrix(true); // Force cache refresh;
  6695. };
  6696. // XHR response validator for local file scenario
  6697. Tools.ValidateXHRData = function (xhr, dataType) {
  6698. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6699. if (dataType === void 0) { dataType = 7; }
  6700. try {
  6701. if (dataType & 1) {
  6702. if (xhr.responseText && xhr.responseText.length > 0) {
  6703. return true;
  6704. }
  6705. else if (dataType === 1) {
  6706. return false;
  6707. }
  6708. }
  6709. if (dataType & 2) {
  6710. // Check header width and height since there is no "TGA" magic number
  6711. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6712. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6713. return true;
  6714. }
  6715. else if (dataType === 2) {
  6716. return false;
  6717. }
  6718. }
  6719. if (dataType & 4) {
  6720. // Check for the "DDS" magic number
  6721. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6722. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6723. return true;
  6724. }
  6725. else {
  6726. return false;
  6727. }
  6728. }
  6729. }
  6730. catch (e) {
  6731. }
  6732. return false;
  6733. };
  6734. /**
  6735. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6736. * Be aware Math.random() could cause collisions, but:
  6737. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  6738. */
  6739. Tools.RandomId = function () {
  6740. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6741. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6742. return v.toString(16);
  6743. });
  6744. };
  6745. Object.defineProperty(Tools, "NoneLogLevel", {
  6746. get: function () {
  6747. return Tools._NoneLogLevel;
  6748. },
  6749. enumerable: true,
  6750. configurable: true
  6751. });
  6752. Object.defineProperty(Tools, "MessageLogLevel", {
  6753. get: function () {
  6754. return Tools._MessageLogLevel;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(Tools, "WarningLogLevel", {
  6760. get: function () {
  6761. return Tools._WarningLogLevel;
  6762. },
  6763. enumerable: true,
  6764. configurable: true
  6765. });
  6766. Object.defineProperty(Tools, "ErrorLogLevel", {
  6767. get: function () {
  6768. return Tools._ErrorLogLevel;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(Tools, "AllLogLevel", {
  6774. get: function () {
  6775. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6776. },
  6777. enumerable: true,
  6778. configurable: true
  6779. });
  6780. Tools._AddLogEntry = function (entry) {
  6781. Tools._LogCache = entry + Tools._LogCache;
  6782. if (Tools.OnNewCacheEntry) {
  6783. Tools.OnNewCacheEntry(entry);
  6784. }
  6785. };
  6786. Tools._FormatMessage = function (message) {
  6787. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6788. var date = new Date();
  6789. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6790. };
  6791. Tools._LogDisabled = function (message) {
  6792. // nothing to do
  6793. };
  6794. Tools._LogEnabled = function (message) {
  6795. var formattedMessage = Tools._FormatMessage(message);
  6796. console.log("BJS - " + formattedMessage);
  6797. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6798. Tools._AddLogEntry(entry);
  6799. };
  6800. Tools._WarnDisabled = function (message) {
  6801. // nothing to do
  6802. };
  6803. Tools._WarnEnabled = function (message) {
  6804. var formattedMessage = Tools._FormatMessage(message);
  6805. console.warn("BJS - " + formattedMessage);
  6806. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6807. Tools._AddLogEntry(entry);
  6808. };
  6809. Tools._ErrorDisabled = function (message) {
  6810. // nothing to do
  6811. };
  6812. Tools._ErrorEnabled = function (message) {
  6813. Tools.errorsCount++;
  6814. var formattedMessage = Tools._FormatMessage(message);
  6815. console.error("BJS - " + formattedMessage);
  6816. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6817. Tools._AddLogEntry(entry);
  6818. };
  6819. Object.defineProperty(Tools, "LogCache", {
  6820. get: function () {
  6821. return Tools._LogCache;
  6822. },
  6823. enumerable: true,
  6824. configurable: true
  6825. });
  6826. Tools.ClearLogCache = function () {
  6827. Tools._LogCache = "";
  6828. Tools.errorsCount = 0;
  6829. };
  6830. Object.defineProperty(Tools, "LogLevels", {
  6831. set: function (level) {
  6832. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6833. Tools.Log = Tools._LogEnabled;
  6834. }
  6835. else {
  6836. Tools.Log = Tools._LogDisabled;
  6837. }
  6838. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6839. Tools.Warn = Tools._WarnEnabled;
  6840. }
  6841. else {
  6842. Tools.Warn = Tools._WarnDisabled;
  6843. }
  6844. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6845. Tools.Error = Tools._ErrorEnabled;
  6846. }
  6847. else {
  6848. Tools.Error = Tools._ErrorDisabled;
  6849. }
  6850. },
  6851. enumerable: true,
  6852. configurable: true
  6853. });
  6854. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6855. get: function () {
  6856. return Tools._PerformanceNoneLogLevel;
  6857. },
  6858. enumerable: true,
  6859. configurable: true
  6860. });
  6861. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6862. get: function () {
  6863. return Tools._PerformanceUserMarkLogLevel;
  6864. },
  6865. enumerable: true,
  6866. configurable: true
  6867. });
  6868. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6869. get: function () {
  6870. return Tools._PerformanceConsoleLogLevel;
  6871. },
  6872. enumerable: true,
  6873. configurable: true
  6874. });
  6875. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6876. set: function (level) {
  6877. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6878. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6879. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6880. return;
  6881. }
  6882. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6883. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6884. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6885. return;
  6886. }
  6887. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6888. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6889. },
  6890. enumerable: true,
  6891. configurable: true
  6892. });
  6893. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6894. };
  6895. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6896. };
  6897. Tools._StartUserMark = function (counterName, condition) {
  6898. if (condition === void 0) { condition = true; }
  6899. if (!condition || !Tools._performance.mark) {
  6900. return;
  6901. }
  6902. Tools._performance.mark(counterName + "-Begin");
  6903. };
  6904. Tools._EndUserMark = function (counterName, condition) {
  6905. if (condition === void 0) { condition = true; }
  6906. if (!condition || !Tools._performance.mark) {
  6907. return;
  6908. }
  6909. Tools._performance.mark(counterName + "-End");
  6910. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6911. };
  6912. Tools._StartPerformanceConsole = function (counterName, condition) {
  6913. if (condition === void 0) { condition = true; }
  6914. if (!condition) {
  6915. return;
  6916. }
  6917. Tools._StartUserMark(counterName, condition);
  6918. if (console.time) {
  6919. console.time(counterName);
  6920. }
  6921. };
  6922. Tools._EndPerformanceConsole = function (counterName, condition) {
  6923. if (condition === void 0) { condition = true; }
  6924. if (!condition) {
  6925. return;
  6926. }
  6927. Tools._EndUserMark(counterName, condition);
  6928. if (console.time) {
  6929. console.timeEnd(counterName);
  6930. }
  6931. };
  6932. Object.defineProperty(Tools, "Now", {
  6933. get: function () {
  6934. if (window.performance && window.performance.now) {
  6935. return window.performance.now();
  6936. }
  6937. return new Date().getTime();
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. /**
  6943. * This method will return the name of the class used to create the instance of the given object.
  6944. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6945. * @param object the object to get the class name from
  6946. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6947. */
  6948. Tools.getClassName = function (object, isType) {
  6949. if (isType === void 0) { isType = false; }
  6950. var name = null;
  6951. if (!isType && object.getClassName) {
  6952. name = object.getClassName();
  6953. }
  6954. else {
  6955. if (object instanceof Object) {
  6956. var classObj = isType ? object : Object.getPrototypeOf(object);
  6957. name = classObj.constructor["__bjsclassName__"];
  6958. }
  6959. if (!name) {
  6960. name = typeof object;
  6961. }
  6962. }
  6963. return name;
  6964. };
  6965. Tools.first = function (array, predicate) {
  6966. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6967. var el = array_1[_i];
  6968. if (predicate(el)) {
  6969. return el;
  6970. }
  6971. }
  6972. };
  6973. /**
  6974. * This method will return the name of the full name of the class, including its owning module (if any).
  6975. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6976. * @param object the object to get the class name from
  6977. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6978. */
  6979. Tools.getFullClassName = function (object, isType) {
  6980. if (isType === void 0) { isType = false; }
  6981. var className = null;
  6982. var moduleName = null;
  6983. if (!isType && object.getClassName) {
  6984. className = object.getClassName();
  6985. }
  6986. else {
  6987. if (object instanceof Object) {
  6988. var classObj = isType ? object : Object.getPrototypeOf(object);
  6989. className = classObj.constructor["__bjsclassName__"];
  6990. moduleName = classObj.constructor["__bjsmoduleName__"];
  6991. }
  6992. if (!className) {
  6993. className = typeof object;
  6994. }
  6995. }
  6996. if (!className) {
  6997. return null;
  6998. }
  6999. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7000. };
  7001. /**
  7002. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  7003. * @param array
  7004. */
  7005. Tools.arrayOrStringFeeder = function (array) {
  7006. return function (index) {
  7007. if (index >= array.length) {
  7008. return null;
  7009. }
  7010. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7011. if (val && val.getHashCode) {
  7012. val = val.getHashCode();
  7013. }
  7014. if (typeof val === "string") {
  7015. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7016. }
  7017. return val;
  7018. };
  7019. };
  7020. /**
  7021. * Compute the hashCode of a stream of number
  7022. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7023. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7024. * @return the hash code computed
  7025. */
  7026. Tools.hashCodeFromStream = function (feeder) {
  7027. // Based from here: http://stackoverflow.com/a/7616484/802124
  7028. var hash = 0;
  7029. var index = 0;
  7030. var chr = feeder(index++);
  7031. while (chr != null) {
  7032. hash = ((hash << 5) - hash) + chr;
  7033. hash |= 0; // Convert to 32bit integer
  7034. chr = feeder(index++);
  7035. }
  7036. return hash;
  7037. };
  7038. return Tools;
  7039. }());
  7040. Tools.BaseUrl = "";
  7041. Tools.CorsBehavior = "anonymous";
  7042. Tools.UseFallbackTexture = true;
  7043. // Used in case of a texture loading problem
  7044. Tools.fallbackTexture = "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";
  7045. // Logs
  7046. Tools._NoneLogLevel = 0;
  7047. Tools._MessageLogLevel = 1;
  7048. Tools._WarningLogLevel = 2;
  7049. Tools._ErrorLogLevel = 4;
  7050. Tools._LogCache = "";
  7051. Tools.errorsCount = 0;
  7052. Tools.Log = Tools._LogEnabled;
  7053. Tools.Warn = Tools._WarnEnabled;
  7054. Tools.Error = Tools._ErrorEnabled;
  7055. // Performances
  7056. Tools._PerformanceNoneLogLevel = 0;
  7057. Tools._PerformanceUserMarkLogLevel = 1;
  7058. Tools._PerformanceConsoleLogLevel = 2;
  7059. Tools._performance = window.performance;
  7060. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7061. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7062. BABYLON.Tools = Tools;
  7063. /**
  7064. * This class is used to track a performance counter which is number based.
  7065. * The user has access to many properties which give statistics of different nature
  7066. *
  7067. * The implementer can track two kinds of Performance Counter: time and count
  7068. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  7069. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  7070. */
  7071. var PerfCounter = (function () {
  7072. function PerfCounter() {
  7073. this._startMonitoringTime = 0;
  7074. this._min = 0;
  7075. this._max = 0;
  7076. this._average = 0;
  7077. this._lastSecAverage = 0;
  7078. this._current = 0;
  7079. this._totalValueCount = 0;
  7080. this._totalAccumulated = 0;
  7081. this._lastSecAccumulated = 0;
  7082. this._lastSecTime = 0;
  7083. this._lastSecValueCount = 0;
  7084. }
  7085. Object.defineProperty(PerfCounter.prototype, "min", {
  7086. /**
  7087. * Returns the smallest value ever
  7088. */
  7089. get: function () {
  7090. return this._min;
  7091. },
  7092. enumerable: true,
  7093. configurable: true
  7094. });
  7095. Object.defineProperty(PerfCounter.prototype, "max", {
  7096. /**
  7097. * Returns the biggest value ever
  7098. */
  7099. get: function () {
  7100. return this._max;
  7101. },
  7102. enumerable: true,
  7103. configurable: true
  7104. });
  7105. Object.defineProperty(PerfCounter.prototype, "average", {
  7106. /**
  7107. * Returns the average value since the performance counter is running
  7108. */
  7109. get: function () {
  7110. return this._average;
  7111. },
  7112. enumerable: true,
  7113. configurable: true
  7114. });
  7115. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7116. /**
  7117. * Returns the average value of the last second the counter was monitored
  7118. */
  7119. get: function () {
  7120. return this._lastSecAverage;
  7121. },
  7122. enumerable: true,
  7123. configurable: true
  7124. });
  7125. Object.defineProperty(PerfCounter.prototype, "current", {
  7126. /**
  7127. * Returns the current value
  7128. */
  7129. get: function () {
  7130. return this._current;
  7131. },
  7132. enumerable: true,
  7133. configurable: true
  7134. });
  7135. Object.defineProperty(PerfCounter.prototype, "total", {
  7136. get: function () {
  7137. return this._totalAccumulated;
  7138. },
  7139. enumerable: true,
  7140. configurable: true
  7141. });
  7142. /**
  7143. * Call this method to start monitoring a new frame.
  7144. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  7145. */
  7146. PerfCounter.prototype.fetchNewFrame = function () {
  7147. this._totalValueCount++;
  7148. this._current = 0;
  7149. this._lastSecValueCount++;
  7150. };
  7151. /**
  7152. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7153. * @param newCount the count value to add to the monitored count
  7154. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  7155. */
  7156. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7157. if (!PerfCounter.Enabled) {
  7158. return;
  7159. }
  7160. this._current += newCount;
  7161. if (fetchResult) {
  7162. this._fetchResult();
  7163. }
  7164. };
  7165. /**
  7166. * Start monitoring this performance counter
  7167. */
  7168. PerfCounter.prototype.beginMonitoring = function () {
  7169. if (!PerfCounter.Enabled) {
  7170. return;
  7171. }
  7172. this._startMonitoringTime = Tools.Now;
  7173. };
  7174. /**
  7175. * Compute the time lapsed since the previous beginMonitoring() call.
  7176. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  7177. */
  7178. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7179. if (newFrame === void 0) { newFrame = true; }
  7180. if (!PerfCounter.Enabled) {
  7181. return;
  7182. }
  7183. if (newFrame) {
  7184. this.fetchNewFrame();
  7185. }
  7186. var currentTime = Tools.Now;
  7187. this._current = currentTime - this._startMonitoringTime;
  7188. if (newFrame) {
  7189. this._fetchResult();
  7190. }
  7191. };
  7192. PerfCounter.prototype._fetchResult = function () {
  7193. this._totalAccumulated += this._current;
  7194. this._lastSecAccumulated += this._current;
  7195. // Min/Max update
  7196. this._min = Math.min(this._min, this._current);
  7197. this._max = Math.max(this._max, this._current);
  7198. this._average = this._totalAccumulated / this._totalValueCount;
  7199. // Reset last sec?
  7200. var now = Tools.Now;
  7201. if ((now - this._lastSecTime) > 1000) {
  7202. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7203. this._lastSecTime = now;
  7204. this._lastSecAccumulated = 0;
  7205. this._lastSecValueCount = 0;
  7206. }
  7207. };
  7208. return PerfCounter;
  7209. }());
  7210. PerfCounter.Enabled = true;
  7211. BABYLON.PerfCounter = PerfCounter;
  7212. /**
  7213. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7214. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7215. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7216. * @param name The name of the class, case should be preserved
  7217. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7218. */
  7219. function className(name, module) {
  7220. return function (target) {
  7221. target["__bjsclassName__"] = name;
  7222. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7223. };
  7224. }
  7225. BABYLON.className = className;
  7226. /**
  7227. * An implementation of a loop for asynchronous functions.
  7228. */
  7229. var AsyncLoop = (function () {
  7230. /**
  7231. * Constroctor.
  7232. * @param iterations the number of iterations.
  7233. * @param _fn the function to run each iteration
  7234. * @param _successCallback the callback that will be called upon succesful execution
  7235. * @param offset starting offset.
  7236. */
  7237. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7238. if (offset === void 0) { offset = 0; }
  7239. this.iterations = iterations;
  7240. this._fn = _fn;
  7241. this._successCallback = _successCallback;
  7242. this.index = offset - 1;
  7243. this._done = false;
  7244. }
  7245. /**
  7246. * Execute the next iteration. Must be called after the last iteration was finished.
  7247. */
  7248. AsyncLoop.prototype.executeNext = function () {
  7249. if (!this._done) {
  7250. if (this.index + 1 < this.iterations) {
  7251. ++this.index;
  7252. this._fn(this);
  7253. }
  7254. else {
  7255. this.breakLoop();
  7256. }
  7257. }
  7258. };
  7259. /**
  7260. * Break the loop and run the success callback.
  7261. */
  7262. AsyncLoop.prototype.breakLoop = function () {
  7263. this._done = true;
  7264. this._successCallback();
  7265. };
  7266. /**
  7267. * Helper function
  7268. */
  7269. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7270. if (offset === void 0) { offset = 0; }
  7271. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7272. loop.executeNext();
  7273. return loop;
  7274. };
  7275. /**
  7276. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7277. * @param iterations total number of iterations
  7278. * @param syncedIterations number of synchronous iterations in each async iteration.
  7279. * @param fn the function to call each iteration.
  7280. * @param callback a success call back that will be called when iterating stops.
  7281. * @param breakFunction a break condition (optional)
  7282. * @param timeout timeout settings for the setTimeout function. default - 0.
  7283. * @constructor
  7284. */
  7285. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7286. if (timeout === void 0) { timeout = 0; }
  7287. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7288. if (breakFunction && breakFunction())
  7289. loop.breakLoop();
  7290. else {
  7291. setTimeout(function () {
  7292. for (var i = 0; i < syncedIterations; ++i) {
  7293. var iteration = (loop.index * syncedIterations) + i;
  7294. if (iteration >= iterations)
  7295. break;
  7296. fn(iteration);
  7297. if (breakFunction && breakFunction()) {
  7298. loop.breakLoop();
  7299. break;
  7300. }
  7301. }
  7302. loop.executeNext();
  7303. }, timeout);
  7304. }
  7305. }, callback);
  7306. };
  7307. return AsyncLoop;
  7308. }());
  7309. BABYLON.AsyncLoop = AsyncLoop;
  7310. })(BABYLON || (BABYLON = {}));
  7311. //# sourceMappingURL=babylon.tools.js.map
  7312. var BABYLON;
  7313. (function (BABYLON) {
  7314. var Internals;
  7315. (function (Internals) {
  7316. var _AlphaState = (function () {
  7317. /**
  7318. * Initializes the state.
  7319. */
  7320. function _AlphaState() {
  7321. this._isAlphaBlendDirty = false;
  7322. this._isBlendFunctionParametersDirty = false;
  7323. this._alphaBlend = false;
  7324. this._blendFunctionParameters = new Array(4);
  7325. this.reset();
  7326. }
  7327. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7328. get: function () {
  7329. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7330. },
  7331. enumerable: true,
  7332. configurable: true
  7333. });
  7334. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7335. get: function () {
  7336. return this._alphaBlend;
  7337. },
  7338. set: function (value) {
  7339. if (this._alphaBlend === value) {
  7340. return;
  7341. }
  7342. this._alphaBlend = value;
  7343. this._isAlphaBlendDirty = true;
  7344. },
  7345. enumerable: true,
  7346. configurable: true
  7347. });
  7348. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7349. if (this._blendFunctionParameters[0] === value0 &&
  7350. this._blendFunctionParameters[1] === value1 &&
  7351. this._blendFunctionParameters[2] === value2 &&
  7352. this._blendFunctionParameters[3] === value3) {
  7353. return;
  7354. }
  7355. this._blendFunctionParameters[0] = value0;
  7356. this._blendFunctionParameters[1] = value1;
  7357. this._blendFunctionParameters[2] = value2;
  7358. this._blendFunctionParameters[3] = value3;
  7359. this._isBlendFunctionParametersDirty = true;
  7360. };
  7361. _AlphaState.prototype.reset = function () {
  7362. this._alphaBlend = false;
  7363. this._blendFunctionParameters[0] = null;
  7364. this._blendFunctionParameters[1] = null;
  7365. this._blendFunctionParameters[2] = null;
  7366. this._blendFunctionParameters[3] = null;
  7367. this._isAlphaBlendDirty = true;
  7368. this._isBlendFunctionParametersDirty = false;
  7369. };
  7370. _AlphaState.prototype.apply = function (gl) {
  7371. if (!this.isDirty) {
  7372. return;
  7373. }
  7374. // Alpha blend
  7375. if (this._isAlphaBlendDirty) {
  7376. if (this._alphaBlend) {
  7377. gl.enable(gl.BLEND);
  7378. }
  7379. else {
  7380. gl.disable(gl.BLEND);
  7381. }
  7382. this._isAlphaBlendDirty = false;
  7383. }
  7384. // Alpha function
  7385. if (this._isBlendFunctionParametersDirty) {
  7386. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7387. this._isBlendFunctionParametersDirty = false;
  7388. }
  7389. };
  7390. return _AlphaState;
  7391. }());
  7392. Internals._AlphaState = _AlphaState;
  7393. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7394. })(BABYLON || (BABYLON = {}));
  7395. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7396. var BABYLON;
  7397. (function (BABYLON) {
  7398. var Internals;
  7399. (function (Internals) {
  7400. var _DepthCullingState = (function () {
  7401. /**
  7402. * Initializes the state.
  7403. */
  7404. function _DepthCullingState() {
  7405. this._isDepthTestDirty = false;
  7406. this._isDepthMaskDirty = false;
  7407. this._isDepthFuncDirty = false;
  7408. this._isCullFaceDirty = false;
  7409. this._isCullDirty = false;
  7410. this._isZOffsetDirty = false;
  7411. this.reset();
  7412. }
  7413. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7414. get: function () {
  7415. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7416. },
  7417. enumerable: true,
  7418. configurable: true
  7419. });
  7420. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7421. get: function () {
  7422. return this._zOffset;
  7423. },
  7424. set: function (value) {
  7425. if (this._zOffset === value) {
  7426. return;
  7427. }
  7428. this._zOffset = value;
  7429. this._isZOffsetDirty = true;
  7430. },
  7431. enumerable: true,
  7432. configurable: true
  7433. });
  7434. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7435. get: function () {
  7436. return this._cullFace;
  7437. },
  7438. set: function (value) {
  7439. if (this._cullFace === value) {
  7440. return;
  7441. }
  7442. this._cullFace = value;
  7443. this._isCullFaceDirty = true;
  7444. },
  7445. enumerable: true,
  7446. configurable: true
  7447. });
  7448. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7449. get: function () {
  7450. return this._cull;
  7451. },
  7452. set: function (value) {
  7453. if (this._cull === value) {
  7454. return;
  7455. }
  7456. this._cull = value;
  7457. this._isCullDirty = true;
  7458. },
  7459. enumerable: true,
  7460. configurable: true
  7461. });
  7462. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7463. get: function () {
  7464. return this._depthFunc;
  7465. },
  7466. set: function (value) {
  7467. if (this._depthFunc === value) {
  7468. return;
  7469. }
  7470. this._depthFunc = value;
  7471. this._isDepthFuncDirty = true;
  7472. },
  7473. enumerable: true,
  7474. configurable: true
  7475. });
  7476. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7477. get: function () {
  7478. return this._depthMask;
  7479. },
  7480. set: function (value) {
  7481. if (this._depthMask === value) {
  7482. return;
  7483. }
  7484. this._depthMask = value;
  7485. this._isDepthMaskDirty = true;
  7486. },
  7487. enumerable: true,
  7488. configurable: true
  7489. });
  7490. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7491. get: function () {
  7492. return this._depthTest;
  7493. },
  7494. set: function (value) {
  7495. if (this._depthTest === value) {
  7496. return;
  7497. }
  7498. this._depthTest = value;
  7499. this._isDepthTestDirty = true;
  7500. },
  7501. enumerable: true,
  7502. configurable: true
  7503. });
  7504. _DepthCullingState.prototype.reset = function () {
  7505. this._depthMask = true;
  7506. this._depthTest = true;
  7507. this._depthFunc = null;
  7508. this._cullFace = null;
  7509. this._cull = null;
  7510. this._zOffset = 0;
  7511. this._isDepthTestDirty = true;
  7512. this._isDepthMaskDirty = true;
  7513. this._isDepthFuncDirty = false;
  7514. this._isCullFaceDirty = false;
  7515. this._isCullDirty = false;
  7516. this._isZOffsetDirty = false;
  7517. };
  7518. _DepthCullingState.prototype.apply = function (gl) {
  7519. if (!this.isDirty) {
  7520. return;
  7521. }
  7522. // Cull
  7523. if (this._isCullDirty) {
  7524. if (this.cull) {
  7525. gl.enable(gl.CULL_FACE);
  7526. }
  7527. else {
  7528. gl.disable(gl.CULL_FACE);
  7529. }
  7530. this._isCullDirty = false;
  7531. }
  7532. // Cull face
  7533. if (this._isCullFaceDirty) {
  7534. gl.cullFace(this.cullFace);
  7535. this._isCullFaceDirty = false;
  7536. }
  7537. // Depth mask
  7538. if (this._isDepthMaskDirty) {
  7539. gl.depthMask(this.depthMask);
  7540. this._isDepthMaskDirty = false;
  7541. }
  7542. // Depth test
  7543. if (this._isDepthTestDirty) {
  7544. if (this.depthTest) {
  7545. gl.enable(gl.DEPTH_TEST);
  7546. }
  7547. else {
  7548. gl.disable(gl.DEPTH_TEST);
  7549. }
  7550. this._isDepthTestDirty = false;
  7551. }
  7552. // Depth func
  7553. if (this._isDepthFuncDirty) {
  7554. gl.depthFunc(this.depthFunc);
  7555. this._isDepthFuncDirty = false;
  7556. }
  7557. // zOffset
  7558. if (this._isZOffsetDirty) {
  7559. if (this.zOffset) {
  7560. gl.enable(gl.POLYGON_OFFSET_FILL);
  7561. gl.polygonOffset(this.zOffset, 0);
  7562. }
  7563. else {
  7564. gl.disable(gl.POLYGON_OFFSET_FILL);
  7565. }
  7566. this._isZOffsetDirty = false;
  7567. }
  7568. };
  7569. return _DepthCullingState;
  7570. }());
  7571. Internals._DepthCullingState = _DepthCullingState;
  7572. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7573. })(BABYLON || (BABYLON = {}));
  7574. //# sourceMappingURL=babylon.depthCullingState.js.map
  7575. var BABYLON;
  7576. (function (BABYLON) {
  7577. var Internals;
  7578. (function (Internals) {
  7579. var _StencilState = (function () {
  7580. function _StencilState() {
  7581. this._isStencilTestDirty = false;
  7582. this._isStencilMaskDirty = false;
  7583. this._isStencilFuncDirty = false;
  7584. this._isStencilOpDirty = false;
  7585. this.reset();
  7586. }
  7587. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7588. get: function () {
  7589. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7595. get: function () {
  7596. return this._stencilFunc;
  7597. },
  7598. set: function (value) {
  7599. if (this._stencilFunc === value) {
  7600. return;
  7601. }
  7602. this._stencilFunc = value;
  7603. this._isStencilFuncDirty = true;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7609. get: function () {
  7610. return this._stencilFuncRef;
  7611. },
  7612. set: function (value) {
  7613. if (this._stencilFuncRef === value) {
  7614. return;
  7615. }
  7616. this._stencilFuncRef = value;
  7617. this._isStencilFuncDirty = true;
  7618. },
  7619. enumerable: true,
  7620. configurable: true
  7621. });
  7622. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7623. get: function () {
  7624. return this._stencilFuncMask;
  7625. },
  7626. set: function (value) {
  7627. if (this._stencilFuncMask === value) {
  7628. return;
  7629. }
  7630. this._stencilFuncMask = value;
  7631. this._isStencilFuncDirty = true;
  7632. },
  7633. enumerable: true,
  7634. configurable: true
  7635. });
  7636. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7637. get: function () {
  7638. return this._stencilOpStencilFail;
  7639. },
  7640. set: function (value) {
  7641. if (this._stencilOpStencilFail === value) {
  7642. return;
  7643. }
  7644. this._stencilOpStencilFail = value;
  7645. this._isStencilOpDirty = true;
  7646. },
  7647. enumerable: true,
  7648. configurable: true
  7649. });
  7650. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7651. get: function () {
  7652. return this._stencilOpDepthFail;
  7653. },
  7654. set: function (value) {
  7655. if (this._stencilOpDepthFail === value) {
  7656. return;
  7657. }
  7658. this._stencilOpDepthFail = value;
  7659. this._isStencilOpDirty = true;
  7660. },
  7661. enumerable: true,
  7662. configurable: true
  7663. });
  7664. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7665. get: function () {
  7666. return this._stencilOpStencilDepthPass;
  7667. },
  7668. set: function (value) {
  7669. if (this._stencilOpStencilDepthPass === value) {
  7670. return;
  7671. }
  7672. this._stencilOpStencilDepthPass = value;
  7673. this._isStencilOpDirty = true;
  7674. },
  7675. enumerable: true,
  7676. configurable: true
  7677. });
  7678. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7679. get: function () {
  7680. return this._stencilMask;
  7681. },
  7682. set: function (value) {
  7683. if (this._stencilMask === value) {
  7684. return;
  7685. }
  7686. this._stencilMask = value;
  7687. this._isStencilMaskDirty = true;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7693. get: function () {
  7694. return this._stencilTest;
  7695. },
  7696. set: function (value) {
  7697. if (this._stencilTest === value) {
  7698. return;
  7699. }
  7700. this._stencilTest = value;
  7701. this._isStencilTestDirty = true;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. _StencilState.prototype.reset = function () {
  7707. this._stencilTest = false;
  7708. this._stencilMask = 0xFF;
  7709. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7710. this._stencilFuncRef = 1;
  7711. this._stencilFuncMask = 0xFF;
  7712. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7713. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7714. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7715. this._isStencilTestDirty = true;
  7716. this._isStencilMaskDirty = true;
  7717. this._isStencilFuncDirty = true;
  7718. this._isStencilOpDirty = true;
  7719. };
  7720. _StencilState.prototype.apply = function (gl) {
  7721. if (!this.isDirty) {
  7722. return;
  7723. }
  7724. // Stencil test
  7725. if (this._isStencilTestDirty) {
  7726. if (this.stencilTest) {
  7727. gl.enable(gl.STENCIL_TEST);
  7728. }
  7729. else {
  7730. gl.disable(gl.STENCIL_TEST);
  7731. }
  7732. this._isStencilTestDirty = false;
  7733. }
  7734. // Stencil mask
  7735. if (this._isStencilMaskDirty) {
  7736. gl.stencilMask(this.stencilMask);
  7737. this._isStencilMaskDirty = false;
  7738. }
  7739. // Stencil func
  7740. if (this._isStencilFuncDirty) {
  7741. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7742. this._isStencilFuncDirty = false;
  7743. }
  7744. // Stencil op
  7745. if (this._isStencilOpDirty) {
  7746. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7747. this._isStencilOpDirty = false;
  7748. }
  7749. };
  7750. return _StencilState;
  7751. }());
  7752. Internals._StencilState = _StencilState;
  7753. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7754. })(BABYLON || (BABYLON = {}));
  7755. //# sourceMappingURL=babylon.stencilState.js.map
  7756. var BABYLON;
  7757. (function (BABYLON) {
  7758. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7759. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7760. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7761. gl.compileShader(shader);
  7762. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7763. throw new Error(gl.getShaderInfoLog(shader));
  7764. }
  7765. return shader;
  7766. };
  7767. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7768. var magFilter = gl.NEAREST;
  7769. var minFilter = gl.NEAREST;
  7770. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7771. magFilter = gl.LINEAR;
  7772. if (generateMipMaps) {
  7773. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7774. }
  7775. else {
  7776. minFilter = gl.LINEAR;
  7777. }
  7778. }
  7779. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7780. magFilter = gl.LINEAR;
  7781. if (generateMipMaps) {
  7782. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7783. }
  7784. else {
  7785. minFilter = gl.LINEAR;
  7786. }
  7787. }
  7788. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7789. magFilter = gl.NEAREST;
  7790. if (generateMipMaps) {
  7791. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7792. }
  7793. else {
  7794. minFilter = gl.NEAREST;
  7795. }
  7796. }
  7797. return {
  7798. min: minFilter,
  7799. mag: magFilter
  7800. };
  7801. };
  7802. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7804. var engine = scene.getEngine();
  7805. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7806. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7807. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7808. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7809. texture._baseWidth = width;
  7810. texture._baseHeight = height;
  7811. texture._width = potWidth;
  7812. texture._height = potHeight;
  7813. texture.isReady = true;
  7814. processFunction(potWidth, potHeight);
  7815. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7818. if (!noMipmap && !isCompressed) {
  7819. gl.generateMipmap(gl.TEXTURE_2D);
  7820. }
  7821. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7822. engine.resetTextureCache();
  7823. scene._removePendingData(texture);
  7824. texture.onLoadedCallbacks.forEach(function (callback) {
  7825. callback();
  7826. });
  7827. texture.onLoadedCallbacks = [];
  7828. };
  7829. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7830. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7831. var img;
  7832. var onload = function () {
  7833. loadedImages[index] = img;
  7834. loadedImages._internalCount++;
  7835. scene._removePendingData(img);
  7836. if (loadedImages._internalCount === 6) {
  7837. onfinish(loadedImages);
  7838. }
  7839. };
  7840. var onerror = function () {
  7841. scene._removePendingData(img);
  7842. if (onErrorCallBack) {
  7843. onErrorCallBack();
  7844. }
  7845. };
  7846. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7847. scene._addPendingData(img);
  7848. };
  7849. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7850. if (onError === void 0) { onError = null; }
  7851. var loadedImages = [];
  7852. loadedImages._internalCount = 0;
  7853. for (var index = 0; index < 6; index++) {
  7854. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7855. }
  7856. };
  7857. var InstancingAttributeInfo = (function () {
  7858. function InstancingAttributeInfo() {
  7859. }
  7860. return InstancingAttributeInfo;
  7861. }());
  7862. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7863. var EngineCapabilities = (function () {
  7864. function EngineCapabilities() {
  7865. }
  7866. return EngineCapabilities;
  7867. }());
  7868. BABYLON.EngineCapabilities = EngineCapabilities;
  7869. /**
  7870. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7871. */
  7872. var Engine = (function () {
  7873. /**
  7874. * @constructor
  7875. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7876. * @param {boolean} [antialias] - enable antialias
  7877. * @param options - further options to be sent to the getContext function
  7878. */
  7879. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7880. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7881. var _this = this;
  7882. // Public members
  7883. this.isFullscreen = false;
  7884. this.isPointerLock = false;
  7885. this.cullBackFaces = true;
  7886. this.renderEvenInBackground = true;
  7887. this.preventCacheWipeBetweenFrames = false;
  7888. // To enable/disable IDB support and avoid XHR on .manifest
  7889. this.enableOfflineSupport = true;
  7890. this.scenes = new Array();
  7891. this._windowIsBackground = false;
  7892. this._webGLVersion = 1.0;
  7893. this._badOS = false;
  7894. this._drawCalls = new BABYLON.PerfCounter();
  7895. this._renderingQueueLaunched = false;
  7896. this._activeRenderLoops = [];
  7897. // FPS
  7898. this.fpsRange = 60;
  7899. this.previousFramesDuration = [];
  7900. this.fps = 60;
  7901. this.deltaTime = 0;
  7902. // States
  7903. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7904. this._stencilState = new BABYLON.Internals._StencilState();
  7905. this._alphaState = new BABYLON.Internals._AlphaState();
  7906. this._alphaMode = Engine.ALPHA_DISABLE;
  7907. // Cache
  7908. this._loadedTexturesCache = new Array();
  7909. this._maxTextureChannels = 16;
  7910. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7911. this._compiledEffects = {};
  7912. this._vertexAttribArraysEnabled = [];
  7913. this._uintIndicesCurrentlySet = false;
  7914. this._currentBoundBuffer = new Array();
  7915. this._currentBufferPointers = [];
  7916. this._currentInstanceLocations = new Array();
  7917. this._currentInstanceBuffers = new Array();
  7918. this._vaoRecordInProgress = false;
  7919. this._mustWipeVertexAttributes = false;
  7920. // Hardware supported Compressed Textures
  7921. this._texturesSupported = new Array();
  7922. this._onVRFullScreenTriggered = function () {
  7923. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7924. //get the old size before we change
  7925. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7926. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7927. //get the width and height, change the render size
  7928. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7929. var width, height;
  7930. _this.setHardwareScalingLevel(1);
  7931. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7932. }
  7933. else {
  7934. //When the specs are implemented, need to uncomment this.
  7935. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7936. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7937. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7938. _this._vrDisplayEnabled = undefined;
  7939. }
  7940. };
  7941. this._renderingCanvas = canvas;
  7942. Engine.Instances.push(this);
  7943. this._externalData = new BABYLON.StringDictionary();
  7944. options = options || {};
  7945. if (antialias != null) {
  7946. options.antialias = antialias;
  7947. }
  7948. if (options.preserveDrawingBuffer === undefined) {
  7949. options.preserveDrawingBuffer = false;
  7950. }
  7951. if (options.audioEngine === undefined) {
  7952. options.audioEngine = true;
  7953. }
  7954. if (options.stencil === undefined) {
  7955. options.stencil = true;
  7956. }
  7957. // GL
  7958. if (!options.disableWebGL2Support) {
  7959. try {
  7960. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7961. if (this._gl) {
  7962. this._webGLVersion = 2.0;
  7963. }
  7964. }
  7965. catch (e) {
  7966. }
  7967. }
  7968. if (!this._gl) {
  7969. if (!canvas) {
  7970. throw new Error("The provided canvas is null or undefined.");
  7971. }
  7972. try {
  7973. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7974. }
  7975. catch (e) {
  7976. throw new Error("WebGL not supported");
  7977. }
  7978. }
  7979. if (!this._gl) {
  7980. throw new Error("WebGL not supported");
  7981. }
  7982. this._onBlur = function () {
  7983. _this._windowIsBackground = true;
  7984. };
  7985. this._onFocus = function () {
  7986. _this._windowIsBackground = false;
  7987. };
  7988. window.addEventListener("blur", this._onBlur);
  7989. window.addEventListener("focus", this._onFocus);
  7990. // Viewport
  7991. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7992. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7993. this.resize();
  7994. // Caps
  7995. this._isStencilEnable = options.stencil;
  7996. this._caps = new EngineCapabilities();
  7997. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7998. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7999. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8000. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8001. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8002. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8003. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8004. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8005. // Infos
  8006. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8007. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8008. if (rendererInfo != null) {
  8009. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8010. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8011. }
  8012. if (!this._glVendor) {
  8013. this._glVendor = "Unknown vendor";
  8014. }
  8015. if (!this._glRenderer) {
  8016. this._glRenderer = "Unknown renderer";
  8017. }
  8018. // Extensions
  8019. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8020. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8021. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8022. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8023. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8024. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8025. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8026. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  8027. 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');
  8028. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8029. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8030. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8031. this._caps.highPrecisionShaderSupported = true;
  8032. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8033. // Checks if some of the format renders first to allow the use of webgl inspector.
  8034. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8035. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8036. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8037. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8038. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8039. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8040. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8041. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8042. // Vertex array object
  8043. if (this._webGLVersion > 1) {
  8044. this._caps.vertexArrayObject = true;
  8045. }
  8046. else {
  8047. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8048. if (vertexArrayObjectExtension != null) {
  8049. this._caps.vertexArrayObject = true;
  8050. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8051. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8052. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8053. }
  8054. else {
  8055. this._caps.vertexArrayObject = false;
  8056. }
  8057. }
  8058. // Instances count
  8059. if (this._webGLVersion > 1) {
  8060. this._caps.instancedArrays = true;
  8061. }
  8062. else {
  8063. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8064. if (instanceExtension != null) {
  8065. this._caps.instancedArrays = true;
  8066. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8067. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8068. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8069. }
  8070. else {
  8071. this._caps.instancedArrays = false;
  8072. }
  8073. }
  8074. // Intelligently add supported compressed formats in order to check for.
  8075. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8076. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8077. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8078. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8079. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  8080. if (this._caps.astc)
  8081. this.texturesSupported.push('-astc.ktx');
  8082. if (this._caps.s3tc)
  8083. this.texturesSupported.push('-dxt.ktx');
  8084. if (this._caps.pvrtc)
  8085. this.texturesSupported.push('-pvrtc.ktx');
  8086. if (this._caps.etc2)
  8087. this.texturesSupported.push('-etc2.ktx');
  8088. if (this._caps.atc)
  8089. this.texturesSupported.push('-atc.ktx');
  8090. if (this._caps.etc1)
  8091. this.texturesSupported.push('-etc1.ktx');
  8092. if (this._gl.getShaderPrecisionFormat) {
  8093. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8094. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8095. }
  8096. // Depth buffer
  8097. this.setDepthBuffer(true);
  8098. this.setDepthFunctionToLessOrEqual();
  8099. this.setDepthWrite(true);
  8100. // Fullscreen
  8101. this._onFullscreenChange = function () {
  8102. if (document.fullscreen !== undefined) {
  8103. _this.isFullscreen = document.fullscreen;
  8104. }
  8105. else if (document.mozFullScreen !== undefined) {
  8106. _this.isFullscreen = document.mozFullScreen;
  8107. }
  8108. else if (document.webkitIsFullScreen !== undefined) {
  8109. _this.isFullscreen = document.webkitIsFullScreen;
  8110. }
  8111. else if (document.msIsFullScreen !== undefined) {
  8112. _this.isFullscreen = document.msIsFullScreen;
  8113. }
  8114. // Pointer lock
  8115. if (_this.isFullscreen && _this._pointerLockRequested) {
  8116. canvas.requestPointerLock = canvas.requestPointerLock ||
  8117. canvas.msRequestPointerLock ||
  8118. canvas.mozRequestPointerLock ||
  8119. canvas.webkitRequestPointerLock;
  8120. if (canvas.requestPointerLock) {
  8121. canvas.requestPointerLock();
  8122. }
  8123. }
  8124. };
  8125. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8126. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8127. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8128. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8129. // Pointer lock
  8130. this._onPointerLockChange = function () {
  8131. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8132. document.webkitPointerLockElement === canvas ||
  8133. document.msPointerLockElement === canvas ||
  8134. document.pointerLockElement === canvas);
  8135. };
  8136. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8137. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8138. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8139. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8140. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8141. Engine.audioEngine = new BABYLON.AudioEngine();
  8142. }
  8143. //default loading screen
  8144. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  8145. //Load WebVR Devices
  8146. if (options.autoEnableWebVR) {
  8147. this.initWebVR();
  8148. }
  8149. //Detect if we are running on a faulty buggy OS.
  8150. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  8151. //ua sniffing is the tool of the devil.
  8152. this._badOS = regexp.test(navigator.userAgent);
  8153. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8154. }
  8155. Object.defineProperty(Engine, "LastCreatedEngine", {
  8156. get: function () {
  8157. if (Engine.Instances.length === 0) {
  8158. return null;
  8159. }
  8160. return Engine.Instances[Engine.Instances.length - 1];
  8161. },
  8162. enumerable: true,
  8163. configurable: true
  8164. });
  8165. Object.defineProperty(Engine, "LastCreatedScene", {
  8166. get: function () {
  8167. var lastCreatedEngine = Engine.LastCreatedEngine;
  8168. if (!lastCreatedEngine) {
  8169. return null;
  8170. }
  8171. if (lastCreatedEngine.scenes.length === 0) {
  8172. return null;
  8173. }
  8174. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8175. },
  8176. enumerable: true,
  8177. configurable: true
  8178. });
  8179. Object.defineProperty(Engine, "NEVER", {
  8180. get: function () {
  8181. return Engine._NEVER;
  8182. },
  8183. enumerable: true,
  8184. configurable: true
  8185. });
  8186. Object.defineProperty(Engine, "ALWAYS", {
  8187. get: function () {
  8188. return Engine._ALWAYS;
  8189. },
  8190. enumerable: true,
  8191. configurable: true
  8192. });
  8193. Object.defineProperty(Engine, "LESS", {
  8194. get: function () {
  8195. return Engine._LESS;
  8196. },
  8197. enumerable: true,
  8198. configurable: true
  8199. });
  8200. Object.defineProperty(Engine, "EQUAL", {
  8201. get: function () {
  8202. return Engine._EQUAL;
  8203. },
  8204. enumerable: true,
  8205. configurable: true
  8206. });
  8207. Object.defineProperty(Engine, "LEQUAL", {
  8208. get: function () {
  8209. return Engine._LEQUAL;
  8210. },
  8211. enumerable: true,
  8212. configurable: true
  8213. });
  8214. Object.defineProperty(Engine, "GREATER", {
  8215. get: function () {
  8216. return Engine._GREATER;
  8217. },
  8218. enumerable: true,
  8219. configurable: true
  8220. });
  8221. Object.defineProperty(Engine, "GEQUAL", {
  8222. get: function () {
  8223. return Engine._GEQUAL;
  8224. },
  8225. enumerable: true,
  8226. configurable: true
  8227. });
  8228. Object.defineProperty(Engine, "NOTEQUAL", {
  8229. get: function () {
  8230. return Engine._NOTEQUAL;
  8231. },
  8232. enumerable: true,
  8233. configurable: true
  8234. });
  8235. Object.defineProperty(Engine, "KEEP", {
  8236. get: function () {
  8237. return Engine._KEEP;
  8238. },
  8239. enumerable: true,
  8240. configurable: true
  8241. });
  8242. Object.defineProperty(Engine, "REPLACE", {
  8243. get: function () {
  8244. return Engine._REPLACE;
  8245. },
  8246. enumerable: true,
  8247. configurable: true
  8248. });
  8249. Object.defineProperty(Engine, "INCR", {
  8250. get: function () {
  8251. return Engine._INCR;
  8252. },
  8253. enumerable: true,
  8254. configurable: true
  8255. });
  8256. Object.defineProperty(Engine, "DECR", {
  8257. get: function () {
  8258. return Engine._DECR;
  8259. },
  8260. enumerable: true,
  8261. configurable: true
  8262. });
  8263. Object.defineProperty(Engine, "INVERT", {
  8264. get: function () {
  8265. return Engine._INVERT;
  8266. },
  8267. enumerable: true,
  8268. configurable: true
  8269. });
  8270. Object.defineProperty(Engine, "INCR_WRAP", {
  8271. get: function () {
  8272. return Engine._INCR_WRAP;
  8273. },
  8274. enumerable: true,
  8275. configurable: true
  8276. });
  8277. Object.defineProperty(Engine, "DECR_WRAP", {
  8278. get: function () {
  8279. return Engine._DECR_WRAP;
  8280. },
  8281. enumerable: true,
  8282. configurable: true
  8283. });
  8284. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8285. get: function () {
  8286. return Engine._ALPHA_DISABLE;
  8287. },
  8288. enumerable: true,
  8289. configurable: true
  8290. });
  8291. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8292. get: function () {
  8293. return Engine._ALPHA_ONEONE;
  8294. },
  8295. enumerable: true,
  8296. configurable: true
  8297. });
  8298. Object.defineProperty(Engine, "ALPHA_ADD", {
  8299. get: function () {
  8300. return Engine._ALPHA_ADD;
  8301. },
  8302. enumerable: true,
  8303. configurable: true
  8304. });
  8305. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8306. get: function () {
  8307. return Engine._ALPHA_COMBINE;
  8308. },
  8309. enumerable: true,
  8310. configurable: true
  8311. });
  8312. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8313. get: function () {
  8314. return Engine._ALPHA_SUBTRACT;
  8315. },
  8316. enumerable: true,
  8317. configurable: true
  8318. });
  8319. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8320. get: function () {
  8321. return Engine._ALPHA_MULTIPLY;
  8322. },
  8323. enumerable: true,
  8324. configurable: true
  8325. });
  8326. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8327. get: function () {
  8328. return Engine._ALPHA_MAXIMIZED;
  8329. },
  8330. enumerable: true,
  8331. configurable: true
  8332. });
  8333. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8334. get: function () {
  8335. return Engine._ALPHA_PREMULTIPLIED;
  8336. },
  8337. enumerable: true,
  8338. configurable: true
  8339. });
  8340. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8341. get: function () {
  8342. return Engine._DELAYLOADSTATE_NONE;
  8343. },
  8344. enumerable: true,
  8345. configurable: true
  8346. });
  8347. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8348. get: function () {
  8349. return Engine._DELAYLOADSTATE_LOADED;
  8350. },
  8351. enumerable: true,
  8352. configurable: true
  8353. });
  8354. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8355. get: function () {
  8356. return Engine._DELAYLOADSTATE_LOADING;
  8357. },
  8358. enumerable: true,
  8359. configurable: true
  8360. });
  8361. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8362. get: function () {
  8363. return Engine._DELAYLOADSTATE_NOTLOADED;
  8364. },
  8365. enumerable: true,
  8366. configurable: true
  8367. });
  8368. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8369. get: function () {
  8370. return Engine._TEXTUREFORMAT_ALPHA;
  8371. },
  8372. enumerable: true,
  8373. configurable: true
  8374. });
  8375. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8376. get: function () {
  8377. return Engine._TEXTUREFORMAT_LUMINANCE;
  8378. },
  8379. enumerable: true,
  8380. configurable: true
  8381. });
  8382. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8383. get: function () {
  8384. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8385. },
  8386. enumerable: true,
  8387. configurable: true
  8388. });
  8389. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8390. get: function () {
  8391. return Engine._TEXTUREFORMAT_RGB;
  8392. },
  8393. enumerable: true,
  8394. configurable: true
  8395. });
  8396. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8397. get: function () {
  8398. return Engine._TEXTUREFORMAT_RGBA;
  8399. },
  8400. enumerable: true,
  8401. configurable: true
  8402. });
  8403. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8404. get: function () {
  8405. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8406. },
  8407. enumerable: true,
  8408. configurable: true
  8409. });
  8410. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8411. get: function () {
  8412. return Engine._TEXTURETYPE_FLOAT;
  8413. },
  8414. enumerable: true,
  8415. configurable: true
  8416. });
  8417. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8418. get: function () {
  8419. return Engine._TEXTURETYPE_HALF_FLOAT;
  8420. },
  8421. enumerable: true,
  8422. configurable: true
  8423. });
  8424. Object.defineProperty(Engine, "Version", {
  8425. get: function () {
  8426. return "3.0-alpha";
  8427. },
  8428. enumerable: true,
  8429. configurable: true
  8430. });
  8431. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8432. get: function () {
  8433. return this._texturesSupported;
  8434. },
  8435. enumerable: true,
  8436. configurable: true
  8437. });
  8438. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8439. get: function () {
  8440. return this._textureFormatInUse;
  8441. },
  8442. enumerable: true,
  8443. configurable: true
  8444. });
  8445. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8446. get: function () {
  8447. return this._webGLVersion;
  8448. },
  8449. enumerable: true,
  8450. configurable: true
  8451. });
  8452. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8453. /**
  8454. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8455. */
  8456. get: function () {
  8457. return this._isStencilEnable;
  8458. },
  8459. enumerable: true,
  8460. configurable: true
  8461. });
  8462. Engine.prototype._prepareWorkingCanvas = function () {
  8463. if (this._workingCanvas) {
  8464. return;
  8465. }
  8466. this._workingCanvas = document.createElement("canvas");
  8467. this._workingContext = this._workingCanvas.getContext("2d");
  8468. };
  8469. Engine.prototype.resetTextureCache = function () {
  8470. for (var index = 0; index < this._maxTextureChannels; index++) {
  8471. this._activeTexturesCache[index] = null;
  8472. }
  8473. };
  8474. Engine.prototype.getGlInfo = function () {
  8475. return {
  8476. vendor: this._glVendor,
  8477. renderer: this._glRenderer,
  8478. version: this._glVersion
  8479. };
  8480. };
  8481. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8482. if (useScreen === void 0) { useScreen = false; }
  8483. var viewport = camera.viewport;
  8484. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8485. };
  8486. Engine.prototype.getRenderWidth = function (useScreen) {
  8487. if (useScreen === void 0) { useScreen = false; }
  8488. if (!useScreen && this._currentRenderTarget) {
  8489. return this._currentRenderTarget._width;
  8490. }
  8491. return this._renderingCanvas.width;
  8492. };
  8493. Engine.prototype.getRenderHeight = function (useScreen) {
  8494. if (useScreen === void 0) { useScreen = false; }
  8495. if (!useScreen && this._currentRenderTarget) {
  8496. return this._currentRenderTarget._height;
  8497. }
  8498. return this._renderingCanvas.height;
  8499. };
  8500. Engine.prototype.getRenderingCanvas = function () {
  8501. return this._renderingCanvas;
  8502. };
  8503. Engine.prototype.getRenderingCanvasClientRect = function () {
  8504. return this._renderingCanvas.getBoundingClientRect();
  8505. };
  8506. Engine.prototype.setHardwareScalingLevel = function (level) {
  8507. this._hardwareScalingLevel = level;
  8508. this.resize();
  8509. };
  8510. Engine.prototype.getHardwareScalingLevel = function () {
  8511. return this._hardwareScalingLevel;
  8512. };
  8513. Engine.prototype.getLoadedTexturesCache = function () {
  8514. return this._loadedTexturesCache;
  8515. };
  8516. Engine.prototype.getCaps = function () {
  8517. return this._caps;
  8518. };
  8519. Object.defineProperty(Engine.prototype, "drawCalls", {
  8520. get: function () {
  8521. return this._drawCalls.current;
  8522. },
  8523. enumerable: true,
  8524. configurable: true
  8525. });
  8526. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8527. get: function () {
  8528. return this._drawCalls;
  8529. },
  8530. enumerable: true,
  8531. configurable: true
  8532. });
  8533. Engine.prototype.getDepthFunction = function () {
  8534. return this._depthCullingState.depthFunc;
  8535. };
  8536. Engine.prototype.setDepthFunction = function (depthFunc) {
  8537. this._depthCullingState.depthFunc = depthFunc;
  8538. };
  8539. Engine.prototype.setDepthFunctionToGreater = function () {
  8540. this._depthCullingState.depthFunc = this._gl.GREATER;
  8541. };
  8542. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8543. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8544. };
  8545. Engine.prototype.setDepthFunctionToLess = function () {
  8546. this._depthCullingState.depthFunc = this._gl.LESS;
  8547. };
  8548. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8549. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8550. };
  8551. Engine.prototype.getStencilBuffer = function () {
  8552. return this._stencilState.stencilTest;
  8553. };
  8554. Engine.prototype.setStencilBuffer = function (enable) {
  8555. this._stencilState.stencilTest = enable;
  8556. };
  8557. Engine.prototype.getStencilMask = function () {
  8558. return this._stencilState.stencilMask;
  8559. };
  8560. Engine.prototype.setStencilMask = function (mask) {
  8561. this._stencilState.stencilMask = mask;
  8562. };
  8563. Engine.prototype.getStencilFunction = function () {
  8564. return this._stencilState.stencilFunc;
  8565. };
  8566. Engine.prototype.getStencilFunctionReference = function () {
  8567. return this._stencilState.stencilFuncRef;
  8568. };
  8569. Engine.prototype.getStencilFunctionMask = function () {
  8570. return this._stencilState.stencilFuncMask;
  8571. };
  8572. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8573. this._stencilState.stencilFunc = stencilFunc;
  8574. };
  8575. Engine.prototype.setStencilFunctionReference = function (reference) {
  8576. this._stencilState.stencilFuncRef = reference;
  8577. };
  8578. Engine.prototype.setStencilFunctionMask = function (mask) {
  8579. this._stencilState.stencilFuncMask = mask;
  8580. };
  8581. Engine.prototype.getStencilOperationFail = function () {
  8582. return this._stencilState.stencilOpStencilFail;
  8583. };
  8584. Engine.prototype.getStencilOperationDepthFail = function () {
  8585. return this._stencilState.stencilOpDepthFail;
  8586. };
  8587. Engine.prototype.getStencilOperationPass = function () {
  8588. return this._stencilState.stencilOpStencilDepthPass;
  8589. };
  8590. Engine.prototype.setStencilOperationFail = function (operation) {
  8591. this._stencilState.stencilOpStencilFail = operation;
  8592. };
  8593. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8594. this._stencilState.stencilOpDepthFail = operation;
  8595. };
  8596. Engine.prototype.setStencilOperationPass = function (operation) {
  8597. this._stencilState.stencilOpStencilDepthPass = operation;
  8598. };
  8599. /**
  8600. * stop executing a render loop function and remove it from the execution array
  8601. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8602. */
  8603. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8604. if (!renderFunction) {
  8605. this._activeRenderLoops = [];
  8606. return;
  8607. }
  8608. var index = this._activeRenderLoops.indexOf(renderFunction);
  8609. if (index >= 0) {
  8610. this._activeRenderLoops.splice(index, 1);
  8611. }
  8612. };
  8613. Engine.prototype._renderLoop = function () {
  8614. var shouldRender = true;
  8615. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8616. shouldRender = false;
  8617. }
  8618. if (shouldRender) {
  8619. // Start new frame
  8620. this.beginFrame();
  8621. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8622. var renderFunction = this._activeRenderLoops[index];
  8623. renderFunction();
  8624. }
  8625. // Present
  8626. this.endFrame();
  8627. }
  8628. if (this._activeRenderLoops.length > 0) {
  8629. // Register new frame
  8630. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8631. }
  8632. else {
  8633. this._renderingQueueLaunched = false;
  8634. }
  8635. };
  8636. /**
  8637. * Register and execute a render loop. The engine can have more than one render function.
  8638. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8639. * @example
  8640. * engine.runRenderLoop(function () {
  8641. * scene.render()
  8642. * })
  8643. */
  8644. Engine.prototype.runRenderLoop = function (renderFunction) {
  8645. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8646. return;
  8647. }
  8648. this._activeRenderLoops.push(renderFunction);
  8649. if (!this._renderingQueueLaunched) {
  8650. this._renderingQueueLaunched = true;
  8651. this._bindedRenderFunction = this._renderLoop.bind(this);
  8652. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8653. }
  8654. };
  8655. /**
  8656. * Toggle full screen mode.
  8657. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8658. * @param {any} options - an options object to be sent to the requestFullscreen function
  8659. */
  8660. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8661. if (this.isFullscreen) {
  8662. BABYLON.Tools.ExitFullscreen();
  8663. }
  8664. else {
  8665. this._pointerLockRequested = requestPointerLock;
  8666. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8667. }
  8668. };
  8669. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8670. if (stencil === void 0) { stencil = false; }
  8671. this.applyStates();
  8672. var mode = 0;
  8673. if (backBuffer && color) {
  8674. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8675. mode |= this._gl.COLOR_BUFFER_BIT;
  8676. }
  8677. if (depth) {
  8678. this._gl.clearDepth(1.0);
  8679. mode |= this._gl.DEPTH_BUFFER_BIT;
  8680. }
  8681. if (stencil) {
  8682. this._gl.clearStencil(0);
  8683. mode |= this._gl.STENCIL_BUFFER_BIT;
  8684. }
  8685. this._gl.clear(mode);
  8686. };
  8687. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8688. var gl = this._gl;
  8689. // Save state
  8690. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8691. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8692. // Change state
  8693. gl.enable(gl.SCISSOR_TEST);
  8694. gl.scissor(x, y, width, height);
  8695. // Clear
  8696. this.clear(clearColor, true, true, true);
  8697. // Restore state
  8698. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8699. if (curScissor === true) {
  8700. gl.enable(gl.SCISSOR_TEST);
  8701. }
  8702. else {
  8703. gl.disable(gl.SCISSOR_TEST);
  8704. }
  8705. };
  8706. /**
  8707. * Set the WebGL's viewport
  8708. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8709. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8710. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8711. */
  8712. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8713. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8714. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8715. var x = viewport.x || 0;
  8716. var y = viewport.y || 0;
  8717. this._cachedViewport = viewport;
  8718. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8719. };
  8720. /**
  8721. * Directly set the WebGL Viewport
  8722. * The x, y, width & height are directly passed to the WebGL call
  8723. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  8724. */
  8725. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8726. var currentViewport = this._cachedViewport;
  8727. this._cachedViewport = null;
  8728. this._gl.viewport(x, y, width, height);
  8729. return currentViewport;
  8730. };
  8731. Engine.prototype.beginFrame = function () {
  8732. this._measureFps();
  8733. };
  8734. Engine.prototype.endFrame = function () {
  8735. //force a flush in case we are using a bad OS.
  8736. if (this._badOS) {
  8737. this.flushFramebuffer();
  8738. }
  8739. //submit frame to the vr device, if enabled
  8740. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8741. this._vrDisplayEnabled.submitFrame();
  8742. }
  8743. };
  8744. /**
  8745. * resize the view according to the canvas' size.
  8746. * @example
  8747. * window.addEventListener("resize", function () {
  8748. * engine.resize();
  8749. * });
  8750. */
  8751. Engine.prototype.resize = function () {
  8752. // We're not resizing the size of the canvas while in VR mode & presenting
  8753. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8754. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8755. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8756. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8757. }
  8758. };
  8759. /**
  8760. * force a specific size of the canvas
  8761. * @param {number} width - the new canvas' width
  8762. * @param {number} height - the new canvas' height
  8763. */
  8764. Engine.prototype.setSize = function (width, height) {
  8765. this._renderingCanvas.width = width;
  8766. this._renderingCanvas.height = height;
  8767. for (var index = 0; index < this.scenes.length; index++) {
  8768. var scene = this.scenes[index];
  8769. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8770. var cam = scene.cameras[camIndex];
  8771. cam._currentRenderId = 0;
  8772. }
  8773. }
  8774. };
  8775. //WebVR functions
  8776. Engine.prototype.initWebVR = function () {
  8777. if (!this.vrDisplaysPromise) {
  8778. this._getVRDisplays();
  8779. }
  8780. };
  8781. Engine.prototype.enableVR = function (vrDevice) {
  8782. this._vrDisplayEnabled = vrDevice;
  8783. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8784. };
  8785. Engine.prototype.disableVR = function () {
  8786. if (this._vrDisplayEnabled) {
  8787. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8788. }
  8789. };
  8790. Engine.prototype._getVRDisplays = function () {
  8791. var _this = this;
  8792. var getWebVRDevices = function (devices) {
  8793. var size = devices.length;
  8794. var i = 0;
  8795. _this._vrDisplays = devices.filter(function (device) {
  8796. return devices[i] instanceof VRDisplay;
  8797. });
  8798. return _this._vrDisplays;
  8799. };
  8800. //using a key due to typescript
  8801. if (navigator.getVRDisplays) {
  8802. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8803. }
  8804. };
  8805. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8806. this._currentRenderTarget = texture;
  8807. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8808. var gl = this._gl;
  8809. if (texture.isCube) {
  8810. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8811. }
  8812. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8813. this.wipeCaches();
  8814. };
  8815. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8816. if (this._currentFramebuffer !== framebuffer) {
  8817. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8818. this._currentFramebuffer = framebuffer;
  8819. }
  8820. };
  8821. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8822. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8823. this._currentRenderTarget = null;
  8824. // If MSAA, we need to bitblt back to main texture
  8825. var gl = this._gl;
  8826. if (texture._MSAAFramebuffer) {
  8827. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8828. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8829. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8830. }
  8831. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8832. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8833. gl.generateMipmap(gl.TEXTURE_2D);
  8834. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8835. }
  8836. if (onBeforeUnbind) {
  8837. if (texture._MSAAFramebuffer) {
  8838. // Bind the correct framebuffer
  8839. this.bindUnboundFramebuffer(texture._framebuffer);
  8840. }
  8841. onBeforeUnbind();
  8842. }
  8843. this.bindUnboundFramebuffer(null);
  8844. };
  8845. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8846. if (texture.generateMipMaps) {
  8847. var gl = this._gl;
  8848. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8849. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8850. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8851. }
  8852. };
  8853. Engine.prototype.flushFramebuffer = function () {
  8854. this._gl.flush();
  8855. };
  8856. Engine.prototype.restoreDefaultFramebuffer = function () {
  8857. this._currentRenderTarget = null;
  8858. this.bindUnboundFramebuffer(null);
  8859. this.setViewport(this._cachedViewport);
  8860. this.wipeCaches();
  8861. };
  8862. // VBOs
  8863. Engine.prototype._resetVertexBufferBinding = function () {
  8864. this.bindArrayBuffer(null);
  8865. this._cachedVertexBuffers = null;
  8866. };
  8867. Engine.prototype.createVertexBuffer = function (vertices) {
  8868. var vbo = this._gl.createBuffer();
  8869. this.bindArrayBuffer(vbo);
  8870. if (vertices instanceof Float32Array) {
  8871. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8872. }
  8873. else {
  8874. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8875. }
  8876. this._resetVertexBufferBinding();
  8877. vbo.references = 1;
  8878. return vbo;
  8879. };
  8880. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8881. var vbo = this._gl.createBuffer();
  8882. this.bindArrayBuffer(vbo);
  8883. if (vertices instanceof Float32Array) {
  8884. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8885. }
  8886. else {
  8887. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8888. }
  8889. this._resetVertexBufferBinding();
  8890. vbo.references = 1;
  8891. return vbo;
  8892. };
  8893. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8894. this.bindArrayBuffer(vertexBuffer);
  8895. if (offset === undefined) {
  8896. offset = 0;
  8897. }
  8898. if (count === undefined) {
  8899. if (vertices instanceof Float32Array) {
  8900. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8901. }
  8902. else {
  8903. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8904. }
  8905. }
  8906. else {
  8907. if (vertices instanceof Float32Array) {
  8908. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8909. }
  8910. else {
  8911. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8912. }
  8913. }
  8914. this._resetVertexBufferBinding();
  8915. };
  8916. Engine.prototype._resetIndexBufferBinding = function () {
  8917. this.bindIndexBuffer(null);
  8918. this._cachedIndexBuffer = null;
  8919. };
  8920. Engine.prototype.createIndexBuffer = function (indices) {
  8921. var vbo = this._gl.createBuffer();
  8922. this.bindIndexBuffer(vbo);
  8923. // Check for 32 bits indices
  8924. var arrayBuffer;
  8925. var need32Bits = false;
  8926. if (indices instanceof Uint16Array) {
  8927. arrayBuffer = indices;
  8928. }
  8929. else {
  8930. //check 32 bit support
  8931. if (this._caps.uintIndices) {
  8932. if (indices instanceof Uint32Array) {
  8933. arrayBuffer = indices;
  8934. need32Bits = true;
  8935. }
  8936. else {
  8937. //number[] or Int32Array, check if 32 bit is necessary
  8938. for (var index = 0; index < indices.length; index++) {
  8939. if (indices[index] > 65535) {
  8940. need32Bits = true;
  8941. break;
  8942. }
  8943. }
  8944. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8945. }
  8946. }
  8947. else {
  8948. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8949. arrayBuffer = new Uint16Array(indices);
  8950. }
  8951. }
  8952. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8953. this._resetIndexBufferBinding();
  8954. vbo.references = 1;
  8955. vbo.is32Bits = need32Bits;
  8956. return vbo;
  8957. };
  8958. Engine.prototype.bindArrayBuffer = function (buffer) {
  8959. if (!this._vaoRecordInProgress) {
  8960. this._unBindVertexArrayObject();
  8961. }
  8962. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8963. };
  8964. Engine.prototype.bindIndexBuffer = function (buffer) {
  8965. if (!this._vaoRecordInProgress) {
  8966. this._unBindVertexArrayObject();
  8967. }
  8968. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8969. };
  8970. Engine.prototype.bindBuffer = function (buffer, target) {
  8971. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8972. this._gl.bindBuffer(target, buffer);
  8973. this._currentBoundBuffer[target] = buffer;
  8974. }
  8975. };
  8976. Engine.prototype.updateArrayBuffer = function (data) {
  8977. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8978. };
  8979. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8980. var pointer = this._currentBufferPointers[indx];
  8981. var changed = false;
  8982. if (!pointer) {
  8983. changed = true;
  8984. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8985. }
  8986. else {
  8987. if (pointer.buffer !== buffer) {
  8988. pointer.buffer = buffer;
  8989. changed = true;
  8990. }
  8991. if (pointer.size !== size) {
  8992. pointer.size = size;
  8993. changed = true;
  8994. }
  8995. if (pointer.type !== type) {
  8996. pointer.type = type;
  8997. changed = true;
  8998. }
  8999. if (pointer.normalized !== normalized) {
  9000. pointer.normalized = normalized;
  9001. changed = true;
  9002. }
  9003. if (pointer.stride !== stride) {
  9004. pointer.stride = stride;
  9005. changed = true;
  9006. }
  9007. if (pointer.offset !== offset) {
  9008. pointer.offset = offset;
  9009. changed = true;
  9010. }
  9011. }
  9012. if (changed || this._vaoRecordInProgress) {
  9013. this.bindArrayBuffer(buffer);
  9014. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9015. }
  9016. };
  9017. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9018. if (indexBuffer == null) {
  9019. return;
  9020. }
  9021. if (this._cachedIndexBuffer !== indexBuffer) {
  9022. this._cachedIndexBuffer = indexBuffer;
  9023. this.bindIndexBuffer(indexBuffer);
  9024. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9025. }
  9026. };
  9027. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9028. var attributes = effect.getAttributesNames();
  9029. if (!this._vaoRecordInProgress) {
  9030. this._unBindVertexArrayObject();
  9031. }
  9032. this.unbindAllAttributes();
  9033. for (var index = 0; index < attributes.length; index++) {
  9034. var order = effect.getAttributeLocation(index);
  9035. if (order >= 0) {
  9036. var vertexBuffer = vertexBuffers[attributes[index]];
  9037. if (!vertexBuffer) {
  9038. continue;
  9039. }
  9040. this._gl.enableVertexAttribArray(order);
  9041. if (!this._vaoRecordInProgress) {
  9042. this._vertexAttribArraysEnabled[order] = true;
  9043. }
  9044. var buffer = vertexBuffer.getBuffer();
  9045. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9046. if (vertexBuffer.getIsInstanced()) {
  9047. this._gl.vertexAttribDivisor(order, 1);
  9048. if (!this._vaoRecordInProgress) {
  9049. this._currentInstanceLocations.push(order);
  9050. this._currentInstanceBuffers.push(buffer);
  9051. }
  9052. }
  9053. }
  9054. }
  9055. };
  9056. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9057. var vao = this._gl.createVertexArray();
  9058. this._vaoRecordInProgress = true;
  9059. this._gl.bindVertexArray(vao);
  9060. this._mustWipeVertexAttributes = true;
  9061. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9062. this.bindIndexBuffer(indexBuffer);
  9063. this._vaoRecordInProgress = false;
  9064. this._gl.bindVertexArray(null);
  9065. return vao;
  9066. };
  9067. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9068. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9069. this._cachedVertexArrayObject = vertexArrayObject;
  9070. this._gl.bindVertexArray(vertexArrayObject);
  9071. this._cachedVertexBuffers = null;
  9072. this._cachedIndexBuffer = null;
  9073. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9074. this._mustWipeVertexAttributes = true;
  9075. }
  9076. };
  9077. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9078. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9079. this._cachedVertexBuffers = vertexBuffer;
  9080. this._cachedEffectForVertexBuffers = effect;
  9081. var attributesCount = effect.getAttributesCount();
  9082. this._unBindVertexArrayObject();
  9083. this.unbindAllAttributes();
  9084. var offset = 0;
  9085. for (var index = 0; index < attributesCount; index++) {
  9086. if (index < vertexDeclaration.length) {
  9087. var order = effect.getAttributeLocation(index);
  9088. if (order >= 0) {
  9089. this._gl.enableVertexAttribArray(order);
  9090. this._vertexAttribArraysEnabled[order] = true;
  9091. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9092. }
  9093. offset += vertexDeclaration[index] * 4;
  9094. }
  9095. }
  9096. }
  9097. this._bindIndexBufferWithCache(indexBuffer);
  9098. };
  9099. Engine.prototype._unBindVertexArrayObject = function () {
  9100. if (!this._cachedVertexArrayObject) {
  9101. return;
  9102. }
  9103. this._cachedVertexArrayObject = null;
  9104. this._gl.bindVertexArray(null);
  9105. };
  9106. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9107. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9108. this._cachedVertexBuffers = vertexBuffers;
  9109. this._cachedEffectForVertexBuffers = effect;
  9110. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9111. }
  9112. this._bindIndexBufferWithCache(indexBuffer);
  9113. };
  9114. Engine.prototype.unbindInstanceAttributes = function () {
  9115. var boundBuffer;
  9116. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9117. var instancesBuffer = this._currentInstanceBuffers[i];
  9118. if (boundBuffer != instancesBuffer) {
  9119. boundBuffer = instancesBuffer;
  9120. this.bindArrayBuffer(instancesBuffer);
  9121. }
  9122. var offsetLocation = this._currentInstanceLocations[i];
  9123. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9124. }
  9125. this._currentInstanceBuffers.length = 0;
  9126. this._currentInstanceLocations.length = 0;
  9127. };
  9128. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9129. this._gl.deleteVertexArray(vao);
  9130. };
  9131. Engine.prototype._releaseBuffer = function (buffer) {
  9132. buffer.references--;
  9133. if (buffer.references === 0) {
  9134. this._gl.deleteBuffer(buffer);
  9135. return true;
  9136. }
  9137. return false;
  9138. };
  9139. Engine.prototype.createInstancesBuffer = function (capacity) {
  9140. var buffer = this._gl.createBuffer();
  9141. buffer.capacity = capacity;
  9142. this.bindArrayBuffer(buffer);
  9143. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9144. return buffer;
  9145. };
  9146. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9147. this._gl.deleteBuffer(buffer);
  9148. };
  9149. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9150. this.bindArrayBuffer(instancesBuffer);
  9151. if (data) {
  9152. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9153. }
  9154. if (offsetLocations[0].index !== undefined) {
  9155. var stride = 0;
  9156. for (var i = 0; i < offsetLocations.length; i++) {
  9157. var ai = offsetLocations[i];
  9158. stride += ai.attributeSize * 4;
  9159. }
  9160. for (var i = 0; i < offsetLocations.length; i++) {
  9161. var ai = offsetLocations[i];
  9162. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9163. this._gl.enableVertexAttribArray(ai.index);
  9164. this._vertexAttribArraysEnabled[ai.index] = true;
  9165. }
  9166. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9167. this._gl.vertexAttribDivisor(ai.index, 1);
  9168. this._currentInstanceLocations.push(ai.index);
  9169. this._currentInstanceBuffers.push(instancesBuffer);
  9170. }
  9171. }
  9172. else {
  9173. for (var index = 0; index < 4; index++) {
  9174. var offsetLocation = offsetLocations[index];
  9175. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9176. this._gl.enableVertexAttribArray(offsetLocation);
  9177. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9178. }
  9179. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9180. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9181. this._currentInstanceLocations.push(offsetLocation);
  9182. this._currentInstanceBuffers.push(instancesBuffer);
  9183. }
  9184. }
  9185. };
  9186. Engine.prototype.applyStates = function () {
  9187. this._depthCullingState.apply(this._gl);
  9188. this._stencilState.apply(this._gl);
  9189. this._alphaState.apply(this._gl);
  9190. };
  9191. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9192. // Apply states
  9193. this.applyStates();
  9194. this._drawCalls.addCount(1, false);
  9195. // Render
  9196. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9197. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9198. if (instancesCount) {
  9199. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9200. return;
  9201. }
  9202. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9203. };
  9204. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9205. // Apply states
  9206. this.applyStates();
  9207. this._drawCalls.addCount(1, false);
  9208. if (instancesCount) {
  9209. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9210. return;
  9211. }
  9212. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9213. };
  9214. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9215. // Apply states
  9216. this.applyStates();
  9217. this._drawCalls.addCount(1, false);
  9218. if (instancesCount) {
  9219. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9220. return;
  9221. }
  9222. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9223. };
  9224. // Shaders
  9225. Engine.prototype._releaseEffect = function (effect) {
  9226. if (this._compiledEffects[effect._key]) {
  9227. delete this._compiledEffects[effect._key];
  9228. if (effect.getProgram()) {
  9229. this._gl.deleteProgram(effect.getProgram());
  9230. }
  9231. }
  9232. };
  9233. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9234. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9235. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9236. var name = vertex + "+" + fragment + "@" + defines;
  9237. if (this._compiledEffects[name]) {
  9238. return this._compiledEffects[name];
  9239. }
  9240. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9241. effect._key = name;
  9242. this._compiledEffects[name] = effect;
  9243. return effect;
  9244. };
  9245. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9246. if (uniformsNames === void 0) { uniformsNames = []; }
  9247. if (samplers === void 0) { samplers = []; }
  9248. if (defines === void 0) { defines = ""; }
  9249. return this.createEffect({
  9250. vertex: "particles",
  9251. fragmentElement: fragmentName
  9252. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9253. };
  9254. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9255. context = context || this._gl;
  9256. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9257. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9258. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9259. var shaderProgram = context.createProgram();
  9260. context.attachShader(shaderProgram, vertexShader);
  9261. context.attachShader(shaderProgram, fragmentShader);
  9262. context.linkProgram(shaderProgram);
  9263. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9264. if (!linked) {
  9265. var error = context.getProgramInfoLog(shaderProgram);
  9266. if (error) {
  9267. throw new Error(error);
  9268. }
  9269. }
  9270. context.deleteShader(vertexShader);
  9271. context.deleteShader(fragmentShader);
  9272. return shaderProgram;
  9273. };
  9274. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9275. var results = [];
  9276. for (var index = 0; index < uniformsNames.length; index++) {
  9277. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9278. }
  9279. return results;
  9280. };
  9281. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9282. var results = [];
  9283. for (var index = 0; index < attributesNames.length; index++) {
  9284. try {
  9285. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9286. }
  9287. catch (e) {
  9288. results.push(-1);
  9289. }
  9290. }
  9291. return results;
  9292. };
  9293. Engine.prototype.enableEffect = function (effect) {
  9294. // Use program
  9295. this.setProgram(effect.getProgram());
  9296. this._currentEffect = effect;
  9297. if (effect.onBind) {
  9298. effect.onBind(effect);
  9299. }
  9300. };
  9301. Engine.prototype.setIntArray = function (uniform, array) {
  9302. if (!uniform)
  9303. return;
  9304. this._gl.uniform1iv(uniform, array);
  9305. };
  9306. Engine.prototype.setIntArray2 = function (uniform, array) {
  9307. if (!uniform || array.length % 2 !== 0)
  9308. return;
  9309. this._gl.uniform2iv(uniform, array);
  9310. };
  9311. Engine.prototype.setIntArray3 = function (uniform, array) {
  9312. if (!uniform || array.length % 3 !== 0)
  9313. return;
  9314. this._gl.uniform3iv(uniform, array);
  9315. };
  9316. Engine.prototype.setIntArray4 = function (uniform, array) {
  9317. if (!uniform || array.length % 4 !== 0)
  9318. return;
  9319. this._gl.uniform4iv(uniform, array);
  9320. };
  9321. Engine.prototype.setFloatArray = function (uniform, array) {
  9322. if (!uniform)
  9323. return;
  9324. this._gl.uniform1fv(uniform, array);
  9325. };
  9326. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9327. if (!uniform || array.length % 2 !== 0)
  9328. return;
  9329. this._gl.uniform2fv(uniform, array);
  9330. };
  9331. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9332. if (!uniform || array.length % 3 !== 0)
  9333. return;
  9334. this._gl.uniform3fv(uniform, array);
  9335. };
  9336. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9337. if (!uniform || array.length % 4 !== 0)
  9338. return;
  9339. this._gl.uniform4fv(uniform, array);
  9340. };
  9341. Engine.prototype.setArray = function (uniform, array) {
  9342. if (!uniform)
  9343. return;
  9344. this._gl.uniform1fv(uniform, array);
  9345. };
  9346. Engine.prototype.setArray2 = function (uniform, array) {
  9347. if (!uniform || array.length % 2 !== 0)
  9348. return;
  9349. this._gl.uniform2fv(uniform, array);
  9350. };
  9351. Engine.prototype.setArray3 = function (uniform, array) {
  9352. if (!uniform || array.length % 3 !== 0)
  9353. return;
  9354. this._gl.uniform3fv(uniform, array);
  9355. };
  9356. Engine.prototype.setArray4 = function (uniform, array) {
  9357. if (!uniform || array.length % 4 !== 0)
  9358. return;
  9359. this._gl.uniform4fv(uniform, array);
  9360. };
  9361. Engine.prototype.setMatrices = function (uniform, matrices) {
  9362. if (!uniform)
  9363. return;
  9364. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9365. };
  9366. Engine.prototype.setMatrix = function (uniform, matrix) {
  9367. if (!uniform)
  9368. return;
  9369. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9370. };
  9371. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9372. if (!uniform)
  9373. return;
  9374. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9375. };
  9376. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9377. if (!uniform)
  9378. return;
  9379. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9380. };
  9381. Engine.prototype.setFloat = function (uniform, value) {
  9382. if (!uniform)
  9383. return;
  9384. this._gl.uniform1f(uniform, value);
  9385. };
  9386. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9387. if (!uniform)
  9388. return;
  9389. this._gl.uniform2f(uniform, x, y);
  9390. };
  9391. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9392. if (!uniform)
  9393. return;
  9394. this._gl.uniform3f(uniform, x, y, z);
  9395. };
  9396. Engine.prototype.setBool = function (uniform, bool) {
  9397. if (!uniform)
  9398. return;
  9399. this._gl.uniform1i(uniform, bool);
  9400. };
  9401. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9402. if (!uniform)
  9403. return;
  9404. this._gl.uniform4f(uniform, x, y, z, w);
  9405. };
  9406. Engine.prototype.setColor3 = function (uniform, color3) {
  9407. if (!uniform)
  9408. return;
  9409. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9410. };
  9411. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9412. if (!uniform)
  9413. return;
  9414. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9415. };
  9416. // States
  9417. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9418. if (zOffset === void 0) { zOffset = 0; }
  9419. if (reverseSide === void 0) { reverseSide = false; }
  9420. // Culling
  9421. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9422. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9423. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9424. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9425. if (culling) {
  9426. this._depthCullingState.cullFace = cullFace;
  9427. this._depthCullingState.cull = true;
  9428. }
  9429. else {
  9430. this._depthCullingState.cull = false;
  9431. }
  9432. }
  9433. // Z offset
  9434. this._depthCullingState.zOffset = zOffset;
  9435. };
  9436. Engine.prototype.setDepthBuffer = function (enable) {
  9437. this._depthCullingState.depthTest = enable;
  9438. };
  9439. Engine.prototype.getDepthWrite = function () {
  9440. return this._depthCullingState.depthMask;
  9441. };
  9442. Engine.prototype.setDepthWrite = function (enable) {
  9443. this._depthCullingState.depthMask = enable;
  9444. };
  9445. Engine.prototype.setColorWrite = function (enable) {
  9446. this._gl.colorMask(enable, enable, enable, enable);
  9447. };
  9448. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9449. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9450. if (this._alphaMode === mode) {
  9451. return;
  9452. }
  9453. switch (mode) {
  9454. case Engine.ALPHA_DISABLE:
  9455. this._alphaState.alphaBlend = false;
  9456. break;
  9457. case Engine.ALPHA_PREMULTIPLIED:
  9458. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9459. this._alphaState.alphaBlend = true;
  9460. break;
  9461. case Engine.ALPHA_COMBINE:
  9462. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9463. this._alphaState.alphaBlend = true;
  9464. break;
  9465. case Engine.ALPHA_ONEONE:
  9466. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9467. this._alphaState.alphaBlend = true;
  9468. break;
  9469. case Engine.ALPHA_ADD:
  9470. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9471. this._alphaState.alphaBlend = true;
  9472. break;
  9473. case Engine.ALPHA_SUBTRACT:
  9474. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9475. this._alphaState.alphaBlend = true;
  9476. break;
  9477. case Engine.ALPHA_MULTIPLY:
  9478. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9479. this._alphaState.alphaBlend = true;
  9480. break;
  9481. case Engine.ALPHA_MAXIMIZED:
  9482. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9483. this._alphaState.alphaBlend = true;
  9484. break;
  9485. }
  9486. if (!noDepthWriteChange) {
  9487. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9488. }
  9489. this._alphaMode = mode;
  9490. };
  9491. Engine.prototype.getAlphaMode = function () {
  9492. return this._alphaMode;
  9493. };
  9494. Engine.prototype.setAlphaTesting = function (enable) {
  9495. this._alphaTest = enable;
  9496. };
  9497. Engine.prototype.getAlphaTesting = function () {
  9498. return this._alphaTest;
  9499. };
  9500. // Textures
  9501. Engine.prototype.wipeCaches = function () {
  9502. if (this.preventCacheWipeBetweenFrames) {
  9503. return;
  9504. }
  9505. this.resetTextureCache();
  9506. this._currentEffect = null;
  9507. this._stencilState.reset();
  9508. this._depthCullingState.reset();
  9509. this.setDepthFunctionToLessOrEqual();
  9510. this._alphaState.reset();
  9511. this._cachedVertexBuffers = null;
  9512. this._cachedIndexBuffer = null;
  9513. this._cachedEffectForVertexBuffers = null;
  9514. this._unBindVertexArrayObject();
  9515. this.bindIndexBuffer(null);
  9516. this.bindArrayBuffer(null);
  9517. };
  9518. /**
  9519. * Set the compressed texture format to use, based on the formats you have, and the formats
  9520. * supported by the hardware / browser.
  9521. *
  9522. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9523. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9524. * to API arguments needed to compressed textures. This puts the burden on the container
  9525. * generator to house the arcane code for determining these for current & future formats.
  9526. *
  9527. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9528. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9529. *
  9530. * Note: The result of this call is not taken into account when a texture is base64.
  9531. *
  9532. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9533. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9534. *
  9535. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  9536. * @returns The extension selected.
  9537. */
  9538. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9539. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9540. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9541. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9542. return this._textureFormatInUse = this._texturesSupported[i];
  9543. }
  9544. }
  9545. }
  9546. // actively set format to nothing, to allow this to be called more than once
  9547. // and possibly fail the 2nd time
  9548. return this._textureFormatInUse = null;
  9549. };
  9550. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9551. var _this = this;
  9552. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9553. if (onLoad === void 0) { onLoad = null; }
  9554. if (onError === void 0) { onError = null; }
  9555. if (buffer === void 0) { buffer = null; }
  9556. var texture = fallBack ? fallBack : this._gl.createTexture();
  9557. var extension;
  9558. var isKTX = false;
  9559. var fromData = false;
  9560. var url = String(urlArg);
  9561. if (url.substr(0, 5) === "data:") {
  9562. fromData = true;
  9563. }
  9564. if (!fromData) {
  9565. var lastDot = url.lastIndexOf('.');
  9566. extension = url.substring(lastDot).toLowerCase();
  9567. if (this._textureFormatInUse && !fromData && !fallBack) {
  9568. extension = this._textureFormatInUse;
  9569. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9570. isKTX = true;
  9571. }
  9572. }
  9573. else {
  9574. var oldUrl = url;
  9575. fromData = oldUrl.split(':');
  9576. url = oldUrl;
  9577. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  9578. }
  9579. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9580. var isTGA = (extension === ".tga");
  9581. scene._addPendingData(texture);
  9582. texture.url = url;
  9583. texture.noMipmap = noMipmap;
  9584. texture.references = 1;
  9585. texture.samplingMode = samplingMode;
  9586. texture.onLoadedCallbacks = [];
  9587. if (onLoad) {
  9588. texture.onLoadedCallbacks.push(onLoad);
  9589. }
  9590. if (!fallBack)
  9591. this._loadedTexturesCache.push(texture);
  9592. var onerror = function () {
  9593. scene._removePendingData(texture);
  9594. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9595. if (isKTX) {
  9596. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  9597. }
  9598. else if (onError) {
  9599. onError();
  9600. }
  9601. };
  9602. var callback;
  9603. if (isKTX || isTGA || isDDS) {
  9604. if (isKTX) {
  9605. callback = function (data) {
  9606. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9607. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9608. ktx.uploadLevels(_this._gl, !noMipmap);
  9609. }, samplingMode);
  9610. };
  9611. }
  9612. else if (isTGA) {
  9613. callback = function (arrayBuffer) {
  9614. var data = new Uint8Array(arrayBuffer);
  9615. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9616. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9617. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9618. }, samplingMode);
  9619. };
  9620. }
  9621. else if (isDDS) {
  9622. callback = function (data) {
  9623. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9624. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9625. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9626. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9627. }, samplingMode);
  9628. };
  9629. }
  9630. if (!(fromData instanceof Array))
  9631. BABYLON.Tools.LoadFile(url, function (data) {
  9632. callback(data);
  9633. }, null, scene.database, true, onerror);
  9634. else
  9635. callback(buffer);
  9636. }
  9637. else {
  9638. var onload = function (img) {
  9639. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9640. var isPot = (img.width === potWidth && img.height === potHeight);
  9641. if (!isPot) {
  9642. _this._prepareWorkingCanvas();
  9643. _this._workingCanvas.width = potWidth;
  9644. _this._workingCanvas.height = potHeight;
  9645. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9646. _this._workingContext.imageSmoothingEnabled = false;
  9647. _this._workingContext.mozImageSmoothingEnabled = false;
  9648. _this._workingContext.oImageSmoothingEnabled = false;
  9649. _this._workingContext.webkitImageSmoothingEnabled = false;
  9650. _this._workingContext.msImageSmoothingEnabled = false;
  9651. }
  9652. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9653. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9654. _this._workingContext.imageSmoothingEnabled = true;
  9655. _this._workingContext.mozImageSmoothingEnabled = true;
  9656. _this._workingContext.oImageSmoothingEnabled = true;
  9657. _this._workingContext.webkitImageSmoothingEnabled = true;
  9658. _this._workingContext.msImageSmoothingEnabled = true;
  9659. }
  9660. }
  9661. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9662. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9663. }, samplingMode);
  9664. };
  9665. if (!(fromData instanceof Array))
  9666. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9667. else
  9668. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9669. }
  9670. return texture;
  9671. };
  9672. Engine.prototype._getInternalFormat = function (format) {
  9673. var internalFormat = this._gl.RGBA;
  9674. switch (format) {
  9675. case Engine.TEXTUREFORMAT_ALPHA:
  9676. internalFormat = this._gl.ALPHA;
  9677. break;
  9678. case Engine.TEXTUREFORMAT_LUMINANCE:
  9679. internalFormat = this._gl.LUMINANCE;
  9680. break;
  9681. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9682. internalFormat = this._gl.LUMINANCE_ALPHA;
  9683. break;
  9684. case Engine.TEXTUREFORMAT_RGB:
  9685. internalFormat = this._gl.RGB;
  9686. break;
  9687. case Engine.TEXTUREFORMAT_RGBA:
  9688. internalFormat = this._gl.RGBA;
  9689. break;
  9690. }
  9691. return internalFormat;
  9692. };
  9693. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9694. if (compression === void 0) { compression = null; }
  9695. var internalFormat = this._getInternalFormat(format);
  9696. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9697. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9698. if (texture._width % 4 !== 0) {
  9699. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9700. }
  9701. if (compression) {
  9702. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9703. }
  9704. else {
  9705. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9706. }
  9707. if (texture.generateMipMaps) {
  9708. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9709. }
  9710. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9711. this.resetTextureCache();
  9712. texture.isReady = true;
  9713. };
  9714. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9715. if (compression === void 0) { compression = null; }
  9716. var texture = this._gl.createTexture();
  9717. texture._baseWidth = width;
  9718. texture._baseHeight = height;
  9719. texture._width = width;
  9720. texture._height = height;
  9721. texture.references = 1;
  9722. this.updateRawTexture(texture, data, format, invertY, compression);
  9723. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9724. // Filters
  9725. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9726. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9727. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9728. if (generateMipMaps) {
  9729. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9730. }
  9731. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9732. texture.samplingMode = samplingMode;
  9733. this._loadedTexturesCache.push(texture);
  9734. return texture;
  9735. };
  9736. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9737. var texture = this._gl.createTexture();
  9738. texture._baseWidth = width;
  9739. texture._baseHeight = height;
  9740. if (generateMipMaps) {
  9741. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9742. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9743. }
  9744. this.resetTextureCache();
  9745. texture._width = width;
  9746. texture._height = height;
  9747. texture.isReady = false;
  9748. texture.generateMipMaps = generateMipMaps;
  9749. texture.references = 1;
  9750. texture.samplingMode = samplingMode;
  9751. this.updateTextureSamplingMode(samplingMode, texture);
  9752. this._loadedTexturesCache.push(texture);
  9753. return texture;
  9754. };
  9755. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9756. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9757. if (texture.isCube) {
  9758. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9759. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9760. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9761. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9762. }
  9763. else {
  9764. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9765. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9766. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9767. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9768. }
  9769. texture.samplingMode = samplingMode;
  9770. };
  9771. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9772. if (premulAlpha === void 0) { premulAlpha = false; }
  9773. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9774. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9775. if (premulAlpha) {
  9776. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9777. }
  9778. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9779. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9780. if (texture.generateMipMaps) {
  9781. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9782. }
  9783. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9784. if (premulAlpha) {
  9785. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9786. }
  9787. this.resetTextureCache();
  9788. texture.isReady = true;
  9789. };
  9790. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9791. if (texture._isDisabled) {
  9792. return;
  9793. }
  9794. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9795. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9796. try {
  9797. // Testing video texture support
  9798. if (this._videoTextureSupported === undefined) {
  9799. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9800. if (this._gl.getError() !== 0) {
  9801. this._videoTextureSupported = false;
  9802. }
  9803. else {
  9804. this._videoTextureSupported = true;
  9805. }
  9806. }
  9807. // Copy video through the current working canvas if video texture is not supported
  9808. if (!this._videoTextureSupported) {
  9809. if (!texture._workingCanvas) {
  9810. texture._workingCanvas = document.createElement("canvas");
  9811. texture._workingContext = texture._workingCanvas.getContext("2d");
  9812. texture._workingCanvas.width = texture._width;
  9813. texture._workingCanvas.height = texture._height;
  9814. }
  9815. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9816. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9817. }
  9818. else {
  9819. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9820. }
  9821. if (texture.generateMipMaps) {
  9822. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9823. }
  9824. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9825. this.resetTextureCache();
  9826. texture.isReady = true;
  9827. }
  9828. catch (ex) {
  9829. // Something unexpected
  9830. // Let's disable the texture
  9831. texture._isDisabled = true;
  9832. }
  9833. };
  9834. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9835. // old version had a "generateMipMaps" arg instead of options.
  9836. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9837. // in the same way, generateDepthBuffer is defaulted to true
  9838. var generateMipMaps = false;
  9839. var generateDepthBuffer = true;
  9840. var generateStencilBuffer = false;
  9841. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9842. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9843. if (options !== undefined) {
  9844. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9845. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9846. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9847. type = options.type === undefined ? type : options.type;
  9848. if (options.samplingMode !== undefined) {
  9849. samplingMode = options.samplingMode;
  9850. }
  9851. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9852. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9853. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9854. }
  9855. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9856. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9857. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9858. }
  9859. }
  9860. var gl = this._gl;
  9861. var texture = gl.createTexture();
  9862. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9863. var width = size.width || size;
  9864. var height = size.height || size;
  9865. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9866. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9867. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9868. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9869. }
  9870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9871. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9872. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9874. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9875. // Create the framebuffer
  9876. var framebuffer = gl.createFramebuffer();
  9877. this.bindUnboundFramebuffer(framebuffer);
  9878. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9879. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9880. if (generateMipMaps) {
  9881. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9882. }
  9883. // Unbind
  9884. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9885. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9886. this.bindUnboundFramebuffer(null);
  9887. texture._framebuffer = framebuffer;
  9888. texture._baseWidth = width;
  9889. texture._baseHeight = height;
  9890. texture._width = width;
  9891. texture._height = height;
  9892. texture.isReady = true;
  9893. texture.samples = 1;
  9894. texture.generateMipMaps = generateMipMaps;
  9895. texture.references = 1;
  9896. texture.samplingMode = samplingMode;
  9897. texture.type = type;
  9898. texture._generateDepthBuffer = generateDepthBuffer;
  9899. texture._generateStencilBuffer = generateStencilBuffer;
  9900. this.resetTextureCache();
  9901. this._loadedTexturesCache.push(texture);
  9902. return texture;
  9903. };
  9904. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9905. if (samples === void 0) { samples = 1; }
  9906. var depthStencilBuffer = null;
  9907. var gl = this._gl;
  9908. // Create the depth/stencil buffer
  9909. if (generateStencilBuffer) {
  9910. depthStencilBuffer = gl.createRenderbuffer();
  9911. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9912. if (samples > 1) {
  9913. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9914. }
  9915. else {
  9916. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9917. }
  9918. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9919. }
  9920. else if (generateDepthBuffer) {
  9921. depthStencilBuffer = gl.createRenderbuffer();
  9922. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9923. if (samples > 1) {
  9924. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9925. }
  9926. else {
  9927. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9928. }
  9929. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9930. }
  9931. return depthStencilBuffer;
  9932. };
  9933. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9934. if (this.webGLVersion < 2) {
  9935. return 1;
  9936. }
  9937. if (texture.samples === samples) {
  9938. return samples;
  9939. }
  9940. var gl = this._gl;
  9941. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9942. // Dispose previous render buffers
  9943. if (texture._depthStencilBuffer) {
  9944. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9945. }
  9946. if (texture._MSAAFramebuffer) {
  9947. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9948. }
  9949. if (texture._MSAARenderBuffer) {
  9950. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9951. }
  9952. if (samples > 1) {
  9953. texture._MSAAFramebuffer = gl.createFramebuffer();
  9954. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9955. var colorRenderbuffer = gl.createRenderbuffer();
  9956. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9957. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9958. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9959. texture._MSAARenderBuffer = colorRenderbuffer;
  9960. }
  9961. else {
  9962. this.bindUnboundFramebuffer(texture._framebuffer);
  9963. }
  9964. texture.samples = samples;
  9965. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9966. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9967. this.bindUnboundFramebuffer(null);
  9968. return samples;
  9969. };
  9970. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9971. var gl = this._gl;
  9972. var texture = gl.createTexture();
  9973. var generateMipMaps = true;
  9974. var generateDepthBuffer = true;
  9975. var generateStencilBuffer = false;
  9976. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9977. if (options !== undefined) {
  9978. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9979. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9980. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9981. if (options.samplingMode !== undefined) {
  9982. samplingMode = options.samplingMode;
  9983. }
  9984. }
  9985. texture.isCube = true;
  9986. texture.references = 1;
  9987. texture.generateMipMaps = generateMipMaps;
  9988. texture.references = 1;
  9989. texture.samples = 1;
  9990. texture.samplingMode = samplingMode;
  9991. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9992. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9993. for (var face = 0; face < 6; face++) {
  9994. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9995. }
  9996. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9997. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9998. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9999. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10000. // Create the framebuffer
  10001. var framebuffer = gl.createFramebuffer();
  10002. this.bindUnboundFramebuffer(framebuffer);
  10003. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10004. // Mipmaps
  10005. if (texture.generateMipMaps) {
  10006. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10007. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10008. }
  10009. // Unbind
  10010. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10011. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10012. this.bindUnboundFramebuffer(null);
  10013. texture._framebuffer = framebuffer;
  10014. texture._width = size;
  10015. texture._height = size;
  10016. texture.isReady = true;
  10017. this.resetTextureCache();
  10018. this._loadedTexturesCache.push(texture);
  10019. return texture;
  10020. };
  10021. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  10022. var _this = this;
  10023. if (onLoad === void 0) { onLoad = null; }
  10024. if (onError === void 0) { onError = null; }
  10025. var gl = this._gl;
  10026. var texture = gl.createTexture();
  10027. texture.isCube = true;
  10028. texture.url = rootUrl;
  10029. texture.references = 1;
  10030. texture.onLoadedCallbacks = [];
  10031. var isKTX = false;
  10032. var lastDot = rootUrl.lastIndexOf('.');
  10033. var extension = rootUrl.substring(lastDot).toLowerCase();
  10034. if (this._textureFormatInUse) {
  10035. extension = this._textureFormatInUse;
  10036. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10037. isKTX = true;
  10038. }
  10039. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10040. if (isKTX) {
  10041. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10042. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10043. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10044. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10045. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10046. ktx.uploadLevels(_this._gl, !noMipmap);
  10047. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10048. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10049. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10050. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10051. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10052. _this.resetTextureCache();
  10053. texture._width = ktx.pixelWidth;
  10054. texture._height = ktx.pixelHeight;
  10055. texture.isReady = true;
  10056. }, null, null, true, onError);
  10057. }
  10058. else if (isDDS) {
  10059. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10060. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10061. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10062. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10063. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10064. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  10065. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10066. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10067. }
  10068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10070. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10072. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10073. _this.resetTextureCache();
  10074. texture._width = info.width;
  10075. texture._height = info.height;
  10076. texture.isReady = true;
  10077. }, null, null, true, onError);
  10078. }
  10079. else {
  10080. cascadeLoad(rootUrl, scene, function (imgs) {
  10081. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  10082. var height = width;
  10083. _this._prepareWorkingCanvas();
  10084. _this._workingCanvas.width = width;
  10085. _this._workingCanvas.height = height;
  10086. var faces = [
  10087. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10088. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10089. ];
  10090. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10091. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10092. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10093. for (var index = 0; index < faces.length; index++) {
  10094. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10095. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10096. }
  10097. if (!noMipmap) {
  10098. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10099. }
  10100. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10101. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10102. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10104. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10105. _this.resetTextureCache();
  10106. texture._width = width;
  10107. texture._height = height;
  10108. texture.isReady = true;
  10109. texture.onLoadedCallbacks.forEach(function (callback) {
  10110. callback();
  10111. });
  10112. if (onLoad) {
  10113. onLoad();
  10114. }
  10115. }, files, onError);
  10116. }
  10117. this._loadedTexturesCache.push(texture);
  10118. return texture;
  10119. };
  10120. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10121. texture._width = width;
  10122. texture._height = height;
  10123. texture._size = width * height;
  10124. texture._baseWidth = width;
  10125. texture._baseHeight = height;
  10126. };
  10127. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  10128. var _this = this;
  10129. if (onLoad === void 0) { onLoad = null; }
  10130. if (onError === void 0) { onError = null; }
  10131. var gl = this._gl;
  10132. var texture = gl.createTexture();
  10133. scene._addPendingData(texture);
  10134. texture.isCube = true;
  10135. texture.references = 1;
  10136. texture.url = url;
  10137. var textureType = gl.UNSIGNED_BYTE;
  10138. if (type === Engine.TEXTURETYPE_FLOAT) {
  10139. textureType = gl.FLOAT;
  10140. }
  10141. var internalFormat = this._getInternalFormat(format);
  10142. var needConversion = false;
  10143. if (internalFormat === gl.RGB) {
  10144. internalFormat = gl.RGBA;
  10145. needConversion = true;
  10146. }
  10147. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10148. var width = size;
  10149. var height = width;
  10150. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10151. texture._width = width;
  10152. texture._height = height;
  10153. var onerror = function () {
  10154. scene._removePendingData(texture);
  10155. if (onError) {
  10156. onError();
  10157. }
  10158. };
  10159. var internalCallback = function (data) {
  10160. var rgbeDataArrays = callback(data);
  10161. var facesIndex = [
  10162. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10163. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10164. ];
  10165. width = texture._width;
  10166. height = texture._height;
  10167. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10168. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10169. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10170. if (mipmmapGenerator) {
  10171. var arrayTemp = [];
  10172. // Data are known to be in +X +Y +Z -X -Y -Z
  10173. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  10174. arrayTemp.push(rgbeDataArrays[0]); // +X
  10175. arrayTemp.push(rgbeDataArrays[3]); // -X
  10176. arrayTemp.push(rgbeDataArrays[1]); // +Y
  10177. arrayTemp.push(rgbeDataArrays[4]); // -Y
  10178. arrayTemp.push(rgbeDataArrays[2]); // +Z
  10179. arrayTemp.push(rgbeDataArrays[5]); // -Z
  10180. var mipData = mipmmapGenerator(arrayTemp);
  10181. // mipData is order in +X -X +Y -Y +Z -Z
  10182. var mipFaces = [0, 2, 4, 1, 3, 5];
  10183. for (var level = 0; level < mipData.length; level++) {
  10184. var mipSize = width >> level;
  10185. for (var mipIndex in mipFaces) {
  10186. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  10187. if (needConversion) {
  10188. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10189. }
  10190. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10191. }
  10192. }
  10193. }
  10194. else {
  10195. // Data are known to be in +X +Y +Z -X -Y -Z
  10196. for (var index = 0; index < facesIndex.length; index++) {
  10197. var faceData = rgbeDataArrays[index];
  10198. if (needConversion) {
  10199. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  10200. }
  10201. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  10202. }
  10203. if (!noMipmap && isPot) {
  10204. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10205. }
  10206. else {
  10207. noMipmap = true;
  10208. }
  10209. }
  10210. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  10211. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10212. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10213. }
  10214. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  10215. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10216. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10217. }
  10218. else {
  10219. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10221. }
  10222. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10223. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10224. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10225. texture.isReady = true;
  10226. _this.resetTextureCache();
  10227. scene._removePendingData(texture);
  10228. if (onLoad) {
  10229. onLoad();
  10230. }
  10231. };
  10232. BABYLON.Tools.LoadFile(url, function (data) {
  10233. internalCallback(data);
  10234. }, onerror, scene.database, true);
  10235. return texture;
  10236. };
  10237. ;
  10238. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10239. // Create new RGBA data container.
  10240. var rgbaData;
  10241. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10242. rgbaData = new Float32Array(width * height * 4);
  10243. }
  10244. else {
  10245. rgbaData = new Uint32Array(width * height * 4);
  10246. }
  10247. // Convert each pixel.
  10248. for (var x = 0; x < width; x++) {
  10249. for (var y = 0; y < height; y++) {
  10250. var index = (y * width + x) * 3;
  10251. var newIndex = (y * width + x) * 4;
  10252. // Map Old Value to new value.
  10253. rgbaData[newIndex + 0] = rgbData[index + 0];
  10254. rgbaData[newIndex + 1] = rgbData[index + 1];
  10255. rgbaData[newIndex + 2] = rgbData[index + 2];
  10256. // Add fully opaque alpha channel.
  10257. rgbaData[newIndex + 3] = 1;
  10258. }
  10259. }
  10260. return rgbaData;
  10261. };
  10262. Engine.prototype._releaseTexture = function (texture) {
  10263. var gl = this._gl;
  10264. if (texture._framebuffer) {
  10265. gl.deleteFramebuffer(texture._framebuffer);
  10266. }
  10267. if (texture._depthStencilBuffer) {
  10268. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10269. }
  10270. if (texture._MSAAFramebuffer) {
  10271. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10272. }
  10273. if (texture._MSAARenderBuffer) {
  10274. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10275. }
  10276. gl.deleteTexture(texture);
  10277. // Unbind channels
  10278. this.unbindAllTextures();
  10279. var index = this._loadedTexturesCache.indexOf(texture);
  10280. if (index !== -1) {
  10281. this._loadedTexturesCache.splice(index, 1);
  10282. }
  10283. };
  10284. Engine.prototype.setProgram = function (program) {
  10285. if (this._currentProgram !== program) {
  10286. this._gl.useProgram(program);
  10287. this._currentProgram = program;
  10288. }
  10289. };
  10290. Engine.prototype.bindSamplers = function (effect) {
  10291. this.setProgram(effect.getProgram());
  10292. var samplers = effect.getSamplers();
  10293. for (var index = 0; index < samplers.length; index++) {
  10294. var uniform = effect.getUniform(samplers[index]);
  10295. this._gl.uniform1i(uniform, index);
  10296. }
  10297. this._currentEffect = null;
  10298. };
  10299. Engine.prototype.activateTexture = function (texture) {
  10300. if (this._activeTexture !== texture) {
  10301. this._gl.activeTexture(texture);
  10302. this._activeTexture = texture;
  10303. }
  10304. };
  10305. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10306. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10307. this._gl.bindTexture(target, texture);
  10308. this._activeTexturesCache[this._activeTexture] = texture;
  10309. }
  10310. };
  10311. Engine.prototype._bindTexture = function (channel, texture) {
  10312. if (channel < 0) {
  10313. return;
  10314. }
  10315. this.activateTexture(this._gl.TEXTURE0 + channel);
  10316. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10317. };
  10318. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10319. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10320. };
  10321. Engine.prototype.unbindAllTextures = function () {
  10322. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10323. this.activateTexture(this._gl["TEXTURE" + channel]);
  10324. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10325. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10326. }
  10327. };
  10328. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10329. if (channel < 0) {
  10330. return;
  10331. }
  10332. this._gl.uniform1i(uniform, channel);
  10333. this._setTexture(channel, texture);
  10334. };
  10335. Engine.prototype._setTexture = function (channel, texture) {
  10336. // Not ready?
  10337. if (!texture || !texture.isReady()) {
  10338. if (this._activeTexturesCache[channel] != null) {
  10339. this.activateTexture(this._gl["TEXTURE" + channel]);
  10340. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10341. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10342. }
  10343. return;
  10344. }
  10345. // Video
  10346. var alreadyActivated = false;
  10347. if (texture instanceof BABYLON.VideoTexture) {
  10348. this.activateTexture(this._gl["TEXTURE" + channel]);
  10349. alreadyActivated = true;
  10350. texture.update();
  10351. }
  10352. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10353. texture.delayLoad();
  10354. return;
  10355. }
  10356. var internalTexture = texture.getInternalTexture();
  10357. if (this._activeTexturesCache[channel] === internalTexture) {
  10358. return;
  10359. }
  10360. if (!alreadyActivated) {
  10361. this.activateTexture(this._gl["TEXTURE" + channel]);
  10362. }
  10363. if (internalTexture.isCube) {
  10364. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10365. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10366. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10367. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10368. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10369. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10370. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10371. }
  10372. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10373. }
  10374. else {
  10375. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10376. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10377. internalTexture._cachedWrapU = texture.wrapU;
  10378. switch (texture.wrapU) {
  10379. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10380. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10381. break;
  10382. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10383. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10384. break;
  10385. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10386. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10387. break;
  10388. }
  10389. }
  10390. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10391. internalTexture._cachedWrapV = texture.wrapV;
  10392. switch (texture.wrapV) {
  10393. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10394. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10395. break;
  10396. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10397. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10398. break;
  10399. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10400. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10401. break;
  10402. }
  10403. }
  10404. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10405. }
  10406. };
  10407. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10408. if (channel < 0) {
  10409. return;
  10410. }
  10411. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10412. this._textureUnits = new Int32Array(textures.length);
  10413. }
  10414. for (var i = 0; i < textures.length; i++) {
  10415. this._textureUnits[i] = channel + i;
  10416. }
  10417. this._gl.uniform1iv(uniform, this._textureUnits);
  10418. for (var index = 0; index < textures.length; index++) {
  10419. this._setTexture(channel + index, textures[index]);
  10420. }
  10421. };
  10422. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10423. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10424. var value = texture.anisotropicFilteringLevel;
  10425. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10426. value = 1;
  10427. }
  10428. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10429. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10430. texture._cachedAnisotropicFilteringLevel = value;
  10431. }
  10432. };
  10433. Engine.prototype.readPixels = function (x, y, width, height) {
  10434. var data = new Uint8Array(height * width * 4);
  10435. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10436. return data;
  10437. };
  10438. /**
  10439. * Add an externaly attached data from its key.
  10440. * This method call will fail and return false, if such key already exists.
  10441. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10442. * @param key the unique key that identifies the data
  10443. * @param data the data object to associate to the key for this Engine instance
  10444. * @return true if no such key were already present and the data was added successfully, false otherwise
  10445. */
  10446. Engine.prototype.addExternalData = function (key, data) {
  10447. return this._externalData.add(key, data);
  10448. };
  10449. /**
  10450. * Get an externaly attached data from its key
  10451. * @param key the unique key that identifies the data
  10452. * @return the associated data, if present (can be null), or undefined if not present
  10453. */
  10454. Engine.prototype.getExternalData = function (key) {
  10455. return this._externalData.get(key);
  10456. };
  10457. /**
  10458. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10459. * @param key the unique key that identifies the data
  10460. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10461. * @return the associated data, can be null if the factory returned null.
  10462. */
  10463. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10464. return this._externalData.getOrAddWithFactory(key, factory);
  10465. };
  10466. /**
  10467. * Remove an externaly attached data from the Engine instance
  10468. * @param key the unique key that identifies the data
  10469. * @return true if the data was successfully removed, false if it doesn't exist
  10470. */
  10471. Engine.prototype.removeExternalData = function (key) {
  10472. return this._externalData.remove(key);
  10473. };
  10474. Engine.prototype.releaseInternalTexture = function (texture) {
  10475. if (!texture) {
  10476. return;
  10477. }
  10478. texture.references--;
  10479. // Final reference ?
  10480. if (texture.references === 0) {
  10481. var texturesCache = this.getLoadedTexturesCache();
  10482. var index = texturesCache.indexOf(texture);
  10483. if (index > -1) {
  10484. texturesCache.splice(index, 1);
  10485. }
  10486. this._releaseTexture(texture);
  10487. }
  10488. };
  10489. Engine.prototype.unbindAllAttributes = function () {
  10490. if (this._mustWipeVertexAttributes) {
  10491. this._mustWipeVertexAttributes = false;
  10492. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10493. this._gl.disableVertexAttribArray(i);
  10494. this._vertexAttribArraysEnabled[i] = false;
  10495. this._currentBufferPointers[i] = null;
  10496. }
  10497. return;
  10498. }
  10499. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10500. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10501. continue;
  10502. }
  10503. this._gl.disableVertexAttribArray(i);
  10504. this._vertexAttribArraysEnabled[i] = false;
  10505. this._currentBufferPointers[i] = null;
  10506. }
  10507. };
  10508. // Dispose
  10509. Engine.prototype.dispose = function () {
  10510. this.hideLoadingUI();
  10511. this.stopRenderLoop();
  10512. // Release scenes
  10513. while (this.scenes.length) {
  10514. this.scenes[0].dispose();
  10515. }
  10516. // Release audio engine
  10517. Engine.audioEngine.dispose();
  10518. // Release effects
  10519. for (var name in this._compiledEffects) {
  10520. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10521. }
  10522. // Unbind
  10523. this.unbindAllAttributes();
  10524. this._gl = null;
  10525. //WebVR
  10526. this.disableVR();
  10527. // Events
  10528. window.removeEventListener("blur", this._onBlur);
  10529. window.removeEventListener("focus", this._onFocus);
  10530. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10531. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10532. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10533. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10534. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10535. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10536. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10537. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10538. // Remove from Instances
  10539. var index = Engine.Instances.indexOf(this);
  10540. if (index >= 0) {
  10541. Engine.Instances.splice(index, 1);
  10542. }
  10543. };
  10544. // Loading screen
  10545. Engine.prototype.displayLoadingUI = function () {
  10546. this._loadingScreen.displayLoadingUI();
  10547. };
  10548. Engine.prototype.hideLoadingUI = function () {
  10549. this._loadingScreen.hideLoadingUI();
  10550. };
  10551. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10552. get: function () {
  10553. return this._loadingScreen;
  10554. },
  10555. set: function (loadingScreen) {
  10556. this._loadingScreen = loadingScreen;
  10557. },
  10558. enumerable: true,
  10559. configurable: true
  10560. });
  10561. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10562. set: function (text) {
  10563. this._loadingScreen.loadingUIText = text;
  10564. },
  10565. enumerable: true,
  10566. configurable: true
  10567. });
  10568. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10569. set: function (color) {
  10570. this._loadingScreen.loadingUIBackgroundColor = color;
  10571. },
  10572. enumerable: true,
  10573. configurable: true
  10574. });
  10575. Engine.prototype.attachContextLostEvent = function (callback) {
  10576. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10577. };
  10578. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10579. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10580. };
  10581. Engine.prototype.getVertexShaderSource = function (program) {
  10582. var shaders = this._gl.getAttachedShaders(program);
  10583. return this._gl.getShaderSource(shaders[0]);
  10584. };
  10585. Engine.prototype.getFragmentShaderSource = function (program) {
  10586. var shaders = this._gl.getAttachedShaders(program);
  10587. return this._gl.getShaderSource(shaders[1]);
  10588. };
  10589. // FPS
  10590. Engine.prototype.getFps = function () {
  10591. return this.fps;
  10592. };
  10593. Engine.prototype.getDeltaTime = function () {
  10594. return this.deltaTime;
  10595. };
  10596. Engine.prototype._measureFps = function () {
  10597. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10598. var length = this.previousFramesDuration.length;
  10599. if (length >= 2) {
  10600. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10601. }
  10602. if (length >= this.fpsRange) {
  10603. if (length > this.fpsRange) {
  10604. this.previousFramesDuration.splice(0, 1);
  10605. length = this.previousFramesDuration.length;
  10606. }
  10607. var sum = 0;
  10608. for (var id = 0; id < length - 1; id++) {
  10609. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10610. }
  10611. this.fps = 1000.0 / (sum / (length - 1));
  10612. }
  10613. };
  10614. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10615. if (this._webGLVersion > 1) {
  10616. return this._caps.colorBufferFloat;
  10617. }
  10618. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10619. };
  10620. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10621. if (this._webGLVersion > 1) {
  10622. return this._caps.colorBufferFloat;
  10623. }
  10624. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10625. };
  10626. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10627. Engine.prototype._canRenderToFramebuffer = function (type) {
  10628. var gl = this._gl;
  10629. //clear existing errors
  10630. while (gl.getError() !== gl.NO_ERROR) { }
  10631. var successful = true;
  10632. var texture = gl.createTexture();
  10633. gl.bindTexture(gl.TEXTURE_2D, texture);
  10634. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10635. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10636. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10637. var fb = gl.createFramebuffer();
  10638. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10639. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10640. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10641. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10642. successful = successful && (gl.getError() === gl.NO_ERROR);
  10643. //try render by clearing frame buffer's color buffer
  10644. if (successful) {
  10645. gl.clear(gl.COLOR_BUFFER_BIT);
  10646. successful = successful && (gl.getError() === gl.NO_ERROR);
  10647. }
  10648. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10649. if (successful) {
  10650. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10651. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10652. var readFormat = gl.RGBA;
  10653. var readType = gl.UNSIGNED_BYTE;
  10654. var buffer = new Uint8Array(4);
  10655. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10656. successful = successful && (gl.getError() === gl.NO_ERROR);
  10657. }
  10658. //clean up
  10659. gl.deleteTexture(texture);
  10660. gl.deleteFramebuffer(fb);
  10661. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10662. //clear accumulated errors
  10663. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10664. return successful;
  10665. };
  10666. Engine.prototype._getWebGLTextureType = function (type) {
  10667. if (type === Engine.TEXTURETYPE_FLOAT) {
  10668. return this._gl.FLOAT;
  10669. }
  10670. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10671. // Add Half Float Constant.
  10672. return Engine.HALF_FLOAT_OES;
  10673. }
  10674. return this._gl.UNSIGNED_BYTE;
  10675. };
  10676. ;
  10677. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10678. if (this._webGLVersion === 1) {
  10679. return this._gl.RGBA;
  10680. }
  10681. if (type === Engine.TEXTURETYPE_FLOAT) {
  10682. return Engine.RGBA32F;
  10683. }
  10684. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10685. return Engine.RGBA16F;
  10686. }
  10687. return this._gl.RGBA;
  10688. };
  10689. ;
  10690. // Statics
  10691. Engine.isSupported = function () {
  10692. try {
  10693. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10694. if (navigator.isCocoonJS) {
  10695. return true;
  10696. }
  10697. var tempcanvas = document.createElement("canvas");
  10698. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10699. return gl != null && !!window.WebGLRenderingContext;
  10700. }
  10701. catch (e) {
  10702. return false;
  10703. }
  10704. };
  10705. return Engine;
  10706. }());
  10707. Engine.Instances = new Array();
  10708. // Const statics
  10709. Engine._ALPHA_DISABLE = 0;
  10710. Engine._ALPHA_ADD = 1;
  10711. Engine._ALPHA_COMBINE = 2;
  10712. Engine._ALPHA_SUBTRACT = 3;
  10713. Engine._ALPHA_MULTIPLY = 4;
  10714. Engine._ALPHA_MAXIMIZED = 5;
  10715. Engine._ALPHA_ONEONE = 6;
  10716. Engine._ALPHA_PREMULTIPLIED = 7;
  10717. Engine._DELAYLOADSTATE_NONE = 0;
  10718. Engine._DELAYLOADSTATE_LOADED = 1;
  10719. Engine._DELAYLOADSTATE_LOADING = 2;
  10720. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10721. Engine._TEXTUREFORMAT_ALPHA = 0;
  10722. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10723. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10724. Engine._TEXTUREFORMAT_RGB = 4;
  10725. Engine._TEXTUREFORMAT_RGBA = 5;
  10726. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10727. Engine._TEXTURETYPE_FLOAT = 1;
  10728. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10729. // Depht or Stencil test Constants.
  10730. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10731. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  10732. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  10733. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  10734. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  10735. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  10736. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  10737. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  10738. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10739. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10740. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10741. // Stencil Actions Constants.
  10742. Engine._KEEP = 0x1E00;
  10743. Engine._REPLACE = 0x1E01;
  10744. Engine._INCR = 0x1E02;
  10745. Engine._DECR = 0x1E03;
  10746. Engine._INVERT = 0x150A;
  10747. Engine._INCR_WRAP = 0x8507;
  10748. Engine._DECR_WRAP = 0x8508;
  10749. // Updatable statics so stick with vars here
  10750. Engine.CollisionsEpsilon = 0.001;
  10751. Engine.CodeRepository = "src/";
  10752. Engine.ShadersRepository = "src/Shaders/";
  10753. BABYLON.Engine = Engine;
  10754. })(BABYLON || (BABYLON = {}));
  10755. //# sourceMappingURL=babylon.engine.js.map
  10756. /// <reference path="Tools\babylon.decorators.ts" />
  10757. var BABYLON;
  10758. (function (BABYLON) {
  10759. /**
  10760. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10761. */
  10762. var Node = (function () {
  10763. /**
  10764. * @constructor
  10765. * @param {string} name - the name and id to be given to this node
  10766. * @param {BABYLON.Scene} the scene this node will be added to
  10767. */
  10768. function Node(name, scene) {
  10769. this.state = "";
  10770. this.metadata = null;
  10771. this.doNotSerialize = false;
  10772. this.animations = new Array();
  10773. this._ranges = {};
  10774. this._childrenFlag = -1;
  10775. this._isEnabled = true;
  10776. this._isReady = true;
  10777. this._currentRenderId = -1;
  10778. this._parentRenderId = -1;
  10779. /**
  10780. * An event triggered when the mesh is disposed.
  10781. * @type {BABYLON.Observable}
  10782. */
  10783. this.onDisposeObservable = new BABYLON.Observable();
  10784. this.name = name;
  10785. this.id = name;
  10786. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10787. this._initCache();
  10788. }
  10789. Object.defineProperty(Node.prototype, "parent", {
  10790. get: function () {
  10791. return this._parentNode;
  10792. },
  10793. set: function (parent) {
  10794. if (this._parentNode === parent) {
  10795. return;
  10796. }
  10797. if (this._parentNode) {
  10798. var index = this._parentNode._children.indexOf(this);
  10799. if (index !== -1) {
  10800. this._parentNode._children.splice(index, 1);
  10801. }
  10802. }
  10803. this._parentNode = parent;
  10804. if (this._parentNode) {
  10805. if (!this._parentNode._children) {
  10806. this._parentNode._children = new Array();
  10807. }
  10808. this._parentNode._children.push(this);
  10809. }
  10810. },
  10811. enumerable: true,
  10812. configurable: true
  10813. });
  10814. Node.prototype.getClassName = function () {
  10815. return "Node";
  10816. };
  10817. Object.defineProperty(Node.prototype, "onDispose", {
  10818. set: function (callback) {
  10819. if (this._onDisposeObserver) {
  10820. this.onDisposeObservable.remove(this._onDisposeObserver);
  10821. }
  10822. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Node.prototype.getScene = function () {
  10828. return this._scene;
  10829. };
  10830. Node.prototype.getEngine = function () {
  10831. return this._scene.getEngine();
  10832. };
  10833. // override it in derived class
  10834. Node.prototype.getWorldMatrix = function () {
  10835. return BABYLON.Matrix.Identity();
  10836. };
  10837. // override it in derived class if you add new variables to the cache
  10838. // and call the parent class method
  10839. Node.prototype._initCache = function () {
  10840. this._cache = {};
  10841. this._cache.parent = undefined;
  10842. };
  10843. Node.prototype.updateCache = function (force) {
  10844. if (!force && this.isSynchronized())
  10845. return;
  10846. this._cache.parent = this.parent;
  10847. this._updateCache();
  10848. };
  10849. // override it in derived class if you add new variables to the cache
  10850. // and call the parent class method if !ignoreParentClass
  10851. Node.prototype._updateCache = function (ignoreParentClass) {
  10852. };
  10853. // override it in derived class if you add new variables to the cache
  10854. Node.prototype._isSynchronized = function () {
  10855. return true;
  10856. };
  10857. Node.prototype._markSyncedWithParent = function () {
  10858. this._parentRenderId = this.parent._currentRenderId;
  10859. };
  10860. Node.prototype.isSynchronizedWithParent = function () {
  10861. if (!this.parent) {
  10862. return true;
  10863. }
  10864. if (this._parentRenderId !== this.parent._currentRenderId) {
  10865. return false;
  10866. }
  10867. return this.parent.isSynchronized();
  10868. };
  10869. Node.prototype.isSynchronized = function (updateCache) {
  10870. var check = this.hasNewParent();
  10871. check = check || !this.isSynchronizedWithParent();
  10872. check = check || !this._isSynchronized();
  10873. if (updateCache)
  10874. this.updateCache(true);
  10875. return !check;
  10876. };
  10877. Node.prototype.hasNewParent = function (update) {
  10878. if (this._cache.parent === this.parent)
  10879. return false;
  10880. if (update)
  10881. this._cache.parent = this.parent;
  10882. return true;
  10883. };
  10884. /**
  10885. * Is this node ready to be used/rendered
  10886. * @return {boolean} is it ready
  10887. */
  10888. Node.prototype.isReady = function () {
  10889. return this._isReady;
  10890. };
  10891. /**
  10892. * Is this node enabled.
  10893. * If the node has a parent and is enabled, the parent will be inspected as well.
  10894. * @return {boolean} whether this node (and its parent) is enabled.
  10895. * @see setEnabled
  10896. */
  10897. Node.prototype.isEnabled = function () {
  10898. if (!this._isEnabled) {
  10899. return false;
  10900. }
  10901. if (this.parent) {
  10902. return this.parent.isEnabled();
  10903. }
  10904. return true;
  10905. };
  10906. /**
  10907. * Set the enabled state of this node.
  10908. * @param {boolean} value - the new enabled state
  10909. * @see isEnabled
  10910. */
  10911. Node.prototype.setEnabled = function (value) {
  10912. this._isEnabled = value;
  10913. };
  10914. /**
  10915. * Is this node a descendant of the given node.
  10916. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10917. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10918. * @see parent
  10919. */
  10920. Node.prototype.isDescendantOf = function (ancestor) {
  10921. if (this.parent) {
  10922. if (this.parent === ancestor) {
  10923. return true;
  10924. }
  10925. return this.parent.isDescendantOf(ancestor);
  10926. }
  10927. return false;
  10928. };
  10929. /**
  10930. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10931. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10932. * @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.
  10933. * @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.
  10934. */
  10935. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10936. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10937. if (!this._children) {
  10938. return;
  10939. }
  10940. for (var index = 0; index < this._children.length; index++) {
  10941. var item = this._children[index];
  10942. if (!predicate || predicate(item)) {
  10943. results.push(item);
  10944. }
  10945. if (!directDescendantsOnly) {
  10946. item._getDescendants(results, false, predicate);
  10947. }
  10948. }
  10949. };
  10950. /**
  10951. * Will return all nodes that have this node as ascendant.
  10952. * @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.
  10953. * @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.
  10954. * @return {BABYLON.Node[]} all children nodes of all types.
  10955. */
  10956. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10957. var results = [];
  10958. this._getDescendants(results, directDescendantsOnly, predicate);
  10959. return results;
  10960. };
  10961. /**
  10962. * Get all child-meshes of this node.
  10963. */
  10964. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10965. var results = [];
  10966. this._getDescendants(results, directDecendantsOnly, function (node) {
  10967. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10968. });
  10969. return results;
  10970. };
  10971. /**
  10972. * Get all direct children of this node.
  10973. */
  10974. Node.prototype.getChildren = function (predicate) {
  10975. return this.getDescendants(true, predicate);
  10976. };
  10977. Node.prototype._setReady = function (state) {
  10978. if (state === this._isReady) {
  10979. return;
  10980. }
  10981. if (!state) {
  10982. this._isReady = false;
  10983. return;
  10984. }
  10985. this._isReady = true;
  10986. if (this.onReady) {
  10987. this.onReady(this);
  10988. }
  10989. };
  10990. Node.prototype.getAnimationByName = function (name) {
  10991. for (var i = 0; i < this.animations.length; i++) {
  10992. var animation = this.animations[i];
  10993. if (animation.name === name) {
  10994. return animation;
  10995. }
  10996. }
  10997. return null;
  10998. };
  10999. Node.prototype.createAnimationRange = function (name, from, to) {
  11000. // check name not already in use
  11001. if (!this._ranges[name]) {
  11002. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11003. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11004. if (this.animations[i]) {
  11005. this.animations[i].createRange(name, from, to);
  11006. }
  11007. }
  11008. }
  11009. };
  11010. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11011. if (deleteFrames === void 0) { deleteFrames = true; }
  11012. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11013. if (this.animations[i]) {
  11014. this.animations[i].deleteRange(name, deleteFrames);
  11015. }
  11016. }
  11017. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11018. };
  11019. Node.prototype.getAnimationRange = function (name) {
  11020. return this._ranges[name];
  11021. };
  11022. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11023. var range = this.getAnimationRange(name);
  11024. if (!range) {
  11025. return null;
  11026. }
  11027. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11028. };
  11029. Node.prototype.serializeAnimationRanges = function () {
  11030. var serializationRanges = [];
  11031. for (var name in this._ranges) {
  11032. var range = {};
  11033. range.name = name;
  11034. range.from = this._ranges[name].from;
  11035. range.to = this._ranges[name].to;
  11036. serializationRanges.push(range);
  11037. }
  11038. return serializationRanges;
  11039. };
  11040. Node.prototype.dispose = function () {
  11041. this.parent = null;
  11042. // Callback
  11043. this.onDisposeObservable.notifyObservers(this);
  11044. this.onDisposeObservable.clear();
  11045. };
  11046. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11047. if (parsedNode.ranges) {
  11048. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11049. var data = parsedNode.ranges[index];
  11050. node.createAnimationRange(data.name, data.from, data.to);
  11051. }
  11052. }
  11053. };
  11054. return Node;
  11055. }());
  11056. __decorate([
  11057. BABYLON.serialize()
  11058. ], Node.prototype, "name", void 0);
  11059. __decorate([
  11060. BABYLON.serialize()
  11061. ], Node.prototype, "id", void 0);
  11062. __decorate([
  11063. BABYLON.serialize()
  11064. ], Node.prototype, "uniqueId", void 0);
  11065. __decorate([
  11066. BABYLON.serialize()
  11067. ], Node.prototype, "state", void 0);
  11068. __decorate([
  11069. BABYLON.serialize()
  11070. ], Node.prototype, "metadata", void 0);
  11071. BABYLON.Node = Node;
  11072. })(BABYLON || (BABYLON = {}));
  11073. //# sourceMappingURL=babylon.node.js.map
  11074. var BABYLON;
  11075. (function (BABYLON) {
  11076. var FilesInput = (function () {
  11077. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  11078. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  11079. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  11080. this._engine = p_engine;
  11081. this._canvas = p_canvas;
  11082. this._currentScene = p_scene;
  11083. this._sceneLoadedCallback = p_sceneLoadedCallback;
  11084. this._progressCallback = p_progressCallback;
  11085. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  11086. this._textureLoadingCallback = p_textureLoadingCallback;
  11087. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  11088. }
  11089. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  11090. var _this = this;
  11091. if (p_elementToMonitor) {
  11092. this._elementToMonitor = p_elementToMonitor;
  11093. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  11094. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  11095. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  11096. }
  11097. };
  11098. FilesInput.prototype.renderFunction = function () {
  11099. if (this._additionnalRenderLoopLogicCallback) {
  11100. this._additionnalRenderLoopLogicCallback();
  11101. }
  11102. if (this._currentScene) {
  11103. if (this._textureLoadingCallback) {
  11104. var remaining = this._currentScene.getWaitingItemsCount();
  11105. if (remaining > 0) {
  11106. this._textureLoadingCallback(remaining);
  11107. }
  11108. }
  11109. this._currentScene.render();
  11110. }
  11111. };
  11112. FilesInput.prototype.drag = function (e) {
  11113. e.stopPropagation();
  11114. e.preventDefault();
  11115. };
  11116. FilesInput.prototype.drop = function (eventDrop) {
  11117. eventDrop.stopPropagation();
  11118. eventDrop.preventDefault();
  11119. this.loadFiles(eventDrop);
  11120. };
  11121. FilesInput.prototype.loadFiles = function (event) {
  11122. if (this._startingProcessingFilesCallback)
  11123. this._startingProcessingFilesCallback();
  11124. // Handling data transfer via drag'n'drop
  11125. if (event && event.dataTransfer && event.dataTransfer.files) {
  11126. this._filesToLoad = event.dataTransfer.files;
  11127. }
  11128. // Handling files from input files
  11129. if (event && event.target && event.target.files) {
  11130. this._filesToLoad = event.target.files;
  11131. }
  11132. if (this._filesToLoad && this._filesToLoad.length > 0) {
  11133. for (var i = 0; i < this._filesToLoad.length; i++) {
  11134. var name_1 = this._filesToLoad[i].name.toLowerCase();
  11135. var extension = name_1.split('.').pop();
  11136. var type = this._filesToLoad[i].type;
  11137. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  11138. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  11139. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  11140. }
  11141. else {
  11142. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  11143. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  11144. this._sceneFileToLoad = this._filesToLoad[i];
  11145. }
  11146. else {
  11147. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  11148. }
  11149. }
  11150. }
  11151. this.reload();
  11152. }
  11153. };
  11154. FilesInput.prototype.reload = function () {
  11155. var _this = this;
  11156. var that = this;
  11157. // If a ".babylon" file has been provided
  11158. if (this._sceneFileToLoad) {
  11159. if (this._currentScene) {
  11160. if (BABYLON.Tools.errorsCount > 0) {
  11161. BABYLON.Tools.ClearLogCache();
  11162. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  11163. }
  11164. this._engine.stopRenderLoop();
  11165. this._currentScene.dispose();
  11166. }
  11167. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  11168. that._currentScene = newScene;
  11169. // Wait for textures and shaders to be ready
  11170. that._currentScene.executeWhenReady(function () {
  11171. // Attach camera to canvas inputs
  11172. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  11173. that._currentScene.createDefaultCameraOrLight();
  11174. }
  11175. that._currentScene.activeCamera.attachControl(that._canvas);
  11176. if (that._sceneLoadedCallback) {
  11177. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  11178. }
  11179. that._engine.runRenderLoop(function () { that.renderFunction(); });
  11180. });
  11181. }, function (progress) {
  11182. if (_this._progressCallback) {
  11183. _this._progressCallback(progress);
  11184. }
  11185. });
  11186. }
  11187. else {
  11188. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  11189. }
  11190. };
  11191. return FilesInput;
  11192. }());
  11193. FilesInput.FilesTextures = new Array();
  11194. FilesInput.FilesToLoad = new Array();
  11195. BABYLON.FilesInput = FilesInput;
  11196. })(BABYLON || (BABYLON = {}));
  11197. //# sourceMappingURL=babylon.filesInput.js.map
  11198. var BABYLON;
  11199. (function (BABYLON) {
  11200. var IntersectionInfo = (function () {
  11201. function IntersectionInfo(bu, bv, distance) {
  11202. this.bu = bu;
  11203. this.bv = bv;
  11204. this.distance = distance;
  11205. this.faceId = 0;
  11206. this.subMeshId = 0;
  11207. }
  11208. return IntersectionInfo;
  11209. }());
  11210. BABYLON.IntersectionInfo = IntersectionInfo;
  11211. var PickingInfo = (function () {
  11212. function PickingInfo() {
  11213. this.hit = false;
  11214. this.distance = 0;
  11215. this.pickedPoint = null;
  11216. this.pickedMesh = null;
  11217. this.bu = 0;
  11218. this.bv = 0;
  11219. this.faceId = -1;
  11220. this.subMeshId = 0;
  11221. this.pickedSprite = null;
  11222. }
  11223. // Methods
  11224. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  11225. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  11226. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  11227. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11228. return null;
  11229. }
  11230. var indices = this.pickedMesh.getIndices();
  11231. var result;
  11232. if (useVerticesNormals) {
  11233. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11234. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  11235. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  11236. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  11237. normal0 = normal0.scale(this.bu);
  11238. normal1 = normal1.scale(this.bv);
  11239. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  11240. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  11241. }
  11242. else {
  11243. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11244. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  11245. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  11246. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  11247. var p1p2 = vertex1.subtract(vertex2);
  11248. var p3p2 = vertex3.subtract(vertex2);
  11249. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  11250. }
  11251. if (useWorldCoordinates) {
  11252. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  11253. }
  11254. return BABYLON.Vector3.Normalize(result);
  11255. };
  11256. PickingInfo.prototype.getTextureCoordinates = function () {
  11257. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11258. return null;
  11259. }
  11260. var indices = this.pickedMesh.getIndices();
  11261. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11262. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  11263. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  11264. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  11265. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  11266. uv1 = uv1.scale(this.bu);
  11267. uv2 = uv2.scale(this.bv);
  11268. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  11269. };
  11270. return PickingInfo;
  11271. }());
  11272. BABYLON.PickingInfo = PickingInfo;
  11273. })(BABYLON || (BABYLON = {}));
  11274. //# sourceMappingURL=babylon.pickingInfo.js.map
  11275. var BABYLON;
  11276. (function (BABYLON) {
  11277. var BoundingSphere = (function () {
  11278. function BoundingSphere(minimum, maximum) {
  11279. this.minimum = minimum;
  11280. this.maximum = maximum;
  11281. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11282. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11283. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11284. this.radius = distance * 0.5;
  11285. this.centerWorld = BABYLON.Vector3.Zero();
  11286. this._update(BABYLON.Matrix.Identity());
  11287. }
  11288. // Methods
  11289. BoundingSphere.prototype._update = function (world) {
  11290. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11291. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11292. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11293. };
  11294. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11295. for (var i = 0; i < 6; i++) {
  11296. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11297. return false;
  11298. }
  11299. return true;
  11300. };
  11301. BoundingSphere.prototype.intersectsPoint = function (point) {
  11302. var x = this.centerWorld.x - point.x;
  11303. var y = this.centerWorld.y - point.y;
  11304. var z = this.centerWorld.z - point.z;
  11305. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11306. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11307. return false;
  11308. return true;
  11309. };
  11310. // Statics
  11311. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11312. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11313. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11314. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11315. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11316. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11317. return false;
  11318. return true;
  11319. };
  11320. return BoundingSphere;
  11321. }());
  11322. BABYLON.BoundingSphere = BoundingSphere;
  11323. })(BABYLON || (BABYLON = {}));
  11324. //# sourceMappingURL=babylon.boundingSphere.js.map
  11325. var BABYLON;
  11326. (function (BABYLON) {
  11327. var BoundingBox = (function () {
  11328. function BoundingBox(minimum, maximum) {
  11329. this.minimum = minimum;
  11330. this.maximum = maximum;
  11331. this.vectors = new Array();
  11332. this.vectorsWorld = new Array();
  11333. // Bounding vectors
  11334. this.vectors.push(this.minimum.clone());
  11335. this.vectors.push(this.maximum.clone());
  11336. this.vectors.push(this.minimum.clone());
  11337. this.vectors[2].x = this.maximum.x;
  11338. this.vectors.push(this.minimum.clone());
  11339. this.vectors[3].y = this.maximum.y;
  11340. this.vectors.push(this.minimum.clone());
  11341. this.vectors[4].z = this.maximum.z;
  11342. this.vectors.push(this.maximum.clone());
  11343. this.vectors[5].z = this.minimum.z;
  11344. this.vectors.push(this.maximum.clone());
  11345. this.vectors[6].x = this.minimum.x;
  11346. this.vectors.push(this.maximum.clone());
  11347. this.vectors[7].y = this.minimum.y;
  11348. // OBB
  11349. this.center = this.maximum.add(this.minimum).scale(0.5);
  11350. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11351. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11352. // World
  11353. for (var index = 0; index < this.vectors.length; index++) {
  11354. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11355. }
  11356. this.minimumWorld = BABYLON.Vector3.Zero();
  11357. this.maximumWorld = BABYLON.Vector3.Zero();
  11358. this.centerWorld = BABYLON.Vector3.Zero();
  11359. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11360. this._update(BABYLON.Matrix.Identity());
  11361. }
  11362. // Methods
  11363. BoundingBox.prototype.getWorldMatrix = function () {
  11364. return this._worldMatrix;
  11365. };
  11366. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11367. this._worldMatrix.copyFrom(matrix);
  11368. return this;
  11369. };
  11370. BoundingBox.prototype._update = function (world) {
  11371. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11372. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11373. for (var index = 0; index < this.vectors.length; index++) {
  11374. var v = this.vectorsWorld[index];
  11375. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11376. if (v.x < this.minimumWorld.x)
  11377. this.minimumWorld.x = v.x;
  11378. if (v.y < this.minimumWorld.y)
  11379. this.minimumWorld.y = v.y;
  11380. if (v.z < this.minimumWorld.z)
  11381. this.minimumWorld.z = v.z;
  11382. if (v.x > this.maximumWorld.x)
  11383. this.maximumWorld.x = v.x;
  11384. if (v.y > this.maximumWorld.y)
  11385. this.maximumWorld.y = v.y;
  11386. if (v.z > this.maximumWorld.z)
  11387. this.maximumWorld.z = v.z;
  11388. }
  11389. // Extend
  11390. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11391. this.extendSizeWorld.scaleInPlace(0.5);
  11392. // OBB
  11393. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11394. this.centerWorld.scaleInPlace(0.5);
  11395. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11396. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11397. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11398. this._worldMatrix = world;
  11399. };
  11400. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11401. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11402. };
  11403. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11404. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11405. };
  11406. BoundingBox.prototype.intersectsPoint = function (point) {
  11407. var delta = -BABYLON.Epsilon;
  11408. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11409. return false;
  11410. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11411. return false;
  11412. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11413. return false;
  11414. return true;
  11415. };
  11416. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11417. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11418. };
  11419. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11420. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11421. return false;
  11422. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11423. return false;
  11424. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11425. return false;
  11426. return true;
  11427. };
  11428. // Statics
  11429. BoundingBox.Intersects = function (box0, box1) {
  11430. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11431. return false;
  11432. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11433. return false;
  11434. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11435. return false;
  11436. return true;
  11437. };
  11438. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11439. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11440. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11441. return (num <= (sphereRadius * sphereRadius));
  11442. };
  11443. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11444. for (var p = 0; p < 6; p++) {
  11445. for (var i = 0; i < 8; i++) {
  11446. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11447. return false;
  11448. }
  11449. }
  11450. }
  11451. return true;
  11452. };
  11453. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11454. for (var p = 0; p < 6; p++) {
  11455. var inCount = 8;
  11456. for (var i = 0; i < 8; i++) {
  11457. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11458. --inCount;
  11459. }
  11460. else {
  11461. break;
  11462. }
  11463. }
  11464. if (inCount === 0)
  11465. return false;
  11466. }
  11467. return true;
  11468. };
  11469. return BoundingBox;
  11470. }());
  11471. BABYLON.BoundingBox = BoundingBox;
  11472. })(BABYLON || (BABYLON = {}));
  11473. //# sourceMappingURL=babylon.boundingBox.js.map
  11474. var BABYLON;
  11475. (function (BABYLON) {
  11476. var computeBoxExtents = function (axis, box) {
  11477. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11478. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11479. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11480. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11481. var r = r0 + r1 + r2;
  11482. return {
  11483. min: p - r,
  11484. max: p + r
  11485. };
  11486. };
  11487. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11488. var axisOverlap = function (axis, box0, box1) {
  11489. var result0 = computeBoxExtents(axis, box0);
  11490. var result1 = computeBoxExtents(axis, box1);
  11491. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11492. };
  11493. var BoundingInfo = (function () {
  11494. function BoundingInfo(minimum, maximum) {
  11495. this.minimum = minimum;
  11496. this.maximum = maximum;
  11497. this._isLocked = false;
  11498. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11499. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11500. }
  11501. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11502. get: function () {
  11503. return this._isLocked;
  11504. },
  11505. set: function (value) {
  11506. this._isLocked = value;
  11507. },
  11508. enumerable: true,
  11509. configurable: true
  11510. });
  11511. // Methods
  11512. BoundingInfo.prototype.update = function (world) {
  11513. if (this._isLocked) {
  11514. return;
  11515. }
  11516. this.boundingBox._update(world);
  11517. this.boundingSphere._update(world);
  11518. };
  11519. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11520. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11521. return false;
  11522. return this.boundingBox.isInFrustum(frustumPlanes);
  11523. };
  11524. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11525. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11526. };
  11527. BoundingInfo.prototype._checkCollision = function (collider) {
  11528. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11529. };
  11530. BoundingInfo.prototype.intersectsPoint = function (point) {
  11531. if (!this.boundingSphere.centerWorld) {
  11532. return false;
  11533. }
  11534. if (!this.boundingSphere.intersectsPoint(point)) {
  11535. return false;
  11536. }
  11537. if (!this.boundingBox.intersectsPoint(point)) {
  11538. return false;
  11539. }
  11540. return true;
  11541. };
  11542. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11543. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11544. return false;
  11545. }
  11546. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11547. return false;
  11548. }
  11549. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11550. return false;
  11551. }
  11552. if (!precise) {
  11553. return true;
  11554. }
  11555. var box0 = this.boundingBox;
  11556. var box1 = boundingInfo.boundingBox;
  11557. if (!axisOverlap(box0.directions[0], box0, box1))
  11558. return false;
  11559. if (!axisOverlap(box0.directions[1], box0, box1))
  11560. return false;
  11561. if (!axisOverlap(box0.directions[2], box0, box1))
  11562. return false;
  11563. if (!axisOverlap(box1.directions[0], box0, box1))
  11564. return false;
  11565. if (!axisOverlap(box1.directions[1], box0, box1))
  11566. return false;
  11567. if (!axisOverlap(box1.directions[2], box0, box1))
  11568. return false;
  11569. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11570. return false;
  11571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11572. return false;
  11573. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11574. return false;
  11575. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11576. return false;
  11577. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11578. return false;
  11579. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11580. return false;
  11581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11582. return false;
  11583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11584. return false;
  11585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11586. return false;
  11587. return true;
  11588. };
  11589. return BoundingInfo;
  11590. }());
  11591. BABYLON.BoundingInfo = BoundingInfo;
  11592. })(BABYLON || (BABYLON = {}));
  11593. //# sourceMappingURL=babylon.boundingInfo.js.map
  11594. var BABYLON;
  11595. (function (BABYLON) {
  11596. var Ray = (function () {
  11597. function Ray(origin, direction, length) {
  11598. if (length === void 0) { length = Number.MAX_VALUE; }
  11599. this.origin = origin;
  11600. this.direction = direction;
  11601. this.length = length;
  11602. }
  11603. // Methods
  11604. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  11605. var d = 0.0;
  11606. var maxValue = Number.MAX_VALUE;
  11607. var inv;
  11608. var min;
  11609. var max;
  11610. var temp;
  11611. if (Math.abs(this.direction.x) < 0.0000001) {
  11612. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  11613. return false;
  11614. }
  11615. }
  11616. else {
  11617. inv = 1.0 / this.direction.x;
  11618. min = (minimum.x - this.origin.x) * inv;
  11619. max = (maximum.x - this.origin.x) * inv;
  11620. if (max === -Infinity) {
  11621. max = Infinity;
  11622. }
  11623. if (min > max) {
  11624. temp = min;
  11625. min = max;
  11626. max = temp;
  11627. }
  11628. d = Math.max(min, d);
  11629. maxValue = Math.min(max, maxValue);
  11630. if (d > maxValue) {
  11631. return false;
  11632. }
  11633. }
  11634. if (Math.abs(this.direction.y) < 0.0000001) {
  11635. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  11636. return false;
  11637. }
  11638. }
  11639. else {
  11640. inv = 1.0 / this.direction.y;
  11641. min = (minimum.y - this.origin.y) * inv;
  11642. max = (maximum.y - this.origin.y) * inv;
  11643. if (max === -Infinity) {
  11644. max = Infinity;
  11645. }
  11646. if (min > max) {
  11647. temp = min;
  11648. min = max;
  11649. max = temp;
  11650. }
  11651. d = Math.max(min, d);
  11652. maxValue = Math.min(max, maxValue);
  11653. if (d > maxValue) {
  11654. return false;
  11655. }
  11656. }
  11657. if (Math.abs(this.direction.z) < 0.0000001) {
  11658. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  11659. return false;
  11660. }
  11661. }
  11662. else {
  11663. inv = 1.0 / this.direction.z;
  11664. min = (minimum.z - this.origin.z) * inv;
  11665. max = (maximum.z - this.origin.z) * inv;
  11666. if (max === -Infinity) {
  11667. max = Infinity;
  11668. }
  11669. if (min > max) {
  11670. temp = min;
  11671. min = max;
  11672. max = temp;
  11673. }
  11674. d = Math.max(min, d);
  11675. maxValue = Math.min(max, maxValue);
  11676. if (d > maxValue) {
  11677. return false;
  11678. }
  11679. }
  11680. return true;
  11681. };
  11682. Ray.prototype.intersectsBox = function (box) {
  11683. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  11684. };
  11685. Ray.prototype.intersectsSphere = function (sphere) {
  11686. var x = sphere.center.x - this.origin.x;
  11687. var y = sphere.center.y - this.origin.y;
  11688. var z = sphere.center.z - this.origin.z;
  11689. var pyth = (x * x) + (y * y) + (z * z);
  11690. var rr = sphere.radius * sphere.radius;
  11691. if (pyth <= rr) {
  11692. return true;
  11693. }
  11694. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  11695. if (dot < 0.0) {
  11696. return false;
  11697. }
  11698. var temp = pyth - (dot * dot);
  11699. return temp <= rr;
  11700. };
  11701. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  11702. if (!this._edge1) {
  11703. this._edge1 = BABYLON.Vector3.Zero();
  11704. this._edge2 = BABYLON.Vector3.Zero();
  11705. this._pvec = BABYLON.Vector3.Zero();
  11706. this._tvec = BABYLON.Vector3.Zero();
  11707. this._qvec = BABYLON.Vector3.Zero();
  11708. }
  11709. vertex1.subtractToRef(vertex0, this._edge1);
  11710. vertex2.subtractToRef(vertex0, this._edge2);
  11711. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  11712. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  11713. if (det === 0) {
  11714. return null;
  11715. }
  11716. var invdet = 1 / det;
  11717. this.origin.subtractToRef(vertex0, this._tvec);
  11718. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  11719. if (bu < 0 || bu > 1.0) {
  11720. return null;
  11721. }
  11722. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  11723. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  11724. if (bv < 0 || bu + bv > 1.0) {
  11725. return null;
  11726. }
  11727. //check if the distance is longer than the predefined length.
  11728. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  11729. if (distance > this.length) {
  11730. return null;
  11731. }
  11732. return new BABYLON.IntersectionInfo(bu, bv, distance);
  11733. };
  11734. Ray.prototype.intersectsPlane = function (plane) {
  11735. var distance;
  11736. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  11737. if (Math.abs(result1) < 9.99999997475243E-07) {
  11738. return null;
  11739. }
  11740. else {
  11741. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  11742. distance = (-plane.d - result2) / result1;
  11743. if (distance < 0.0) {
  11744. if (distance < -9.99999997475243E-07) {
  11745. return null;
  11746. }
  11747. else {
  11748. return 0;
  11749. }
  11750. }
  11751. return distance;
  11752. }
  11753. };
  11754. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  11755. var tm = BABYLON.Tmp.Matrix[0];
  11756. mesh.getWorldMatrix().invertToRef(tm);
  11757. if (this._tmpRay) {
  11758. Ray.TransformToRef(this, tm, this._tmpRay);
  11759. }
  11760. else {
  11761. this._tmpRay = Ray.Transform(this, tm);
  11762. }
  11763. return mesh.intersects(this._tmpRay, fastCheck);
  11764. };
  11765. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  11766. if (results) {
  11767. results.length = 0;
  11768. }
  11769. else {
  11770. results = [];
  11771. }
  11772. for (var i = 0; i < meshes.length; i++) {
  11773. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  11774. if (pickInfo.hit) {
  11775. results.push(pickInfo);
  11776. }
  11777. }
  11778. results.sort(this._comparePickingInfo);
  11779. return results;
  11780. };
  11781. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  11782. if (pickingInfoA.distance < pickingInfoB.distance) {
  11783. return -1;
  11784. }
  11785. else if (pickingInfoA.distance > pickingInfoB.distance) {
  11786. return 1;
  11787. }
  11788. else {
  11789. return 0;
  11790. }
  11791. };
  11792. /**
  11793. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  11794. * @param sega the first point of the segment to test the intersection against
  11795. * @param segb the second point of the segment to test the intersection against
  11796. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  11797. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  11798. */
  11799. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  11800. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  11801. var u = segb.subtract(sega);
  11802. var v = rsegb.subtract(this.origin);
  11803. var w = sega.subtract(this.origin);
  11804. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  11805. var b = BABYLON.Vector3.Dot(u, v);
  11806. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  11807. var d = BABYLON.Vector3.Dot(u, w);
  11808. var e = BABYLON.Vector3.Dot(v, w);
  11809. var D = a * c - b * b; // always >= 0
  11810. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  11811. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  11812. // compute the line parameters of the two closest points
  11813. if (D < Ray.smallnum) {
  11814. sN = 0.0; // force using point P0 on segment S1
  11815. sD = 1.0; // to prevent possible division by 0.0 later
  11816. tN = e;
  11817. tD = c;
  11818. }
  11819. else {
  11820. sN = (b * e - c * d);
  11821. tN = (a * e - b * d);
  11822. if (sN < 0.0) {
  11823. sN = 0.0;
  11824. tN = e;
  11825. tD = c;
  11826. }
  11827. else if (sN > sD) {
  11828. sN = sD;
  11829. tN = e + b;
  11830. tD = c;
  11831. }
  11832. }
  11833. if (tN < 0.0) {
  11834. tN = 0.0;
  11835. // recompute sc for this edge
  11836. if (-d < 0.0) {
  11837. sN = 0.0;
  11838. }
  11839. else if (-d > a)
  11840. sN = sD;
  11841. else {
  11842. sN = -d;
  11843. sD = a;
  11844. }
  11845. }
  11846. else if (tN > tD) {
  11847. tN = tD;
  11848. // recompute sc for this edge
  11849. if ((-d + b) < 0.0) {
  11850. sN = 0;
  11851. }
  11852. else if ((-d + b) > a) {
  11853. sN = sD;
  11854. }
  11855. else {
  11856. sN = (-d + b);
  11857. sD = a;
  11858. }
  11859. }
  11860. // finally do the division to get sc and tc
  11861. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  11862. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  11863. // get the difference of the two closest points
  11864. var qtc = v.multiplyByFloats(tc, tc, tc);
  11865. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  11866. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  11867. if (isIntersected) {
  11868. return qtc.length();
  11869. }
  11870. return -1;
  11871. };
  11872. // Statics
  11873. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  11874. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  11875. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  11876. var direction = end.subtract(start);
  11877. direction.normalize();
  11878. return new Ray(start, direction);
  11879. };
  11880. /**
  11881. * 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
  11882. * transformed to the given world matrix.
  11883. * @param origin The origin point
  11884. * @param end The end point
  11885. * @param world a matrix to transform the ray to. Default is the identity matrix.
  11886. */
  11887. Ray.CreateNewFromTo = function (origin, end, world) {
  11888. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  11889. var direction = end.subtract(origin);
  11890. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  11891. direction.normalize();
  11892. return Ray.Transform(new Ray(origin, direction, length), world);
  11893. };
  11894. Ray.Transform = function (ray, matrix) {
  11895. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  11896. Ray.TransformToRef(ray, matrix, result);
  11897. return result;
  11898. };
  11899. Ray.TransformToRef = function (ray, matrix, result) {
  11900. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  11901. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  11902. result.length = ray.length;
  11903. var dir = result.direction;
  11904. var len = dir.length();
  11905. if (!(len === 0 || len === 1)) {
  11906. var num = 1.0 / len;
  11907. dir.x *= num;
  11908. dir.y *= num;
  11909. dir.z *= num;
  11910. result.length *= len;
  11911. }
  11912. };
  11913. return Ray;
  11914. }());
  11915. Ray.smallnum = 0.00000001;
  11916. Ray.rayl = 10e8;
  11917. BABYLON.Ray = Ray;
  11918. })(BABYLON || (BABYLON = {}));
  11919. //# sourceMappingURL=babylon.ray.js.map
  11920. var BABYLON;
  11921. (function (BABYLON) {
  11922. var RayHelper = (function () {
  11923. function RayHelper(ray) {
  11924. this.ray = ray;
  11925. }
  11926. RayHelper.CreateAndShow = function (ray, scene, color) {
  11927. var helper = new RayHelper(ray);
  11928. helper.show(scene, color);
  11929. return helper;
  11930. };
  11931. RayHelper.prototype.show = function (scene, color) {
  11932. if (!this._renderFunction) {
  11933. var ray = this.ray;
  11934. this._renderFunction = this._render.bind(this);
  11935. this._scene = scene;
  11936. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  11937. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  11938. this._scene.registerBeforeRender(this._renderFunction);
  11939. }
  11940. if (color) {
  11941. this._renderLine.color.copyFrom(color);
  11942. }
  11943. };
  11944. RayHelper.prototype.hide = function () {
  11945. if (this._renderFunction) {
  11946. this._scene.unregisterBeforeRender(this._renderFunction);
  11947. this._scene = null;
  11948. this._renderFunction = null;
  11949. this._renderLine.dispose();
  11950. this._renderLine = null;
  11951. this._renderPoints = null;
  11952. }
  11953. };
  11954. RayHelper.prototype._render = function () {
  11955. var ray = this.ray;
  11956. var point = this._renderPoints[1];
  11957. var len = Math.min(ray.length, 1000000);
  11958. point.copyFrom(ray.direction);
  11959. point.scaleInPlace(len);
  11960. point.addInPlace(ray.origin);
  11961. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  11962. };
  11963. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  11964. this._attachedToMesh = mesh;
  11965. var ray = this.ray;
  11966. if (!ray.direction) {
  11967. ray.direction = BABYLON.Vector3.Zero();
  11968. }
  11969. if (!ray.origin) {
  11970. ray.origin = BABYLON.Vector3.Zero();
  11971. }
  11972. if (length) {
  11973. ray.length = length;
  11974. }
  11975. if (!meshSpaceOrigin) {
  11976. meshSpaceOrigin = BABYLON.Vector3.Zero();
  11977. }
  11978. if (!meshSpaceDirection) {
  11979. // -1 so that this will work with Mesh.lookAt
  11980. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  11981. }
  11982. if (!this._meshSpaceDirection) {
  11983. this._meshSpaceDirection = meshSpaceDirection.clone();
  11984. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  11985. }
  11986. else {
  11987. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  11988. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  11989. }
  11990. if (!this._updateToMeshFunction) {
  11991. this._updateToMeshFunction = this._updateToMesh.bind(this);
  11992. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  11993. }
  11994. this._updateToMesh();
  11995. };
  11996. RayHelper.prototype.detachFromMesh = function () {
  11997. if (this._attachedToMesh) {
  11998. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  11999. this._attachedToMesh = null;
  12000. this._updateToMeshFunction = null;
  12001. }
  12002. };
  12003. RayHelper.prototype._updateToMesh = function () {
  12004. var ray = this.ray;
  12005. if (this._attachedToMesh._isDisposed) {
  12006. this.detachFromMesh();
  12007. return;
  12008. }
  12009. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  12010. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  12011. };
  12012. RayHelper.prototype.dispose = function () {
  12013. this.hide();
  12014. this.detachFromMesh();
  12015. this.ray = null;
  12016. };
  12017. return RayHelper;
  12018. }());
  12019. BABYLON.RayHelper = RayHelper;
  12020. })(BABYLON || (BABYLON = {}));
  12021. //# sourceMappingURL=babylon.rayHelper.js.map
  12022. var BABYLON;
  12023. (function (BABYLON) {
  12024. var AbstractMesh = (function (_super) {
  12025. __extends(AbstractMesh, _super);
  12026. // Constructor
  12027. function AbstractMesh(name, scene) {
  12028. var _this = _super.call(this, name, scene) || this;
  12029. _this._facetNb = 0; // facet number
  12030. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12031. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12032. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12033. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12034. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12035. _this._subDiv = {
  12036. max: 1,
  12037. X: 1,
  12038. Y: 1,
  12039. Z: 1
  12040. };
  12041. // Events
  12042. /**
  12043. * An event triggered when this mesh collides with another one
  12044. * @type {BABYLON.Observable}
  12045. */
  12046. _this.onCollideObservable = new BABYLON.Observable();
  12047. /**
  12048. * An event triggered when the collision's position changes
  12049. * @type {BABYLON.Observable}
  12050. */
  12051. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12052. /**
  12053. * An event triggered after the world matrix is updated
  12054. * @type {BABYLON.Observable}
  12055. */
  12056. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12057. // Properties
  12058. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12059. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12060. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12061. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  12062. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12063. _this.visibility = 1.0;
  12064. _this.alphaIndex = Number.MAX_VALUE;
  12065. _this.infiniteDistance = false;
  12066. _this.isVisible = true;
  12067. _this.isPickable = true;
  12068. _this.showBoundingBox = false;
  12069. _this.showSubMeshesBoundingBox = false;
  12070. _this.isBlocker = false;
  12071. _this.renderingGroupId = 0;
  12072. _this.receiveShadows = false;
  12073. _this.renderOutline = false;
  12074. _this.outlineColor = BABYLON.Color3.Red();
  12075. _this.outlineWidth = 0.02;
  12076. _this.renderOverlay = false;
  12077. _this.overlayColor = BABYLON.Color3.Red();
  12078. _this.overlayAlpha = 0.5;
  12079. _this.hasVertexAlpha = false;
  12080. _this.useVertexColors = true;
  12081. _this.applyFog = true;
  12082. _this.computeBonesUsingShaders = true;
  12083. _this.scalingDeterminant = 1;
  12084. _this.numBoneInfluencers = 4;
  12085. _this.useOctreeForRenderingSelection = true;
  12086. _this.useOctreeForPicking = true;
  12087. _this.useOctreeForCollisions = true;
  12088. _this.layerMask = 0x0FFFFFFF;
  12089. /**
  12090. * True if the mesh must be rendered in any case.
  12091. */
  12092. _this.alwaysSelectAsActiveMesh = false;
  12093. // Collisions
  12094. _this._checkCollisions = false;
  12095. _this._collisionMask = -1;
  12096. _this._collisionGroup = -1;
  12097. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12098. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12099. _this._collider = new BABYLON.Collider();
  12100. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12101. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12102. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12103. // Edges
  12104. _this.edgesWidth = 1;
  12105. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12106. // Cache
  12107. _this._localWorld = BABYLON.Matrix.Zero();
  12108. _this._worldMatrix = BABYLON.Matrix.Zero();
  12109. _this._absolutePosition = BABYLON.Vector3.Zero();
  12110. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12111. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12112. _this._isDirty = false;
  12113. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12114. _this._isDisposed = false;
  12115. _this._renderId = 0;
  12116. _this._intersectionsInProgress = new Array();
  12117. _this._isWorldMatrixFrozen = false;
  12118. _this._unIndexed = false;
  12119. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12120. if (collidedMesh === void 0) { collidedMesh = null; }
  12121. //TODO move this to the collision coordinator!
  12122. if (_this.getScene().workerCollisions)
  12123. newPosition.multiplyInPlace(_this._collider.radius);
  12124. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12125. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12126. _this.position.addInPlace(_this._diffPositionForCollisions);
  12127. }
  12128. if (collidedMesh) {
  12129. _this.onCollideObservable.notifyObservers(collidedMesh);
  12130. }
  12131. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12132. };
  12133. _this.getScene().addMesh(_this);
  12134. return _this;
  12135. }
  12136. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12137. get: function () {
  12138. return AbstractMesh._BILLBOARDMODE_NONE;
  12139. },
  12140. enumerable: true,
  12141. configurable: true
  12142. });
  12143. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12144. get: function () {
  12145. return AbstractMesh._BILLBOARDMODE_X;
  12146. },
  12147. enumerable: true,
  12148. configurable: true
  12149. });
  12150. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12151. get: function () {
  12152. return AbstractMesh._BILLBOARDMODE_Y;
  12153. },
  12154. enumerable: true,
  12155. configurable: true
  12156. });
  12157. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12158. get: function () {
  12159. return AbstractMesh._BILLBOARDMODE_Z;
  12160. },
  12161. enumerable: true,
  12162. configurable: true
  12163. });
  12164. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12165. get: function () {
  12166. return AbstractMesh._BILLBOARDMODE_ALL;
  12167. },
  12168. enumerable: true,
  12169. configurable: true
  12170. });
  12171. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12172. /**
  12173. * Read-only : the number of facets in the mesh
  12174. */
  12175. get: function () {
  12176. return this._facetNb;
  12177. },
  12178. enumerable: true,
  12179. configurable: true
  12180. });
  12181. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12182. /**
  12183. * The number (integer) of subdivisions per axis in the partioning space
  12184. */
  12185. get: function () {
  12186. return this._partitioningSubdivisions;
  12187. },
  12188. set: function (nb) {
  12189. this._partitioningSubdivisions = nb;
  12190. },
  12191. enumerable: true,
  12192. configurable: true
  12193. });
  12194. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12195. /**
  12196. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12197. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12198. */
  12199. get: function () {
  12200. return this._partitioningBBoxRatio;
  12201. },
  12202. set: function (ratio) {
  12203. this._partitioningBBoxRatio = ratio;
  12204. },
  12205. enumerable: true,
  12206. configurable: true
  12207. });
  12208. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12209. /**
  12210. * Read-only boolean : is the feature facetData enabled ?
  12211. */
  12212. get: function () {
  12213. return this._facetDataEnabled;
  12214. },
  12215. enumerable: true,
  12216. configurable: true
  12217. });
  12218. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12219. set: function (callback) {
  12220. if (this._onCollideObserver) {
  12221. this.onCollideObservable.remove(this._onCollideObserver);
  12222. }
  12223. this._onCollideObserver = this.onCollideObservable.add(callback);
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12229. set: function (callback) {
  12230. if (this._onCollisionPositionChangeObserver) {
  12231. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12232. }
  12233. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12234. },
  12235. enumerable: true,
  12236. configurable: true
  12237. });
  12238. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12239. get: function () {
  12240. return this._collisionMask;
  12241. },
  12242. set: function (mask) {
  12243. this._collisionMask = !isNaN(mask) ? mask : -1;
  12244. },
  12245. enumerable: true,
  12246. configurable: true
  12247. });
  12248. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12249. get: function () {
  12250. return this._collisionGroup;
  12251. },
  12252. set: function (mask) {
  12253. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12254. },
  12255. enumerable: true,
  12256. configurable: true
  12257. });
  12258. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12259. get: function () {
  12260. return this._skeleton;
  12261. },
  12262. set: function (value) {
  12263. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12264. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12265. }
  12266. if (value && value.needInitialSkinMatrix) {
  12267. value._registerMeshWithPoseMatrix(this);
  12268. }
  12269. this._skeleton = value;
  12270. if (!this._skeleton) {
  12271. this._bonesTransformMatrices = null;
  12272. }
  12273. },
  12274. enumerable: true,
  12275. configurable: true
  12276. });
  12277. /**
  12278. * Returns the string "AbstractMesh"
  12279. */
  12280. AbstractMesh.prototype.getClassName = function () {
  12281. return "AbstractMesh";
  12282. };
  12283. /**
  12284. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12285. */
  12286. AbstractMesh.prototype.toString = function (fullDetails) {
  12287. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12288. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12289. if (this._skeleton) {
  12290. ret += ", skeleton: " + this._skeleton.name;
  12291. }
  12292. if (fullDetails) {
  12293. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12294. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12295. }
  12296. return ret;
  12297. };
  12298. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12299. /**
  12300. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12301. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12302. * Default : (0.0, 0.0, 0.0)
  12303. */
  12304. get: function () {
  12305. return this._rotation;
  12306. },
  12307. set: function (newRotation) {
  12308. this._rotation = newRotation;
  12309. },
  12310. enumerable: true,
  12311. configurable: true
  12312. });
  12313. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12314. /**
  12315. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12316. * Default : (1.0, 1.0, 1.0)
  12317. */
  12318. get: function () {
  12319. return this._scaling;
  12320. },
  12321. set: function (newScaling) {
  12322. this._scaling = newScaling;
  12323. if (this.physicsImpostor) {
  12324. this.physicsImpostor.forceUpdate();
  12325. }
  12326. },
  12327. enumerable: true,
  12328. configurable: true
  12329. });
  12330. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12331. /**
  12332. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12333. * It's null by default.
  12334. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  12335. */
  12336. get: function () {
  12337. return this._rotationQuaternion;
  12338. },
  12339. set: function (quaternion) {
  12340. this._rotationQuaternion = quaternion;
  12341. //reset the rotation vector.
  12342. if (quaternion && this.rotation.length()) {
  12343. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12344. }
  12345. },
  12346. enumerable: true,
  12347. configurable: true
  12348. });
  12349. // Methods
  12350. /**
  12351. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12352. * Returns the AbstractMesh.
  12353. */
  12354. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12355. this._poseMatrix.copyFrom(matrix);
  12356. return this;
  12357. };
  12358. /**
  12359. * Returns the mesh Pose matrix.
  12360. * Returned object : Matrix
  12361. */
  12362. AbstractMesh.prototype.getPoseMatrix = function () {
  12363. return this._poseMatrix;
  12364. };
  12365. /**
  12366. * Disables the mesh edger rendering mode.
  12367. * Returns the AbstractMesh.
  12368. */
  12369. AbstractMesh.prototype.disableEdgesRendering = function () {
  12370. if (this._edgesRenderer !== undefined) {
  12371. this._edgesRenderer.dispose();
  12372. this._edgesRenderer = undefined;
  12373. }
  12374. return this;
  12375. };
  12376. /**
  12377. * Enables the edge rendering mode on the mesh.
  12378. * This mode makes the mesh edges visible.
  12379. * Returns the AbstractMesh.
  12380. */
  12381. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12382. if (epsilon === void 0) { epsilon = 0.95; }
  12383. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12384. this.disableEdgesRendering();
  12385. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12386. return this;
  12387. };
  12388. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12389. /**
  12390. * Returns true if the mesh is blocked. Used by the class Mesh.
  12391. * Returns the boolean `false` by default.
  12392. */
  12393. get: function () {
  12394. return false;
  12395. },
  12396. enumerable: true,
  12397. configurable: true
  12398. });
  12399. /**
  12400. * Returns the mesh itself by default, used by the class Mesh.
  12401. * Returned type : AbstractMesh
  12402. */
  12403. AbstractMesh.prototype.getLOD = function (camera) {
  12404. return this;
  12405. };
  12406. /**
  12407. * Returns 0 by default, used by the class Mesh.
  12408. * Returns an integer.
  12409. */
  12410. AbstractMesh.prototype.getTotalVertices = function () {
  12411. return 0;
  12412. };
  12413. /**
  12414. * Returns null by default, used by the class Mesh.
  12415. * Returned type : integer array
  12416. */
  12417. AbstractMesh.prototype.getIndices = function () {
  12418. return null;
  12419. };
  12420. /**
  12421. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12422. * Returned type : float array or Float32Array
  12423. */
  12424. AbstractMesh.prototype.getVerticesData = function (kind) {
  12425. return null;
  12426. };
  12427. /** Returns false by default, used by the class Mesh.
  12428. * Returns a boolean
  12429. */
  12430. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12431. return false;
  12432. };
  12433. /**
  12434. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12435. * Returns a BoundingInfo
  12436. */
  12437. AbstractMesh.prototype.getBoundingInfo = function () {
  12438. if (this._masterMesh) {
  12439. return this._masterMesh.getBoundingInfo();
  12440. }
  12441. if (!this._boundingInfo) {
  12442. this._updateBoundingInfo();
  12443. }
  12444. return this._boundingInfo;
  12445. };
  12446. /**
  12447. * Sets a mesh new object BoundingInfo.
  12448. * Returns the AbstractMesh.
  12449. */
  12450. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12451. this._boundingInfo = boundingInfo;
  12452. return this;
  12453. };
  12454. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12455. get: function () {
  12456. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12457. },
  12458. enumerable: true,
  12459. configurable: true
  12460. });
  12461. AbstractMesh.prototype._preActivate = function () {
  12462. };
  12463. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12464. };
  12465. AbstractMesh.prototype._activate = function (renderId) {
  12466. this._renderId = renderId;
  12467. };
  12468. /**
  12469. * Returns the last update of the World matrix
  12470. * Returns a Matrix.
  12471. */
  12472. AbstractMesh.prototype.getWorldMatrix = function () {
  12473. if (this._masterMesh) {
  12474. return this._masterMesh.getWorldMatrix();
  12475. }
  12476. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12477. this.computeWorldMatrix();
  12478. }
  12479. return this._worldMatrix;
  12480. };
  12481. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12482. /**
  12483. * Returns directly the last state of the mesh World matrix.
  12484. * A Matrix is returned.
  12485. */
  12486. get: function () {
  12487. return this._worldMatrix;
  12488. },
  12489. enumerable: true,
  12490. configurable: true
  12491. });
  12492. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12493. /**
  12494. * Returns the current mesh absolute position.
  12495. * Retuns a Vector3.
  12496. */
  12497. get: function () {
  12498. return this._absolutePosition;
  12499. },
  12500. enumerable: true,
  12501. configurable: true
  12502. });
  12503. /**
  12504. * Prevents the World matrix to be computed any longer.
  12505. * Returns the AbstractMesh.
  12506. */
  12507. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12508. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12509. this.computeWorldMatrix(true);
  12510. this._isWorldMatrixFrozen = true;
  12511. return this;
  12512. };
  12513. /**
  12514. * Allows back the World matrix computation.
  12515. * Returns the AbstractMesh.
  12516. */
  12517. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12518. this._isWorldMatrixFrozen = false;
  12519. this.computeWorldMatrix(true);
  12520. return this;
  12521. };
  12522. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12523. /**
  12524. * True if the World matrix has been frozen.
  12525. * Returns a boolean.
  12526. */
  12527. get: function () {
  12528. return this._isWorldMatrixFrozen;
  12529. },
  12530. enumerable: true,
  12531. configurable: true
  12532. });
  12533. /**
  12534. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12535. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12536. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12537. * The passed axis is also normalized.
  12538. * Returns the AbstractMesh.
  12539. */
  12540. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12541. axis.normalize();
  12542. if (!this.rotationQuaternion) {
  12543. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12544. this.rotation = BABYLON.Vector3.Zero();
  12545. }
  12546. var rotationQuaternion;
  12547. if (!space || space === BABYLON.Space.LOCAL) {
  12548. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12549. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12550. }
  12551. else {
  12552. if (this.parent) {
  12553. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12554. invertParentWorldMatrix.invert();
  12555. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12556. }
  12557. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12558. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12559. }
  12560. return this;
  12561. };
  12562. /**
  12563. * Translates the mesh along the axis vector for the passed distance in the given space.
  12564. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12565. * Returns the AbstractMesh.
  12566. */
  12567. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12568. var displacementVector = axis.scale(distance);
  12569. if (!space || space === BABYLON.Space.LOCAL) {
  12570. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12571. this.setPositionWithLocalVector(tempV3);
  12572. }
  12573. else {
  12574. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12575. }
  12576. return this;
  12577. };
  12578. /**
  12579. * Adds a rotation step to the mesh current rotation.
  12580. * x, y, z are Euler angles expressed in radians.
  12581. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12582. * This means this rotation is made in the mesh local space only.
  12583. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12584. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12585. * ```javascript
  12586. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12587. * ```
  12588. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12589. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  12590. * Returns the AbstractMesh.
  12591. */
  12592. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12593. var rotationQuaternion;
  12594. if (this.rotationQuaternion) {
  12595. rotationQuaternion = this.rotationQuaternion;
  12596. }
  12597. else {
  12598. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12599. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12600. }
  12601. var accumulation = BABYLON.Tmp.Quaternion[0];
  12602. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12603. rotationQuaternion.multiplyInPlace(accumulation);
  12604. if (!this.rotationQuaternion) {
  12605. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12606. }
  12607. return this;
  12608. };
  12609. /**
  12610. * Retuns the mesh absolute position in the World.
  12611. * Returns a Vector3.
  12612. */
  12613. AbstractMesh.prototype.getAbsolutePosition = function () {
  12614. this.computeWorldMatrix();
  12615. return this._absolutePosition;
  12616. };
  12617. /**
  12618. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12619. * Returns the AbstractMesh.
  12620. */
  12621. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12622. if (!absolutePosition) {
  12623. return;
  12624. }
  12625. var absolutePositionX;
  12626. var absolutePositionY;
  12627. var absolutePositionZ;
  12628. if (absolutePosition.x === undefined) {
  12629. if (arguments.length < 3) {
  12630. return;
  12631. }
  12632. absolutePositionX = arguments[0];
  12633. absolutePositionY = arguments[1];
  12634. absolutePositionZ = arguments[2];
  12635. }
  12636. else {
  12637. absolutePositionX = absolutePosition.x;
  12638. absolutePositionY = absolutePosition.y;
  12639. absolutePositionZ = absolutePosition.z;
  12640. }
  12641. if (this.parent) {
  12642. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12643. invertParentWorldMatrix.invert();
  12644. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12645. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12646. }
  12647. else {
  12648. this.position.x = absolutePositionX;
  12649. this.position.y = absolutePositionY;
  12650. this.position.z = absolutePositionZ;
  12651. }
  12652. return this;
  12653. };
  12654. // ================================== Point of View Movement =================================
  12655. /**
  12656. * Perform relative position change from the point of view of behind the front of the mesh.
  12657. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12658. * Supports definition of mesh facing forward or backward.
  12659. * @param {number} amountRight
  12660. * @param {number} amountUp
  12661. * @param {number} amountForward
  12662. *
  12663. * Returns the AbstractMesh.
  12664. */
  12665. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12666. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12667. return this;
  12668. };
  12669. /**
  12670. * Calculate relative position change from the point of view of behind the front of the mesh.
  12671. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12672. * Supports definition of mesh facing forward or backward.
  12673. * @param {number} amountRight
  12674. * @param {number} amountUp
  12675. * @param {number} amountForward
  12676. *
  12677. * Returns a new Vector3.
  12678. */
  12679. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12680. var rotMatrix = new BABYLON.Matrix();
  12681. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12682. rotQuaternion.toRotationMatrix(rotMatrix);
  12683. var translationDelta = BABYLON.Vector3.Zero();
  12684. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12685. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12686. return translationDelta;
  12687. };
  12688. // ================================== Point of View Rotation =================================
  12689. /**
  12690. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12691. * Supports definition of mesh facing forward or backward.
  12692. * @param {number} flipBack
  12693. * @param {number} twirlClockwise
  12694. * @param {number} tiltRight
  12695. *
  12696. * Returns the AbstractMesh.
  12697. */
  12698. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12699. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12700. return this;
  12701. };
  12702. /**
  12703. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12704. * Supports definition of mesh facing forward or backward.
  12705. * @param {number} flipBack
  12706. * @param {number} twirlClockwise
  12707. * @param {number} tiltRight
  12708. *
  12709. * Returns a new Vector3.
  12710. */
  12711. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12712. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12713. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12714. };
  12715. /**
  12716. * Sets a new pivot matrix to the mesh.
  12717. * Returns the AbstractMesh.
  12718. */
  12719. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12720. this._pivotMatrix = matrix;
  12721. this._cache.pivotMatrixUpdated = true;
  12722. return this;
  12723. };
  12724. /**
  12725. * Returns the mesh pivot matrix.
  12726. * Default : Identity.
  12727. * A Matrix is returned.
  12728. */
  12729. AbstractMesh.prototype.getPivotMatrix = function () {
  12730. return this._pivotMatrix;
  12731. };
  12732. AbstractMesh.prototype._isSynchronized = function () {
  12733. if (this._isDirty) {
  12734. return false;
  12735. }
  12736. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12737. return false;
  12738. if (this._cache.pivotMatrixUpdated) {
  12739. return false;
  12740. }
  12741. if (this.infiniteDistance) {
  12742. return false;
  12743. }
  12744. if (!this._cache.position.equals(this.position))
  12745. return false;
  12746. if (this.rotationQuaternion) {
  12747. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12748. return false;
  12749. }
  12750. if (!this._cache.rotation.equals(this.rotation))
  12751. return false;
  12752. if (!this._cache.scaling.equals(this.scaling))
  12753. return false;
  12754. return true;
  12755. };
  12756. AbstractMesh.prototype._initCache = function () {
  12757. _super.prototype._initCache.call(this);
  12758. this._cache.localMatrixUpdated = false;
  12759. this._cache.position = BABYLON.Vector3.Zero();
  12760. this._cache.scaling = BABYLON.Vector3.Zero();
  12761. this._cache.rotation = BABYLON.Vector3.Zero();
  12762. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12763. this._cache.billboardMode = -1;
  12764. };
  12765. AbstractMesh.prototype.markAsDirty = function (property) {
  12766. if (property === "rotation") {
  12767. this.rotationQuaternion = null;
  12768. }
  12769. this._currentRenderId = Number.MAX_VALUE;
  12770. this._isDirty = true;
  12771. return this;
  12772. };
  12773. /**
  12774. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12775. * Returns the AbstractMesh.
  12776. */
  12777. AbstractMesh.prototype._updateBoundingInfo = function () {
  12778. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12779. this._boundingInfo.update(this.worldMatrixFromCache);
  12780. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12781. return this;
  12782. };
  12783. /**
  12784. * Update a mesh's children BoundingInfo objects only.
  12785. * Returns the AbstractMesh.
  12786. */
  12787. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12788. if (!this.subMeshes) {
  12789. return;
  12790. }
  12791. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12792. var subMesh = this.subMeshes[subIndex];
  12793. if (!subMesh.IsGlobal) {
  12794. subMesh.updateBoundingInfo(matrix);
  12795. }
  12796. }
  12797. return this;
  12798. };
  12799. /**
  12800. * Computes the mesh World matrix and returns it.
  12801. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12802. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12803. * If the parameter `force`is set to `true`, the actual computation is done.
  12804. * Returns the mesh World Matrix.
  12805. */
  12806. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12807. if (this._isWorldMatrixFrozen) {
  12808. return this._worldMatrix;
  12809. }
  12810. if (!force && ((this._currentRenderId === this.getScene().getRenderId() && this.isSynchronized(true)))) {
  12811. this._currentRenderId = this.getScene().getRenderId();
  12812. return this._worldMatrix;
  12813. }
  12814. this._cache.position.copyFrom(this.position);
  12815. this._cache.scaling.copyFrom(this.scaling);
  12816. this._cache.pivotMatrixUpdated = false;
  12817. this._cache.billboardMode = this.billboardMode;
  12818. this._currentRenderId = this.getScene().getRenderId();
  12819. this._isDirty = false;
  12820. // Scaling
  12821. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12822. // Rotation
  12823. //rotate, if quaternion is set and rotation was used
  12824. if (this.rotationQuaternion) {
  12825. var len = this.rotation.length();
  12826. if (len) {
  12827. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12828. this.rotation.copyFromFloats(0, 0, 0);
  12829. }
  12830. }
  12831. if (this.rotationQuaternion) {
  12832. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12833. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12834. }
  12835. else {
  12836. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12837. this._cache.rotation.copyFrom(this.rotation);
  12838. }
  12839. // Translation
  12840. if (this.infiniteDistance && !this.parent) {
  12841. var camera = this.getScene().activeCamera;
  12842. if (camera) {
  12843. var cameraWorldMatrix = camera.getWorldMatrix();
  12844. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12845. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12846. }
  12847. }
  12848. else {
  12849. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12850. }
  12851. // Composing transformations
  12852. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12853. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12854. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12855. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12856. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12857. // Need to decompose each rotation here
  12858. var currentPosition = BABYLON.Tmp.Vector3[3];
  12859. if (this.parent && this.parent.getWorldMatrix) {
  12860. if (this._meshToBoneReferal) {
  12861. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12862. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12863. }
  12864. else {
  12865. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12866. }
  12867. }
  12868. else {
  12869. currentPosition.copyFrom(this.position);
  12870. }
  12871. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12872. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12873. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12874. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12875. }
  12876. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12877. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12878. }
  12879. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12880. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12881. }
  12882. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12883. }
  12884. else {
  12885. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12886. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12887. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12888. }
  12889. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12890. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12891. }
  12892. // Local world
  12893. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12894. // Parent
  12895. if (this.parent && this.parent.getWorldMatrix) {
  12896. this._markSyncedWithParent();
  12897. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12898. if (this._meshToBoneReferal) {
  12899. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12900. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12901. }
  12902. else {
  12903. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12904. }
  12905. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12906. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12907. this._worldMatrix.copyFrom(this._localWorld);
  12908. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12909. }
  12910. else {
  12911. if (this._meshToBoneReferal) {
  12912. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12913. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12914. }
  12915. else {
  12916. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12917. }
  12918. }
  12919. }
  12920. else {
  12921. this._worldMatrix.copyFrom(this._localWorld);
  12922. }
  12923. // Bounding info
  12924. this._updateBoundingInfo();
  12925. // Absolute position
  12926. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12927. // Callbacks
  12928. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12929. if (!this._poseMatrix) {
  12930. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12931. }
  12932. return this._worldMatrix;
  12933. };
  12934. /**
  12935. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12936. * @param func: callback function to add
  12937. *
  12938. * Returns the AbstractMesh.
  12939. */
  12940. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12941. this.onAfterWorldMatrixUpdateObservable.add(func);
  12942. return this;
  12943. };
  12944. /**
  12945. * Removes a registered callback function.
  12946. * Returns the AbstractMesh.
  12947. */
  12948. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12949. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12950. return this;
  12951. };
  12952. /**
  12953. * Sets the mesh position in its local space.
  12954. * Returns the AbstractMesh.
  12955. */
  12956. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12957. this.computeWorldMatrix();
  12958. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12959. return this;
  12960. };
  12961. /**
  12962. * Returns the mesh position in the local space from the current World matrix values.
  12963. * Returns a new Vector3.
  12964. */
  12965. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12966. this.computeWorldMatrix();
  12967. var invLocalWorldMatrix = this._localWorld.clone();
  12968. invLocalWorldMatrix.invert();
  12969. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12970. };
  12971. /**
  12972. * Translates the mesh along the passed Vector3 in its local space.
  12973. * Returns the AbstractMesh.
  12974. */
  12975. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12976. this.computeWorldMatrix(true);
  12977. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12978. return this;
  12979. };
  12980. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12981. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12982. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12983. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12984. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12985. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12986. /// <returns>Mesh oriented towards targetMesh</returns>
  12987. if (yawCor === void 0) { yawCor = 0; }
  12988. if (pitchCor === void 0) { pitchCor = 0; }
  12989. if (rollCor === void 0) { rollCor = 0; }
  12990. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12991. var dv = AbstractMesh._lookAtVectorCache;
  12992. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12993. targetPoint.subtractToRef(pos, dv);
  12994. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12995. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12996. var pitch = Math.atan2(dv.y, len);
  12997. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12998. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12999. return this;
  13000. };
  13001. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13002. this._meshToBoneReferal = affectedMesh;
  13003. this.parent = bone;
  13004. if (bone.getWorldMatrix().determinant() < 0) {
  13005. this.scalingDeterminant *= -1;
  13006. }
  13007. return this;
  13008. };
  13009. AbstractMesh.prototype.detachFromBone = function () {
  13010. if (this.parent.getWorldMatrix().determinant() < 0) {
  13011. this.scalingDeterminant *= -1;
  13012. }
  13013. this._meshToBoneReferal = null;
  13014. this.parent = null;
  13015. return this;
  13016. };
  13017. /**
  13018. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13019. * A mesh is in the frustum if its bounding box intersects the frustum.
  13020. * Boolean returned.
  13021. */
  13022. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13023. return this._boundingInfo.isInFrustum(frustumPlanes);
  13024. };
  13025. /**
  13026. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13027. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13028. * Boolean returned.
  13029. */
  13030. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13031. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13032. ;
  13033. };
  13034. /**
  13035. * True if the mesh intersects another mesh or a SolidParticle object.
  13036. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  13037. * Returns a boolean.
  13038. */
  13039. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13040. if (!this._boundingInfo || !mesh._boundingInfo) {
  13041. return false;
  13042. }
  13043. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13044. };
  13045. /**
  13046. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13047. * Returns a boolean.
  13048. */
  13049. AbstractMesh.prototype.intersectsPoint = function (point) {
  13050. if (!this._boundingInfo) {
  13051. return false;
  13052. }
  13053. return this._boundingInfo.intersectsPoint(point);
  13054. };
  13055. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13056. return this.physicsImpostor;
  13057. };
  13058. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13059. if (!camera) {
  13060. camera = this.getScene().activeCamera;
  13061. }
  13062. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13063. };
  13064. /**
  13065. * Returns the distance from the mesh to the active camera.
  13066. * Returns a float.
  13067. */
  13068. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13069. if (!camera) {
  13070. camera = this.getScene().activeCamera;
  13071. }
  13072. return this.absolutePosition.subtract(camera.position).length();
  13073. };
  13074. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13075. if (!this.physicsImpostor) {
  13076. return;
  13077. }
  13078. this.physicsImpostor.applyImpulse(force, contactPoint);
  13079. return this;
  13080. };
  13081. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13082. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13083. return;
  13084. }
  13085. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13086. mainPivot: pivot1,
  13087. connectedPivot: pivot2,
  13088. nativeParams: options
  13089. });
  13090. return this;
  13091. };
  13092. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13093. // Collisions
  13094. /**
  13095. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13096. * Default `false`.
  13097. */
  13098. get: function () {
  13099. return this._checkCollisions;
  13100. },
  13101. set: function (collisionEnabled) {
  13102. this._checkCollisions = collisionEnabled;
  13103. if (this.getScene().workerCollisions) {
  13104. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13105. }
  13106. },
  13107. enumerable: true,
  13108. configurable: true
  13109. });
  13110. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13111. var globalPosition = this.getAbsolutePosition();
  13112. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13113. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13114. this._collider.radius = this.ellipsoid;
  13115. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13116. return this;
  13117. };
  13118. // Submeshes octree
  13119. /**
  13120. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13121. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13122. * Returns an Octree of submeshes.
  13123. */
  13124. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13125. if (maxCapacity === void 0) { maxCapacity = 64; }
  13126. if (maxDepth === void 0) { maxDepth = 2; }
  13127. if (!this._submeshesOctree) {
  13128. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13129. }
  13130. this.computeWorldMatrix(true);
  13131. // Update octree
  13132. var bbox = this.getBoundingInfo().boundingBox;
  13133. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13134. return this._submeshesOctree;
  13135. };
  13136. // Collisions
  13137. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13138. this._generatePointsArray();
  13139. // Transformation
  13140. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13141. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13142. subMesh._lastColliderWorldVertices = [];
  13143. subMesh._trianglePlanes = [];
  13144. var start = subMesh.verticesStart;
  13145. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13146. for (var i = start; i < end; i++) {
  13147. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13148. }
  13149. }
  13150. // Collide
  13151. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13152. if (collider.collisionFound) {
  13153. collider.collidedMesh = this;
  13154. }
  13155. return this;
  13156. };
  13157. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13158. var subMeshes;
  13159. var len;
  13160. // Octrees
  13161. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13162. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13163. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13164. len = intersections.length;
  13165. subMeshes = intersections.data;
  13166. }
  13167. else {
  13168. subMeshes = this.subMeshes;
  13169. len = subMeshes.length;
  13170. }
  13171. for (var index = 0; index < len; index++) {
  13172. var subMesh = subMeshes[index];
  13173. // Bounding test
  13174. if (len > 1 && !subMesh._checkCollision(collider))
  13175. continue;
  13176. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13177. }
  13178. return this;
  13179. };
  13180. AbstractMesh.prototype._checkCollision = function (collider) {
  13181. // Bounding box test
  13182. if (!this._boundingInfo._checkCollision(collider))
  13183. return this;
  13184. // Transformation matrix
  13185. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13186. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13187. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13188. return this;
  13189. };
  13190. // Picking
  13191. AbstractMesh.prototype._generatePointsArray = function () {
  13192. return false;
  13193. };
  13194. /**
  13195. * Checks if the passed Ray intersects with the mesh.
  13196. * Returns an object PickingInfo.
  13197. */
  13198. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13199. var pickingInfo = new BABYLON.PickingInfo();
  13200. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13201. return pickingInfo;
  13202. }
  13203. if (!this._generatePointsArray()) {
  13204. return pickingInfo;
  13205. }
  13206. var intersectInfo = null;
  13207. // Octrees
  13208. var subMeshes;
  13209. var len;
  13210. if (this._submeshesOctree && this.useOctreeForPicking) {
  13211. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13212. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13213. len = intersections.length;
  13214. subMeshes = intersections.data;
  13215. }
  13216. else {
  13217. subMeshes = this.subMeshes;
  13218. len = subMeshes.length;
  13219. }
  13220. for (var index = 0; index < len; index++) {
  13221. var subMesh = subMeshes[index];
  13222. // Bounding test
  13223. if (len > 1 && !subMesh.canIntersects(ray))
  13224. continue;
  13225. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13226. if (currentIntersectInfo) {
  13227. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13228. intersectInfo = currentIntersectInfo;
  13229. intersectInfo.subMeshId = index;
  13230. if (fastCheck) {
  13231. break;
  13232. }
  13233. }
  13234. }
  13235. }
  13236. if (intersectInfo) {
  13237. // Get picked point
  13238. var world = this.getWorldMatrix();
  13239. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13240. var direction = ray.direction.clone();
  13241. direction = direction.scale(intersectInfo.distance);
  13242. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13243. var pickedPoint = worldOrigin.add(worldDirection);
  13244. // Return result
  13245. pickingInfo.hit = true;
  13246. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13247. pickingInfo.pickedPoint = pickedPoint;
  13248. pickingInfo.pickedMesh = this;
  13249. pickingInfo.bu = intersectInfo.bu;
  13250. pickingInfo.bv = intersectInfo.bv;
  13251. pickingInfo.faceId = intersectInfo.faceId;
  13252. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13253. return pickingInfo;
  13254. }
  13255. return pickingInfo;
  13256. };
  13257. /**
  13258. * Clones the mesh, used by the class Mesh.
  13259. * Just returns `null` for an AbstractMesh.
  13260. */
  13261. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13262. return null;
  13263. };
  13264. /**
  13265. * Disposes all the mesh submeshes.
  13266. * Returns the AbstractMesh.
  13267. */
  13268. AbstractMesh.prototype.releaseSubMeshes = function () {
  13269. if (this.subMeshes) {
  13270. while (this.subMeshes.length) {
  13271. this.subMeshes[0].dispose();
  13272. }
  13273. }
  13274. else {
  13275. this.subMeshes = new Array();
  13276. }
  13277. return this;
  13278. };
  13279. /**
  13280. * Disposes the AbstractMesh.
  13281. * Some internal references are kept for further use.
  13282. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13283. * Returns nothing.
  13284. */
  13285. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13286. var _this = this;
  13287. var index;
  13288. // Action manager
  13289. if (this.actionManager) {
  13290. this.actionManager.dispose();
  13291. this.actionManager = null;
  13292. }
  13293. // Skeleton
  13294. this.skeleton = null;
  13295. // Animations
  13296. this.getScene().stopAnimation(this);
  13297. // Physics
  13298. if (this.physicsImpostor) {
  13299. this.physicsImpostor.dispose();
  13300. }
  13301. // Intersections in progress
  13302. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13303. var other = this._intersectionsInProgress[index];
  13304. var pos = other._intersectionsInProgress.indexOf(this);
  13305. other._intersectionsInProgress.splice(pos, 1);
  13306. }
  13307. this._intersectionsInProgress = [];
  13308. // Lights
  13309. var lights = this.getScene().lights;
  13310. lights.forEach(function (light) {
  13311. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13312. if (meshIndex !== -1) {
  13313. light.includedOnlyMeshes.splice(meshIndex, 1);
  13314. }
  13315. meshIndex = light.excludedMeshes.indexOf(_this);
  13316. if (meshIndex !== -1) {
  13317. light.excludedMeshes.splice(meshIndex, 1);
  13318. }
  13319. // Shadow generators
  13320. var generator = light.getShadowGenerator();
  13321. if (generator) {
  13322. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  13323. if (meshIndex !== -1) {
  13324. generator.getShadowMap().renderList.splice(meshIndex, 1);
  13325. }
  13326. }
  13327. });
  13328. // Edges
  13329. if (this._edgesRenderer) {
  13330. this._edgesRenderer.dispose();
  13331. this._edgesRenderer = null;
  13332. }
  13333. // SubMeshes
  13334. if (this.getClassName() !== "InstancedMesh") {
  13335. this.releaseSubMeshes();
  13336. }
  13337. // Engine
  13338. this.getScene().getEngine().wipeCaches();
  13339. // Remove from scene
  13340. this.getScene().removeMesh(this);
  13341. if (!doNotRecurse) {
  13342. // Particles
  13343. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13344. if (this.getScene().particleSystems[index].emitter === this) {
  13345. this.getScene().particleSystems[index].dispose();
  13346. index--;
  13347. }
  13348. }
  13349. // Children
  13350. var objects = this.getDescendants(true);
  13351. for (index = 0; index < objects.length; index++) {
  13352. objects[index].dispose();
  13353. }
  13354. }
  13355. else {
  13356. var childMeshes = this.getChildMeshes(true);
  13357. for (index = 0; index < childMeshes.length; index++) {
  13358. var child = childMeshes[index];
  13359. child.parent = null;
  13360. child.computeWorldMatrix(true);
  13361. }
  13362. }
  13363. // facet data
  13364. if (this._facetDataEnabled) {
  13365. this.disableFacetData();
  13366. }
  13367. this.onAfterWorldMatrixUpdateObservable.clear();
  13368. this.onCollideObservable.clear();
  13369. this.onCollisionPositionChangeObservable.clear();
  13370. this._isDisposed = true;
  13371. _super.prototype.dispose.call(this);
  13372. };
  13373. /**
  13374. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13375. * This Vector3 is expressed in the World space.
  13376. */
  13377. AbstractMesh.prototype.getDirection = function (localAxis) {
  13378. var result = BABYLON.Vector3.Zero();
  13379. this.getDirectionToRef(localAxis, result);
  13380. return result;
  13381. };
  13382. /**
  13383. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13384. * localAxis is expressed in the mesh local space.
  13385. * result is computed in the Wordl space from the mesh World matrix.
  13386. * Returns the AbstractMesh.
  13387. */
  13388. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13389. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13390. return this;
  13391. };
  13392. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13393. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13394. if (this.getScene().getRenderId() == 0) {
  13395. this.computeWorldMatrix(true);
  13396. }
  13397. var wm = this.getWorldMatrix();
  13398. if (space == BABYLON.Space.WORLD) {
  13399. var tmat = BABYLON.Tmp.Matrix[0];
  13400. wm.invertToRef(tmat);
  13401. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13402. }
  13403. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13404. this._pivotMatrix.m[12] = -point.x;
  13405. this._pivotMatrix.m[13] = -point.y;
  13406. this._pivotMatrix.m[14] = -point.z;
  13407. this._cache.pivotMatrixUpdated = true;
  13408. return this;
  13409. };
  13410. /**
  13411. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13412. */
  13413. AbstractMesh.prototype.getPivotPoint = function () {
  13414. var point = BABYLON.Vector3.Zero();
  13415. this.getPivotPointToRef(point);
  13416. return point;
  13417. };
  13418. /**
  13419. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13420. * Returns the AbstractMesh.
  13421. */
  13422. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13423. result.x = -this._pivotMatrix.m[12];
  13424. result.y = -this._pivotMatrix.m[13];
  13425. result.z = -this._pivotMatrix.m[14];
  13426. return this;
  13427. };
  13428. /**
  13429. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13430. */
  13431. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13432. var point = BABYLON.Vector3.Zero();
  13433. this.getAbsolutePivotPointToRef(point);
  13434. return point;
  13435. };
  13436. /**
  13437. * Defines the passed mesh as the parent of the current mesh.
  13438. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  13439. * Returns the AbstractMesh.
  13440. */
  13441. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  13442. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13443. var child = this;
  13444. var parent = mesh;
  13445. if (mesh == null) {
  13446. if (child.parent && keepWorldPositionRotation) {
  13447. var rotation = BABYLON.Tmp.Quaternion[0];
  13448. var position = BABYLON.Tmp.Vector3[0];
  13449. var scale = BABYLON.Tmp.Vector3[1];
  13450. child.getWorldMatrix().decompose(scale, rotation, position);
  13451. if (child.rotationQuaternion) {
  13452. child.rotationQuaternion.copyFrom(rotation);
  13453. }
  13454. else {
  13455. rotation.toEulerAnglesToRef(child.rotation);
  13456. }
  13457. child.position.x = position.x;
  13458. child.position.y = position.y;
  13459. child.position.z = position.z;
  13460. }
  13461. }
  13462. else {
  13463. if (keepWorldPositionRotation) {
  13464. var rotation = BABYLON.Tmp.Quaternion[0];
  13465. var position = BABYLON.Tmp.Vector3[0];
  13466. var scale = BABYLON.Tmp.Vector3[1];
  13467. var m1 = BABYLON.Tmp.Matrix[0];
  13468. var m2 = BABYLON.Tmp.Matrix[1];
  13469. parent.getWorldMatrix().decompose(scale, rotation, position);
  13470. rotation.toRotationMatrix(m1);
  13471. m2.setTranslation(position);
  13472. m2.multiplyToRef(m1, m1);
  13473. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13474. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13475. m.decompose(scale, rotation, position);
  13476. if (child.rotationQuaternion) {
  13477. child.rotationQuaternion.copyFrom(rotation);
  13478. }
  13479. else {
  13480. rotation.toEulerAnglesToRef(child.rotation);
  13481. }
  13482. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13483. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13484. m.decompose(scale, rotation, position);
  13485. child.position.x = position.x;
  13486. child.position.y = position.y;
  13487. child.position.z = position.z;
  13488. }
  13489. }
  13490. child.parent = parent;
  13491. return this;
  13492. };
  13493. /**
  13494. * Adds the passed mesh as a child to the current mesh.
  13495. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  13496. * Returns the AbstractMesh.
  13497. */
  13498. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  13499. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13500. mesh.setParent(this, keepWorldPositionRotation);
  13501. return this;
  13502. };
  13503. /**
  13504. * Removes the passed mesh from the current mesh children list.
  13505. * Returns the AbstractMesh.
  13506. */
  13507. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  13508. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13509. mesh.setParent(null, keepWorldPositionRotation);
  13510. return this;
  13511. };
  13512. /**
  13513. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13514. * Returns the AbstractMesh.
  13515. */
  13516. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13517. result.x = this._pivotMatrix.m[12];
  13518. result.y = this._pivotMatrix.m[13];
  13519. result.z = this._pivotMatrix.m[14];
  13520. this.getPivotPointToRef(result);
  13521. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13522. return this;
  13523. };
  13524. // Facet data
  13525. /**
  13526. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13527. * Returns the AbstractMesh.
  13528. */
  13529. AbstractMesh.prototype._initFacetData = function () {
  13530. if (!this._facetNormals) {
  13531. this._facetNormals = new Array();
  13532. }
  13533. if (!this._facetPositions) {
  13534. this._facetPositions = new Array();
  13535. }
  13536. if (!this._facetPartitioning) {
  13537. this._facetPartitioning = new Array();
  13538. }
  13539. this._facetNb = this.getIndices().length / 3;
  13540. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13541. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13542. for (var f = 0; f < this._facetNb; f++) {
  13543. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13544. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13545. }
  13546. this._facetDataEnabled = true;
  13547. return this;
  13548. };
  13549. /**
  13550. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13551. * This method can be called within the render loop.
  13552. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  13553. * Returns the AbstractMesh.
  13554. */
  13555. AbstractMesh.prototype.updateFacetData = function () {
  13556. if (!this._facetDataEnabled) {
  13557. this._initFacetData();
  13558. }
  13559. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13560. var indices = this.getIndices();
  13561. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13562. var bInfo = this.getBoundingInfo();
  13563. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13564. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13565. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13566. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13567. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13568. this._subDiv.max = this._partitioningSubdivisions;
  13569. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13570. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13571. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13572. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13573. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13574. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13575. // set the parameters for ComputeNormals()
  13576. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13577. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13578. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13579. this._facetParameters.bInfo = bInfo;
  13580. this._facetParameters.bbSize = this._bbSize;
  13581. this._facetParameters.subDiv = this._subDiv;
  13582. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13583. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13584. return this;
  13585. };
  13586. /**
  13587. * Returns the facetLocalNormals array.
  13588. * The normals are expressed in the mesh local space.
  13589. */
  13590. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13591. if (!this._facetNormals) {
  13592. this.updateFacetData();
  13593. }
  13594. return this._facetNormals;
  13595. };
  13596. /**
  13597. * Returns the facetLocalPositions array.
  13598. * The facet positions are expressed in the mesh local space.
  13599. */
  13600. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13601. if (!this._facetPositions) {
  13602. this.updateFacetData();
  13603. }
  13604. return this._facetPositions;
  13605. };
  13606. /**
  13607. * Returns the facetLocalPartioning array.
  13608. */
  13609. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13610. if (!this._facetPartitioning) {
  13611. this.updateFacetData();
  13612. }
  13613. return this._facetPartitioning;
  13614. };
  13615. /**
  13616. * Returns the i-th facet position in the world system.
  13617. * This method allocates a new Vector3 per call.
  13618. */
  13619. AbstractMesh.prototype.getFacetPosition = function (i) {
  13620. var pos = BABYLON.Vector3.Zero();
  13621. this.getFacetPositionToRef(i, pos);
  13622. return pos;
  13623. };
  13624. /**
  13625. * Sets the reference Vector3 with the i-th facet position in the world system.
  13626. * Returns the AbstractMesh.
  13627. */
  13628. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13629. var localPos = (this.getFacetLocalPositions())[i];
  13630. var world = this.getWorldMatrix();
  13631. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13632. return this;
  13633. };
  13634. /**
  13635. * Returns the i-th facet normal in the world system.
  13636. * This method allocates a new Vector3 per call.
  13637. */
  13638. AbstractMesh.prototype.getFacetNormal = function (i) {
  13639. var norm = BABYLON.Vector3.Zero();
  13640. this.getFacetNormalToRef(i, norm);
  13641. return norm;
  13642. };
  13643. /**
  13644. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13645. * Returns the AbstractMesh.
  13646. */
  13647. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13648. var localNorm = (this.getFacetLocalNormals())[i];
  13649. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13650. return this;
  13651. };
  13652. /**
  13653. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  13654. */
  13655. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13656. var bInfo = this.getBoundingInfo();
  13657. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13658. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13659. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13660. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13661. return null;
  13662. }
  13663. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13664. };
  13665. /**
  13666. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13667. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13668. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  13669. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13670. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  13671. */
  13672. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13673. if (checkFace === void 0) { checkFace = false; }
  13674. if (facing === void 0) { facing = true; }
  13675. var world = this.getWorldMatrix();
  13676. var invMat = BABYLON.Tmp.Matrix[5];
  13677. world.invertToRef(invMat);
  13678. var invVect = BABYLON.Tmp.Vector3[8];
  13679. var closest = null;
  13680. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13681. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13682. if (projected) {
  13683. // tranform the local computed projected vector to world coordinates
  13684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13685. }
  13686. return closest;
  13687. };
  13688. /**
  13689. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13690. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13691. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  13692. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13693. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  13694. */
  13695. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13696. if (checkFace === void 0) { checkFace = false; }
  13697. if (facing === void 0) { facing = true; }
  13698. var closest = null;
  13699. var tmpx = 0.0;
  13700. var tmpy = 0.0;
  13701. var tmpz = 0.0;
  13702. var d = 0.0; // tmp dot facet normal * facet position
  13703. var t0 = 0.0;
  13704. var projx = 0.0;
  13705. var projy = 0.0;
  13706. var projz = 0.0;
  13707. // Get all the facets in the same partitioning block than (x, y, z)
  13708. var facetPositions = this.getFacetLocalPositions();
  13709. var facetNormals = this.getFacetLocalNormals();
  13710. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13711. if (!facetsInBlock) {
  13712. return null;
  13713. }
  13714. // Get the closest facet to (x, y, z)
  13715. var shortest = Number.MAX_VALUE; // init distance vars
  13716. var tmpDistance = shortest;
  13717. var fib; // current facet in the block
  13718. var norm; // current facet normal
  13719. var p0; // current facet barycenter position
  13720. // loop on all the facets in the current partitioning block
  13721. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13722. fib = facetsInBlock[idx];
  13723. norm = facetNormals[fib];
  13724. p0 = facetPositions[fib];
  13725. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13726. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13727. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13728. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13729. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13730. projx = x + norm.x * t0;
  13731. projy = y + norm.y * t0;
  13732. projz = z + norm.z * t0;
  13733. tmpx = projx - x;
  13734. tmpy = projy - y;
  13735. tmpz = projz - z;
  13736. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13737. if (tmpDistance < shortest) {
  13738. shortest = tmpDistance;
  13739. closest = fib;
  13740. if (projected) {
  13741. projected.x = projx;
  13742. projected.y = projy;
  13743. projected.z = projz;
  13744. }
  13745. }
  13746. }
  13747. }
  13748. return closest;
  13749. };
  13750. /**
  13751. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13752. */
  13753. AbstractMesh.prototype.getFacetDataParameters = function () {
  13754. return this._facetParameters;
  13755. };
  13756. /**
  13757. * Disables the feature FacetData and frees the related memory.
  13758. * Returns the AbstractMesh.
  13759. */
  13760. AbstractMesh.prototype.disableFacetData = function () {
  13761. if (this._facetDataEnabled) {
  13762. this._facetDataEnabled = false;
  13763. this._facetPositions = null;
  13764. this._facetNormals = null;
  13765. this._facetPartitioning = null;
  13766. this._facetParameters = null;
  13767. }
  13768. return this;
  13769. };
  13770. return AbstractMesh;
  13771. }(BABYLON.Node));
  13772. // Statics
  13773. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13774. AbstractMesh._BILLBOARDMODE_X = 1;
  13775. AbstractMesh._BILLBOARDMODE_Y = 2;
  13776. AbstractMesh._BILLBOARDMODE_Z = 4;
  13777. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13778. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13779. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13780. BABYLON.AbstractMesh = AbstractMesh;
  13781. })(BABYLON || (BABYLON = {}));
  13782. //# sourceMappingURL=babylon.abstractMesh.js.map
  13783. var BABYLON;
  13784. (function (BABYLON) {
  13785. var Light = (function (_super) {
  13786. __extends(Light, _super);
  13787. /**
  13788. * Creates a Light object in the scene.
  13789. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13790. */
  13791. function Light(name, scene) {
  13792. var _this = _super.call(this, name, scene) || this;
  13793. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13794. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13795. _this.intensity = 1.0;
  13796. _this.range = Number.MAX_VALUE;
  13797. _this.includeOnlyWithLayerMask = 0;
  13798. _this.includedOnlyMeshes = new Array();
  13799. _this.excludedMeshes = new Array();
  13800. _this.excludeWithLayerMask = 0;
  13801. _this.lightmapMode = 0;
  13802. // PBR Properties.
  13803. _this.radius = 0.00001;
  13804. _this._excludedMeshesIds = new Array();
  13805. _this._includedOnlyMeshesIds = new Array();
  13806. _this.getScene().addLight(_this);
  13807. return _this;
  13808. }
  13809. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13810. /**
  13811. * If every light affecting the material is in this lightmapMode,
  13812. * material.lightmapTexture adds or multiplies
  13813. * (depends on material.useLightmapAsShadowmap)
  13814. * after every other light calculations.
  13815. */
  13816. get: function () {
  13817. return Light._LIGHTMAP_DEFAULT;
  13818. },
  13819. enumerable: true,
  13820. configurable: true
  13821. });
  13822. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13823. /**
  13824. * material.lightmapTexture as only diffuse lighting from this light
  13825. * adds pnly specular lighting from this light
  13826. * adds dynamic shadows
  13827. */
  13828. get: function () {
  13829. return Light._LIGHTMAP_SPECULAR;
  13830. },
  13831. enumerable: true,
  13832. configurable: true
  13833. });
  13834. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13835. /**
  13836. * material.lightmapTexture as only lighting
  13837. * no light calculation from this light
  13838. * only adds dynamic shadows from this light
  13839. */
  13840. get: function () {
  13841. return Light._LIGHTMAP_SHADOWSONLY;
  13842. },
  13843. enumerable: true,
  13844. configurable: true
  13845. });
  13846. /**
  13847. * Returns the string "Light".
  13848. */
  13849. Light.prototype.getClassName = function () {
  13850. return "Light";
  13851. };
  13852. /**
  13853. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13854. */
  13855. Light.prototype.toString = function (fullDetails) {
  13856. var ret = "Name: " + this.name;
  13857. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13858. if (this.animations) {
  13859. for (var i = 0; i < this.animations.length; i++) {
  13860. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13861. }
  13862. }
  13863. if (fullDetails) {
  13864. }
  13865. return ret;
  13866. };
  13867. /**
  13868. * Returns the Light associated shadow generator.
  13869. */
  13870. Light.prototype.getShadowGenerator = function () {
  13871. return this._shadowGenerator;
  13872. };
  13873. /**
  13874. * Returns a Vector3, the absolute light position in the World.
  13875. */
  13876. Light.prototype.getAbsolutePosition = function () {
  13877. return BABYLON.Vector3.Zero();
  13878. };
  13879. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  13880. };
  13881. Light.prototype._getWorldMatrix = function () {
  13882. return BABYLON.Matrix.Identity();
  13883. };
  13884. /**
  13885. * Boolean : True if the light will affect the passed mesh.
  13886. */
  13887. Light.prototype.canAffectMesh = function (mesh) {
  13888. if (!mesh) {
  13889. return true;
  13890. }
  13891. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13892. return false;
  13893. }
  13894. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13895. return false;
  13896. }
  13897. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13898. return false;
  13899. }
  13900. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13901. return false;
  13902. }
  13903. return true;
  13904. };
  13905. /**
  13906. * Returns the light World matrix.
  13907. */
  13908. Light.prototype.getWorldMatrix = function () {
  13909. this._currentRenderId = this.getScene().getRenderId();
  13910. var worldMatrix = this._getWorldMatrix();
  13911. if (this.parent && this.parent.getWorldMatrix) {
  13912. if (!this._parentedWorldMatrix) {
  13913. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13914. }
  13915. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13916. this._markSyncedWithParent();
  13917. return this._parentedWorldMatrix;
  13918. }
  13919. return worldMatrix;
  13920. };
  13921. /**
  13922. * Disposes the light.
  13923. */
  13924. Light.prototype.dispose = function () {
  13925. if (this._shadowGenerator) {
  13926. this._shadowGenerator.dispose();
  13927. this._shadowGenerator = null;
  13928. }
  13929. // Animations
  13930. this.getScene().stopAnimation(this);
  13931. // Remove from scene
  13932. this.getScene().removeLight(this);
  13933. _super.prototype.dispose.call(this);
  13934. };
  13935. /**
  13936. * Returns the light type ID (integer).
  13937. */
  13938. Light.prototype.getTypeID = function () {
  13939. return 0;
  13940. };
  13941. /**
  13942. * Returns a new Light object, named "name", from the current one.
  13943. */
  13944. Light.prototype.clone = function (name) {
  13945. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13946. };
  13947. /**
  13948. * Serializes the current light into a Serialization object.
  13949. * Returns the serialized object.
  13950. */
  13951. Light.prototype.serialize = function () {
  13952. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13953. // Type
  13954. serializationObject.type = this.getTypeID();
  13955. // Parent
  13956. if (this.parent) {
  13957. serializationObject.parentId = this.parent.id;
  13958. }
  13959. // Inclusion / exclusions
  13960. if (this.excludedMeshes.length > 0) {
  13961. serializationObject.excludedMeshesIds = [];
  13962. this.excludedMeshes.forEach(function (mesh) {
  13963. serializationObject.excludedMeshesIds.push(mesh.id);
  13964. });
  13965. }
  13966. if (this.includedOnlyMeshes.length > 0) {
  13967. serializationObject.includedOnlyMeshesIds = [];
  13968. this.includedOnlyMeshes.forEach(function (mesh) {
  13969. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13970. });
  13971. }
  13972. // Animations
  13973. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13974. serializationObject.ranges = this.serializeAnimationRanges();
  13975. return serializationObject;
  13976. };
  13977. /**
  13978. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13979. * This new light is named "name" and added to the passed scene.
  13980. */
  13981. Light.GetConstructorFromName = function (type, name, scene) {
  13982. switch (type) {
  13983. case 0:
  13984. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13985. case 1:
  13986. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13987. case 2:
  13988. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13989. case 3:
  13990. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13991. }
  13992. };
  13993. /**
  13994. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13995. */
  13996. Light.Parse = function (parsedLight, scene) {
  13997. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13998. // Inclusion / exclusions
  13999. if (parsedLight.excludedMeshesIds) {
  14000. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14001. }
  14002. if (parsedLight.includedOnlyMeshesIds) {
  14003. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14004. }
  14005. // Parent
  14006. if (parsedLight.parentId) {
  14007. light._waitingParentId = parsedLight.parentId;
  14008. }
  14009. // Animations
  14010. if (parsedLight.animations) {
  14011. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14012. var parsedAnimation = parsedLight.animations[animationIndex];
  14013. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14014. }
  14015. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14016. }
  14017. if (parsedLight.autoAnimate) {
  14018. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14019. }
  14020. return light;
  14021. };
  14022. return Light;
  14023. }(BABYLON.Node));
  14024. //lightmapMode Consts
  14025. Light._LIGHTMAP_DEFAULT = 0;
  14026. Light._LIGHTMAP_SPECULAR = 1;
  14027. Light._LIGHTMAP_SHADOWSONLY = 2;
  14028. __decorate([
  14029. BABYLON.serializeAsColor3()
  14030. ], Light.prototype, "diffuse", void 0);
  14031. __decorate([
  14032. BABYLON.serializeAsColor3()
  14033. ], Light.prototype, "specular", void 0);
  14034. __decorate([
  14035. BABYLON.serialize()
  14036. ], Light.prototype, "intensity", void 0);
  14037. __decorate([
  14038. BABYLON.serialize()
  14039. ], Light.prototype, "range", void 0);
  14040. __decorate([
  14041. BABYLON.serialize()
  14042. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  14043. __decorate([
  14044. BABYLON.serialize()
  14045. ], Light.prototype, "excludeWithLayerMask", void 0);
  14046. __decorate([
  14047. BABYLON.serialize()
  14048. ], Light.prototype, "lightmapMode", void 0);
  14049. __decorate([
  14050. BABYLON.serialize()
  14051. ], Light.prototype, "radius", void 0);
  14052. BABYLON.Light = Light;
  14053. })(BABYLON || (BABYLON = {}));
  14054. //# sourceMappingURL=babylon.light.js.map
  14055. var BABYLON;
  14056. (function (BABYLON) {
  14057. var PointLight = (function (_super) {
  14058. __extends(PointLight, _super);
  14059. /**
  14060. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  14061. * A PointLight emits the light in every direction.
  14062. * It can cast shadows.
  14063. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  14064. * ```javascript
  14065. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  14066. * ```
  14067. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14068. */
  14069. function PointLight(name, position, scene) {
  14070. var _this = _super.call(this, name, scene) || this;
  14071. _this.position = position;
  14072. return _this;
  14073. }
  14074. /**
  14075. * Returns the string "PointLight"
  14076. */
  14077. PointLight.prototype.getClassName = function () {
  14078. return "PointLight";
  14079. };
  14080. /**
  14081. * Returns a Vector3, the PointLight absolute position in the World.
  14082. */
  14083. PointLight.prototype.getAbsolutePosition = function () {
  14084. return this.transformedPosition ? this.transformedPosition : this.position;
  14085. };
  14086. /**
  14087. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  14088. */
  14089. PointLight.prototype.computeTransformedPosition = function () {
  14090. if (this.parent && this.parent.getWorldMatrix) {
  14091. if (!this.transformedPosition) {
  14092. this.transformedPosition = BABYLON.Vector3.Zero();
  14093. }
  14094. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14095. return true;
  14096. }
  14097. return false;
  14098. };
  14099. /**
  14100. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  14101. * Returns the PointLight.
  14102. */
  14103. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  14104. if (this.parent && this.parent.getWorldMatrix) {
  14105. this.computeTransformedPosition();
  14106. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  14107. return this;
  14108. }
  14109. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  14110. return this;
  14111. };
  14112. /**
  14113. * Boolean : returns true by default.
  14114. */
  14115. PointLight.prototype.needCube = function () {
  14116. return true;
  14117. };
  14118. /**
  14119. * Boolean : returns false by default.
  14120. */
  14121. PointLight.prototype.supportsVSM = function () {
  14122. return false;
  14123. };
  14124. /**
  14125. * Boolean : returns false by default.
  14126. */
  14127. PointLight.prototype.needRefreshPerFrame = function () {
  14128. return false;
  14129. };
  14130. /**
  14131. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  14132. */
  14133. PointLight.prototype.getShadowDirection = function (faceIndex) {
  14134. switch (faceIndex) {
  14135. case 0:
  14136. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  14137. case 1:
  14138. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  14139. case 2:
  14140. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  14141. case 3:
  14142. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  14143. case 4:
  14144. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  14145. case 5:
  14146. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  14147. }
  14148. return BABYLON.Vector3.Zero();
  14149. };
  14150. /**
  14151. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  14152. * - fov = PI / 2
  14153. * - aspect ratio : 1.0
  14154. * - z-near and far equal to the active camera minZ and maxZ.
  14155. * Returns the PointLight.
  14156. */
  14157. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14158. if (this.customProjectionMatrixBuilder) {
  14159. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14160. }
  14161. else {
  14162. var activeCamera = this.getScene().activeCamera;
  14163. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  14164. }
  14165. return this;
  14166. };
  14167. PointLight.prototype._getWorldMatrix = function () {
  14168. if (!this._worldMatrix) {
  14169. this._worldMatrix = BABYLON.Matrix.Identity();
  14170. }
  14171. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14172. return this._worldMatrix;
  14173. };
  14174. /**
  14175. * Returns the integer 0.
  14176. */
  14177. PointLight.prototype.getTypeID = function () {
  14178. return 0;
  14179. };
  14180. return PointLight;
  14181. }(BABYLON.Light));
  14182. __decorate([
  14183. BABYLON.serializeAsVector3()
  14184. ], PointLight.prototype, "position", void 0);
  14185. BABYLON.PointLight = PointLight;
  14186. })(BABYLON || (BABYLON = {}));
  14187. //# sourceMappingURL=babylon.pointLight.js.map
  14188. var BABYLON;
  14189. (function (BABYLON) {
  14190. var SpotLight = (function (_super) {
  14191. __extends(SpotLight, _super);
  14192. /**
  14193. * Creates a SpotLight object in the scene with the passed parameters :
  14194. * - `position` (Vector3) is the initial SpotLight position,
  14195. * - `direction` (Vector3) is the initial SpotLight direction,
  14196. * - `angle` (float, in radians) is the spot light cone angle,
  14197. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  14198. * A spot light is a simply light oriented cone.
  14199. * It can cast shadows.
  14200. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14201. */
  14202. function SpotLight(name, position, direction, angle, exponent, scene) {
  14203. var _this = _super.call(this, name, scene) || this;
  14204. _this.position = position;
  14205. _this.direction = direction;
  14206. _this.angle = angle;
  14207. _this.exponent = exponent;
  14208. return _this;
  14209. }
  14210. /**
  14211. * Returns the string "SpotLight".
  14212. */
  14213. SpotLight.prototype.getClassName = function () {
  14214. return "SpotLight";
  14215. };
  14216. /**
  14217. * Returns the SpotLight absolute position in the World (Vector3).
  14218. */
  14219. SpotLight.prototype.getAbsolutePosition = function () {
  14220. return this.transformedPosition ? this.transformedPosition : this.position;
  14221. };
  14222. /**
  14223. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  14224. * Returns the SpotLight.
  14225. */
  14226. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14227. if (this.customProjectionMatrixBuilder) {
  14228. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14229. }
  14230. else {
  14231. var activeCamera = this.getScene().activeCamera;
  14232. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  14233. }
  14234. return this;
  14235. };
  14236. /**
  14237. * Boolean : false by default.
  14238. */
  14239. SpotLight.prototype.needCube = function () {
  14240. return false;
  14241. };
  14242. /**
  14243. * Boolean : true by default.
  14244. */
  14245. SpotLight.prototype.supportsVSM = function () {
  14246. return true;
  14247. };
  14248. /**
  14249. * Boolean : false by default.
  14250. */
  14251. SpotLight.prototype.needRefreshPerFrame = function () {
  14252. return false;
  14253. };
  14254. /**
  14255. * Returns the SpotLight direction (Vector3) for any passed face index.
  14256. */
  14257. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  14258. return this.direction;
  14259. };
  14260. /**
  14261. * Updates the SpotLight direction towards the passed target (Vector3).
  14262. * Returns the updated direction.
  14263. */
  14264. SpotLight.prototype.setDirectionToTarget = function (target) {
  14265. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14266. return this.direction;
  14267. };
  14268. /**
  14269. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  14270. */
  14271. SpotLight.prototype.computeTransformedPosition = function () {
  14272. if (this.parent && this.parent.getWorldMatrix) {
  14273. if (!this.transformedPosition) {
  14274. this.transformedPosition = BABYLON.Vector3.Zero();
  14275. }
  14276. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14277. return true;
  14278. }
  14279. return false;
  14280. };
  14281. /**
  14282. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  14283. * Return the SpotLight.
  14284. */
  14285. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  14286. var normalizeDirection;
  14287. if (this.parent && this.parent.getWorldMatrix) {
  14288. if (!this._transformedDirection) {
  14289. this._transformedDirection = BABYLON.Vector3.Zero();
  14290. }
  14291. this.computeTransformedPosition();
  14292. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14293. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  14294. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  14295. }
  14296. else {
  14297. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  14298. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14299. }
  14300. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  14301. return this;
  14302. };
  14303. SpotLight.prototype._getWorldMatrix = function () {
  14304. if (!this._worldMatrix) {
  14305. this._worldMatrix = BABYLON.Matrix.Identity();
  14306. }
  14307. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14308. return this._worldMatrix;
  14309. };
  14310. /**
  14311. * Returns the integer 2.
  14312. */
  14313. SpotLight.prototype.getTypeID = function () {
  14314. return 2;
  14315. };
  14316. /**
  14317. * Returns the SpotLight rotation (Vector3).
  14318. */
  14319. SpotLight.prototype.getRotation = function () {
  14320. this.direction.normalize();
  14321. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  14322. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  14323. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  14324. };
  14325. return SpotLight;
  14326. }(BABYLON.Light));
  14327. __decorate([
  14328. BABYLON.serializeAsVector3()
  14329. ], SpotLight.prototype, "position", void 0);
  14330. __decorate([
  14331. BABYLON.serializeAsVector3()
  14332. ], SpotLight.prototype, "direction", void 0);
  14333. __decorate([
  14334. BABYLON.serialize()
  14335. ], SpotLight.prototype, "angle", void 0);
  14336. __decorate([
  14337. BABYLON.serialize()
  14338. ], SpotLight.prototype, "exponent", void 0);
  14339. BABYLON.SpotLight = SpotLight;
  14340. })(BABYLON || (BABYLON = {}));
  14341. //# sourceMappingURL=babylon.spotLight.js.map
  14342. var BABYLON;
  14343. (function (BABYLON) {
  14344. var HemisphericLight = (function (_super) {
  14345. __extends(HemisphericLight, _super);
  14346. /**
  14347. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  14348. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  14349. * The HemisphericLight can't cast shadows.
  14350. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14351. */
  14352. function HemisphericLight(name, direction, scene) {
  14353. var _this = _super.call(this, name, scene) || this;
  14354. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  14355. _this.direction = direction;
  14356. return _this;
  14357. }
  14358. /**
  14359. * Returns the string "HemisphericLight".
  14360. */
  14361. HemisphericLight.prototype.getClassName = function () {
  14362. return "HemisphericLight";
  14363. };
  14364. /**
  14365. * Sets the HemisphericLight direction towards the passed target (Vector3).
  14366. * Returns the updated direction.
  14367. */
  14368. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  14369. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  14370. return this.direction;
  14371. };
  14372. HemisphericLight.prototype.getShadowGenerator = function () {
  14373. return null;
  14374. };
  14375. /**
  14376. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  14377. * Returns the HemisphericLight.
  14378. */
  14379. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  14380. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14381. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  14382. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  14383. return this;
  14384. };
  14385. HemisphericLight.prototype._getWorldMatrix = function () {
  14386. if (!this._worldMatrix) {
  14387. this._worldMatrix = BABYLON.Matrix.Identity();
  14388. }
  14389. return this._worldMatrix;
  14390. };
  14391. /**
  14392. * Returns the integer 3.
  14393. */
  14394. HemisphericLight.prototype.getTypeID = function () {
  14395. return 3;
  14396. };
  14397. return HemisphericLight;
  14398. }(BABYLON.Light));
  14399. __decorate([
  14400. BABYLON.serializeAsColor3()
  14401. ], HemisphericLight.prototype, "groundColor", void 0);
  14402. __decorate([
  14403. BABYLON.serializeAsVector3()
  14404. ], HemisphericLight.prototype, "direction", void 0);
  14405. BABYLON.HemisphericLight = HemisphericLight;
  14406. })(BABYLON || (BABYLON = {}));
  14407. //# sourceMappingURL=babylon.hemisphericLight.js.map
  14408. /// <reference path="babylon.light.ts" />
  14409. var BABYLON;
  14410. (function (BABYLON) {
  14411. var DirectionalLight = (function (_super) {
  14412. __extends(DirectionalLight, _super);
  14413. /**
  14414. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  14415. * The directional light is emitted from everywhere in the given direction.
  14416. * It can cast shawdows.
  14417. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14418. */
  14419. function DirectionalLight(name, direction, scene) {
  14420. var _this = _super.call(this, name, scene) || this;
  14421. _this.shadowOrthoScale = 0.5;
  14422. _this.autoUpdateExtends = true;
  14423. // Cache
  14424. _this._orthoLeft = Number.MAX_VALUE;
  14425. _this._orthoRight = Number.MIN_VALUE;
  14426. _this._orthoTop = Number.MIN_VALUE;
  14427. _this._orthoBottom = Number.MAX_VALUE;
  14428. _this.position = direction.scale(-1.0);
  14429. _this.direction = direction;
  14430. return _this;
  14431. }
  14432. /**
  14433. * Returns the string "DirectionalLight".
  14434. */
  14435. DirectionalLight.prototype.getClassName = function () {
  14436. return "DirectionalLight";
  14437. };
  14438. /**
  14439. * Returns the DirectionalLight absolute position in the World.
  14440. */
  14441. DirectionalLight.prototype.getAbsolutePosition = function () {
  14442. return this.transformedPosition ? this.transformedPosition : this.position;
  14443. };
  14444. /**
  14445. * Sets the DirectionalLight direction toward the passed target (Vector3).
  14446. * Returns the updated DirectionalLight direction (Vector3).
  14447. */
  14448. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  14449. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14450. return this.direction;
  14451. };
  14452. /**
  14453. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  14454. * Returns the DirectionalLight.
  14455. */
  14456. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14457. if (this.customProjectionMatrixBuilder) {
  14458. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14459. }
  14460. else {
  14461. var activeCamera = this.getScene().activeCamera;
  14462. // Check extends
  14463. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  14464. var tempVector3 = BABYLON.Vector3.Zero();
  14465. this._orthoLeft = Number.MAX_VALUE;
  14466. this._orthoRight = Number.MIN_VALUE;
  14467. this._orthoTop = Number.MIN_VALUE;
  14468. this._orthoBottom = Number.MAX_VALUE;
  14469. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  14470. var mesh = renderList[meshIndex];
  14471. if (!mesh) {
  14472. continue;
  14473. }
  14474. var boundingInfo = mesh.getBoundingInfo();
  14475. if (!boundingInfo) {
  14476. continue;
  14477. }
  14478. var boundingBox = boundingInfo.boundingBox;
  14479. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  14480. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  14481. if (tempVector3.x < this._orthoLeft)
  14482. this._orthoLeft = tempVector3.x;
  14483. if (tempVector3.y < this._orthoBottom)
  14484. this._orthoBottom = tempVector3.y;
  14485. if (tempVector3.x > this._orthoRight)
  14486. this._orthoRight = tempVector3.x;
  14487. if (tempVector3.y > this._orthoTop)
  14488. this._orthoTop = tempVector3.y;
  14489. }
  14490. }
  14491. }
  14492. var xOffset = this._orthoRight - this._orthoLeft;
  14493. var yOffset = this._orthoTop - this._orthoBottom;
  14494. 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);
  14495. }
  14496. return this;
  14497. };
  14498. /**
  14499. * Boolean : true by default.
  14500. */
  14501. DirectionalLight.prototype.supportsVSM = function () {
  14502. return true;
  14503. };
  14504. /**
  14505. * Boolean : true by default.
  14506. */
  14507. DirectionalLight.prototype.needRefreshPerFrame = function () {
  14508. return true;
  14509. };
  14510. /**
  14511. * Boolean : false by default.
  14512. */
  14513. DirectionalLight.prototype.needCube = function () {
  14514. return false;
  14515. };
  14516. /**
  14517. * Returns the light direction (Vector3) for any passed face index.
  14518. */
  14519. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  14520. return this.direction;
  14521. };
  14522. /**
  14523. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  14524. */
  14525. DirectionalLight.prototype.computeTransformedPosition = function () {
  14526. if (this.parent && this.parent.getWorldMatrix) {
  14527. if (!this.transformedPosition) {
  14528. this.transformedPosition = BABYLON.Vector3.Zero();
  14529. }
  14530. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14531. return true;
  14532. }
  14533. return false;
  14534. };
  14535. /**
  14536. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  14537. * Returns the DirectionalLight.
  14538. */
  14539. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  14540. if (this.parent && this.parent.getWorldMatrix) {
  14541. if (!this._transformedDirection) {
  14542. this._transformedDirection = BABYLON.Vector3.Zero();
  14543. }
  14544. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14545. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  14546. return this;
  14547. }
  14548. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  14549. return this;
  14550. };
  14551. DirectionalLight.prototype._getWorldMatrix = function () {
  14552. if (!this._worldMatrix) {
  14553. this._worldMatrix = BABYLON.Matrix.Identity();
  14554. }
  14555. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14556. return this._worldMatrix;
  14557. };
  14558. /**
  14559. * Returns the integer 1.
  14560. */
  14561. DirectionalLight.prototype.getTypeID = function () {
  14562. return 1;
  14563. };
  14564. return DirectionalLight;
  14565. }(BABYLON.Light));
  14566. __decorate([
  14567. BABYLON.serializeAsVector3()
  14568. ], DirectionalLight.prototype, "position", void 0);
  14569. __decorate([
  14570. BABYLON.serializeAsVector3()
  14571. ], DirectionalLight.prototype, "direction", void 0);
  14572. __decorate([
  14573. BABYLON.serialize()
  14574. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  14575. __decorate([
  14576. BABYLON.serialize()
  14577. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  14578. BABYLON.DirectionalLight = DirectionalLight;
  14579. })(BABYLON || (BABYLON = {}));
  14580. //# sourceMappingURL=babylon.directionalLight.js.map
  14581. var BABYLON;
  14582. (function (BABYLON) {
  14583. var ShadowGenerator = (function () {
  14584. /**
  14585. * Creates a ShadowGenerator object.
  14586. * A ShadowGenerator is the required tool to use the shadows.
  14587. * Each light casting shadows needs to use its own ShadowGenerator.
  14588. * Required parameters :
  14589. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  14590. * - `light` : the light object generating the shadows.
  14591. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  14592. */
  14593. function ShadowGenerator(mapSize, light) {
  14594. var _this = this;
  14595. // Members
  14596. this._filter = ShadowGenerator.FILTER_NONE;
  14597. this.blurScale = 2;
  14598. this._blurBoxOffset = 0;
  14599. this._bias = 0.00005;
  14600. this._lightDirection = BABYLON.Vector3.Zero();
  14601. this.forceBackFacesOnly = false;
  14602. this._darkness = 0;
  14603. this._transparencyShadow = false;
  14604. this._viewMatrix = BABYLON.Matrix.Zero();
  14605. this._projectionMatrix = BABYLON.Matrix.Zero();
  14606. this._transformMatrix = BABYLON.Matrix.Zero();
  14607. this._worldViewProjection = BABYLON.Matrix.Zero();
  14608. this._currentFaceIndex = 0;
  14609. this._currentFaceIndexCache = 0;
  14610. this._useFullFloat = true;
  14611. this._light = light;
  14612. this._scene = light.getScene();
  14613. this._mapSize = mapSize;
  14614. light._shadowGenerator = this;
  14615. // Texture type fallback from float to int if not supported.
  14616. var textureType;
  14617. var caps = this._scene.getEngine().getCaps();
  14618. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  14619. this._useFullFloat = true;
  14620. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14621. }
  14622. else {
  14623. this._useFullFloat = false;
  14624. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14625. }
  14626. // Render target
  14627. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  14628. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14629. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14630. this._shadowMap.anisotropicFilteringLevel = 1;
  14631. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14632. this._shadowMap.renderParticles = false;
  14633. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  14634. _this._currentFaceIndex = faceIndex;
  14635. });
  14636. this._shadowMap.onAfterUnbindObservable.add(function () {
  14637. if (!_this.useBlurVarianceShadowMap) {
  14638. return;
  14639. }
  14640. if (!_this._shadowMap2) {
  14641. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  14642. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14643. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14644. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  14645. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  14646. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  14647. effect.setTexture("textureSampler", _this._shadowMap);
  14648. });
  14649. _this.blurBoxOffset = 1;
  14650. }
  14651. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  14652. });
  14653. // Custom render function
  14654. var renderSubMesh = function (subMesh) {
  14655. var mesh = subMesh.getRenderingMesh();
  14656. var scene = _this._scene;
  14657. var engine = scene.getEngine();
  14658. // Culling
  14659. engine.setState(subMesh.getMaterial().backFaceCulling);
  14660. // Managing instances
  14661. var batch = mesh._getInstancesRenderList(subMesh._id);
  14662. if (batch.mustReturn) {
  14663. return;
  14664. }
  14665. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14666. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  14667. engine.enableEffect(_this._effect);
  14668. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  14669. var material = subMesh.getMaterial();
  14670. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  14671. _this._effect.setVector3("lightPosition", _this.getLight().position);
  14672. if (_this.getLight().needCube()) {
  14673. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  14674. }
  14675. // Alpha test
  14676. if (material && material.needAlphaTesting()) {
  14677. var alphaTexture = material.getAlphaTestTexture();
  14678. _this._effect.setTexture("diffuseSampler", alphaTexture);
  14679. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  14680. }
  14681. // Bones
  14682. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14683. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  14684. }
  14685. if (_this.forceBackFacesOnly) {
  14686. engine.setState(true, 0, false, true);
  14687. }
  14688. // Draw
  14689. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  14690. if (_this.forceBackFacesOnly) {
  14691. engine.setState(true, 0, false, false);
  14692. }
  14693. }
  14694. else {
  14695. // Need to reset refresh rate of the shadowMap
  14696. _this._shadowMap.resetRefreshCounter();
  14697. }
  14698. };
  14699. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  14700. var index;
  14701. for (index = 0; index < opaqueSubMeshes.length; index++) {
  14702. renderSubMesh(opaqueSubMeshes.data[index]);
  14703. }
  14704. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  14705. renderSubMesh(alphaTestSubMeshes.data[index]);
  14706. }
  14707. if (_this._transparencyShadow) {
  14708. for (index = 0; index < transparentSubMeshes.length; index++) {
  14709. renderSubMesh(transparentSubMeshes.data[index]);
  14710. }
  14711. }
  14712. };
  14713. this._shadowMap.onClearObservable.add(function (engine) {
  14714. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  14715. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  14716. }
  14717. else {
  14718. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  14719. }
  14720. });
  14721. }
  14722. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  14723. // Static
  14724. get: function () {
  14725. return ShadowGenerator._FILTER_NONE;
  14726. },
  14727. enumerable: true,
  14728. configurable: true
  14729. });
  14730. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  14731. get: function () {
  14732. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  14733. },
  14734. enumerable: true,
  14735. configurable: true
  14736. });
  14737. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  14738. get: function () {
  14739. return ShadowGenerator._FILTER_POISSONSAMPLING;
  14740. },
  14741. enumerable: true,
  14742. configurable: true
  14743. });
  14744. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  14745. get: function () {
  14746. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  14747. },
  14748. enumerable: true,
  14749. configurable: true
  14750. });
  14751. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  14752. get: function () {
  14753. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  14754. },
  14755. enumerable: true,
  14756. configurable: true
  14757. });
  14758. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  14759. get: function () {
  14760. return this._bias;
  14761. },
  14762. set: function (bias) {
  14763. this._bias = bias;
  14764. },
  14765. enumerable: true,
  14766. configurable: true
  14767. });
  14768. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  14769. get: function () {
  14770. return this._blurBoxOffset;
  14771. },
  14772. set: function (value) {
  14773. var _this = this;
  14774. if (this._blurBoxOffset === value) {
  14775. return;
  14776. }
  14777. this._blurBoxOffset = value;
  14778. if (this._boxBlurPostprocess) {
  14779. this._boxBlurPostprocess.dispose();
  14780. }
  14781. 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);
  14782. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  14783. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  14784. });
  14785. },
  14786. enumerable: true,
  14787. configurable: true
  14788. });
  14789. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  14790. get: function () {
  14791. return this._filter;
  14792. },
  14793. set: function (value) {
  14794. if (this._filter === value) {
  14795. return;
  14796. }
  14797. this._filter = value;
  14798. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  14799. this._shadowMap.anisotropicFilteringLevel = 16;
  14800. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14801. }
  14802. else {
  14803. this._shadowMap.anisotropicFilteringLevel = 1;
  14804. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14805. }
  14806. },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  14811. get: function () {
  14812. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  14813. },
  14814. set: function (value) {
  14815. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  14816. },
  14817. enumerable: true,
  14818. configurable: true
  14819. });
  14820. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  14821. get: function () {
  14822. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  14823. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  14824. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  14825. },
  14826. set: function (value) {
  14827. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  14828. },
  14829. enumerable: true,
  14830. configurable: true
  14831. });
  14832. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  14833. get: function () {
  14834. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  14835. },
  14836. set: function (value) {
  14837. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  14838. },
  14839. enumerable: true,
  14840. configurable: true
  14841. });
  14842. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  14843. get: function () {
  14844. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  14845. },
  14846. set: function (value) {
  14847. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  14848. },
  14849. enumerable: true,
  14850. configurable: true
  14851. });
  14852. /**
  14853. * Boolean : true when the ShadowGenerator is finally computed.
  14854. */
  14855. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  14856. var defines = [];
  14857. if (this._useFullFloat) {
  14858. defines.push("#define FULLFLOAT");
  14859. }
  14860. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  14861. defines.push("#define VSM");
  14862. }
  14863. if (this.getLight().needCube()) {
  14864. defines.push("#define CUBEMAP");
  14865. }
  14866. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14867. var mesh = subMesh.getMesh();
  14868. var material = subMesh.getMaterial();
  14869. // Alpha test
  14870. if (material && material.needAlphaTesting()) {
  14871. defines.push("#define ALPHATEST");
  14872. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14873. attribs.push(BABYLON.VertexBuffer.UVKind);
  14874. defines.push("#define UV1");
  14875. }
  14876. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14877. var alphaTexture = material.getAlphaTestTexture();
  14878. if (alphaTexture.coordinatesIndex === 1) {
  14879. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14880. defines.push("#define UV2");
  14881. }
  14882. }
  14883. }
  14884. // Bones
  14885. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14886. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14887. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14888. if (mesh.numBoneInfluencers > 4) {
  14889. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  14890. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  14891. }
  14892. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  14893. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14894. }
  14895. else {
  14896. defines.push("#define NUM_BONE_INFLUENCERS 0");
  14897. }
  14898. // Instances
  14899. if (useInstances) {
  14900. defines.push("#define INSTANCES");
  14901. attribs.push("world0");
  14902. attribs.push("world1");
  14903. attribs.push("world2");
  14904. attribs.push("world3");
  14905. }
  14906. // Get correct effect
  14907. var join = defines.join("\n");
  14908. if (this._cachedDefines !== join) {
  14909. this._cachedDefines = join;
  14910. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  14911. }
  14912. return this._effect.isReady();
  14913. };
  14914. /**
  14915. * Returns a RenderTargetTexture object : the shadow map texture.
  14916. */
  14917. ShadowGenerator.prototype.getShadowMap = function () {
  14918. return this._shadowMap;
  14919. };
  14920. /**
  14921. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  14922. */
  14923. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  14924. if (this._shadowMap2) {
  14925. return this._shadowMap2;
  14926. }
  14927. return this._shadowMap;
  14928. };
  14929. /**
  14930. * Returns the associated light object.
  14931. */
  14932. ShadowGenerator.prototype.getLight = function () {
  14933. return this._light;
  14934. };
  14935. // Methods
  14936. /**
  14937. * Returns a Matrix object : the updated transformation matrix.
  14938. */
  14939. ShadowGenerator.prototype.getTransformMatrix = function () {
  14940. var scene = this._scene;
  14941. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  14942. return this._transformMatrix;
  14943. }
  14944. this._currentRenderID = scene.getRenderId();
  14945. this._currentFaceIndexCache = this._currentFaceIndex;
  14946. var lightPosition = this._light.position;
  14947. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  14948. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  14949. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  14950. }
  14951. if (this._light.computeTransformedPosition()) {
  14952. lightPosition = this._light.transformedPosition;
  14953. }
  14954. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  14955. this._cachedPosition = lightPosition.clone();
  14956. this._cachedDirection = this._lightDirection.clone();
  14957. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  14958. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  14959. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14960. }
  14961. return this._transformMatrix;
  14962. };
  14963. /**
  14964. * Returns the darkness value (float).
  14965. */
  14966. ShadowGenerator.prototype.getDarkness = function () {
  14967. return this._darkness;
  14968. };
  14969. /**
  14970. * Sets the ShadowGenerator darkness value (float <= 1.0).
  14971. * Returns the ShadowGenerator.
  14972. */
  14973. ShadowGenerator.prototype.setDarkness = function (darkness) {
  14974. if (darkness >= 1.0)
  14975. this._darkness = 1.0;
  14976. else if (darkness <= 0.0)
  14977. this._darkness = 0.0;
  14978. else
  14979. this._darkness = darkness;
  14980. return this;
  14981. };
  14982. /**
  14983. * Sets the ability to have transparent shadow (boolean).
  14984. * Returns the ShadowGenerator.
  14985. */
  14986. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  14987. this._transparencyShadow = hasShadow;
  14988. return this;
  14989. };
  14990. ShadowGenerator.prototype._packHalf = function (depth) {
  14991. var scale = depth * 255.0;
  14992. var fract = scale - Math.floor(scale);
  14993. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  14994. };
  14995. /**
  14996. * Disposes the ShadowGenerator.
  14997. * Returns nothing.
  14998. */
  14999. ShadowGenerator.prototype.dispose = function () {
  15000. this._shadowMap.dispose();
  15001. if (this._shadowMap2) {
  15002. this._shadowMap2.dispose();
  15003. }
  15004. if (this._downSamplePostprocess) {
  15005. this._downSamplePostprocess.dispose();
  15006. }
  15007. if (this._boxBlurPostprocess) {
  15008. this._boxBlurPostprocess.dispose();
  15009. }
  15010. this._light._shadowGenerator = null;
  15011. };
  15012. /**
  15013. * Serializes the ShadowGenerator and returns a serializationObject.
  15014. */
  15015. ShadowGenerator.prototype.serialize = function () {
  15016. var serializationObject = {};
  15017. serializationObject.lightId = this._light.id;
  15018. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  15019. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  15020. serializationObject.usePoissonSampling = this.usePoissonSampling;
  15021. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  15022. serializationObject.darkness = this.getDarkness();
  15023. serializationObject.renderList = [];
  15024. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  15025. var mesh = this.getShadowMap().renderList[meshIndex];
  15026. serializationObject.renderList.push(mesh.id);
  15027. }
  15028. return serializationObject;
  15029. };
  15030. /**
  15031. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  15032. */
  15033. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  15034. //casting to point light, as light is missing the position attr and typescript complains.
  15035. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  15036. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  15037. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  15038. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  15039. meshes.forEach(function (mesh) {
  15040. shadowGenerator.getShadowMap().renderList.push(mesh);
  15041. });
  15042. }
  15043. if (parsedShadowGenerator.usePoissonSampling) {
  15044. shadowGenerator.usePoissonSampling = true;
  15045. }
  15046. else if (parsedShadowGenerator.useVarianceShadowMap) {
  15047. shadowGenerator.useVarianceShadowMap = true;
  15048. }
  15049. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  15050. shadowGenerator.useBlurVarianceShadowMap = true;
  15051. if (parsedShadowGenerator.blurScale) {
  15052. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  15053. }
  15054. if (parsedShadowGenerator.blurBoxOffset) {
  15055. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  15056. }
  15057. }
  15058. if (parsedShadowGenerator.bias !== undefined) {
  15059. shadowGenerator.bias = parsedShadowGenerator.bias;
  15060. }
  15061. if (parsedShadowGenerator.darkness) {
  15062. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  15063. }
  15064. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  15065. return shadowGenerator;
  15066. };
  15067. return ShadowGenerator;
  15068. }());
  15069. ShadowGenerator._FILTER_NONE = 0;
  15070. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  15071. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  15072. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  15073. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 4;
  15074. BABYLON.ShadowGenerator = ShadowGenerator;
  15075. })(BABYLON || (BABYLON = {}));
  15076. //# sourceMappingURL=babylon.shadowGenerator.js.map
  15077. var BABYLON;
  15078. (function (BABYLON) {
  15079. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  15080. if (boxMin.x > sphereCenter.x + sphereRadius)
  15081. return false;
  15082. if (sphereCenter.x - sphereRadius > boxMax.x)
  15083. return false;
  15084. if (boxMin.y > sphereCenter.y + sphereRadius)
  15085. return false;
  15086. if (sphereCenter.y - sphereRadius > boxMax.y)
  15087. return false;
  15088. if (boxMin.z > sphereCenter.z + sphereRadius)
  15089. return false;
  15090. if (sphereCenter.z - sphereRadius > boxMax.z)
  15091. return false;
  15092. return true;
  15093. };
  15094. var getLowestRoot = (function () {
  15095. var result = { root: 0, found: false };
  15096. return function (a, b, c, maxR) {
  15097. result.root = 0;
  15098. result.found = false;
  15099. var determinant = b * b - 4.0 * a * c;
  15100. if (determinant < 0)
  15101. return result;
  15102. var sqrtD = Math.sqrt(determinant);
  15103. var r1 = (-b - sqrtD) / (2.0 * a);
  15104. var r2 = (-b + sqrtD) / (2.0 * a);
  15105. if (r1 > r2) {
  15106. var temp = r2;
  15107. r2 = r1;
  15108. r1 = temp;
  15109. }
  15110. if (r1 > 0 && r1 < maxR) {
  15111. result.root = r1;
  15112. result.found = true;
  15113. return result;
  15114. }
  15115. if (r2 > 0 && r2 < maxR) {
  15116. result.root = r2;
  15117. result.found = true;
  15118. return result;
  15119. }
  15120. return result;
  15121. };
  15122. })();
  15123. var Collider = (function () {
  15124. function Collider() {
  15125. this.radius = new BABYLON.Vector3(1, 1, 1);
  15126. this.retry = 0;
  15127. this.basePointWorld = BABYLON.Vector3.Zero();
  15128. this.velocityWorld = BABYLON.Vector3.Zero();
  15129. this.normalizedVelocity = BABYLON.Vector3.Zero();
  15130. this._collisionPoint = BABYLON.Vector3.Zero();
  15131. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  15132. this._tempVector = BABYLON.Vector3.Zero();
  15133. this._tempVector2 = BABYLON.Vector3.Zero();
  15134. this._tempVector3 = BABYLON.Vector3.Zero();
  15135. this._tempVector4 = BABYLON.Vector3.Zero();
  15136. this._edge = BABYLON.Vector3.Zero();
  15137. this._baseToVertex = BABYLON.Vector3.Zero();
  15138. this._destinationPoint = BABYLON.Vector3.Zero();
  15139. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  15140. this._displacementVector = BABYLON.Vector3.Zero();
  15141. this._collisionMask = -1;
  15142. }
  15143. Object.defineProperty(Collider.prototype, "collisionMask", {
  15144. get: function () {
  15145. return this._collisionMask;
  15146. },
  15147. set: function (mask) {
  15148. this._collisionMask = !isNaN(mask) ? mask : -1;
  15149. },
  15150. enumerable: true,
  15151. configurable: true
  15152. });
  15153. // Methods
  15154. Collider.prototype._initialize = function (source, dir, e) {
  15155. this.velocity = dir;
  15156. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  15157. this.basePoint = source;
  15158. source.multiplyToRef(this.radius, this.basePointWorld);
  15159. dir.multiplyToRef(this.radius, this.velocityWorld);
  15160. this.velocityWorldLength = this.velocityWorld.length();
  15161. this.epsilon = e;
  15162. this.collisionFound = false;
  15163. };
  15164. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  15165. pa.subtractToRef(point, this._tempVector);
  15166. pb.subtractToRef(point, this._tempVector2);
  15167. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  15168. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15169. if (d < 0)
  15170. return false;
  15171. pc.subtractToRef(point, this._tempVector3);
  15172. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  15173. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15174. if (d < 0)
  15175. return false;
  15176. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  15177. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15178. return d >= 0;
  15179. };
  15180. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  15181. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  15182. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  15183. if (distance > this.velocityWorldLength + max + sphereRadius) {
  15184. return false;
  15185. }
  15186. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  15187. return false;
  15188. return true;
  15189. };
  15190. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  15191. var t0;
  15192. var embeddedInPlane = false;
  15193. //defensive programming, actually not needed.
  15194. if (!trianglePlaneArray) {
  15195. trianglePlaneArray = [];
  15196. }
  15197. if (!trianglePlaneArray[faceIndex]) {
  15198. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  15199. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  15200. }
  15201. var trianglePlane = trianglePlaneArray[faceIndex];
  15202. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  15203. return;
  15204. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  15205. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  15206. if (normalDotVelocity == 0) {
  15207. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  15208. return;
  15209. embeddedInPlane = true;
  15210. t0 = 0;
  15211. }
  15212. else {
  15213. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15214. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15215. if (t0 > t1) {
  15216. var temp = t1;
  15217. t1 = t0;
  15218. t0 = temp;
  15219. }
  15220. if (t0 > 1.0 || t1 < 0.0)
  15221. return;
  15222. if (t0 < 0)
  15223. t0 = 0;
  15224. if (t0 > 1.0)
  15225. t0 = 1.0;
  15226. }
  15227. this._collisionPoint.copyFromFloats(0, 0, 0);
  15228. var found = false;
  15229. var t = 1.0;
  15230. if (!embeddedInPlane) {
  15231. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  15232. this.velocity.scaleToRef(t0, this._tempVector);
  15233. this._planeIntersectionPoint.addInPlace(this._tempVector);
  15234. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  15235. found = true;
  15236. t = t0;
  15237. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  15238. }
  15239. }
  15240. if (!found) {
  15241. var velocitySquaredLength = this.velocity.lengthSquared();
  15242. var a = velocitySquaredLength;
  15243. this.basePoint.subtractToRef(p1, this._tempVector);
  15244. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15245. var c = this._tempVector.lengthSquared() - 1.0;
  15246. var lowestRoot = getLowestRoot(a, b, c, t);
  15247. if (lowestRoot.found) {
  15248. t = lowestRoot.root;
  15249. found = true;
  15250. this._collisionPoint.copyFrom(p1);
  15251. }
  15252. this.basePoint.subtractToRef(p2, this._tempVector);
  15253. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15254. c = this._tempVector.lengthSquared() - 1.0;
  15255. lowestRoot = getLowestRoot(a, b, c, t);
  15256. if (lowestRoot.found) {
  15257. t = lowestRoot.root;
  15258. found = true;
  15259. this._collisionPoint.copyFrom(p2);
  15260. }
  15261. this.basePoint.subtractToRef(p3, this._tempVector);
  15262. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15263. c = this._tempVector.lengthSquared() - 1.0;
  15264. lowestRoot = getLowestRoot(a, b, c, t);
  15265. if (lowestRoot.found) {
  15266. t = lowestRoot.root;
  15267. found = true;
  15268. this._collisionPoint.copyFrom(p3);
  15269. }
  15270. p2.subtractToRef(p1, this._edge);
  15271. p1.subtractToRef(this.basePoint, this._baseToVertex);
  15272. var edgeSquaredLength = this._edge.lengthSquared();
  15273. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15274. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15275. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15276. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15277. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15278. lowestRoot = getLowestRoot(a, b, c, t);
  15279. if (lowestRoot.found) {
  15280. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15281. if (f >= 0.0 && f <= 1.0) {
  15282. t = lowestRoot.root;
  15283. found = true;
  15284. this._edge.scaleInPlace(f);
  15285. p1.addToRef(this._edge, this._collisionPoint);
  15286. }
  15287. }
  15288. p3.subtractToRef(p2, this._edge);
  15289. p2.subtractToRef(this.basePoint, this._baseToVertex);
  15290. edgeSquaredLength = this._edge.lengthSquared();
  15291. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15292. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15293. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15294. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15295. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15296. lowestRoot = getLowestRoot(a, b, c, t);
  15297. if (lowestRoot.found) {
  15298. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15299. if (f >= 0.0 && f <= 1.0) {
  15300. t = lowestRoot.root;
  15301. found = true;
  15302. this._edge.scaleInPlace(f);
  15303. p2.addToRef(this._edge, this._collisionPoint);
  15304. }
  15305. }
  15306. p1.subtractToRef(p3, this._edge);
  15307. p3.subtractToRef(this.basePoint, this._baseToVertex);
  15308. edgeSquaredLength = this._edge.lengthSquared();
  15309. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15310. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15311. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15312. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15313. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15314. lowestRoot = getLowestRoot(a, b, c, t);
  15315. if (lowestRoot.found) {
  15316. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15317. if (f >= 0.0 && f <= 1.0) {
  15318. t = lowestRoot.root;
  15319. found = true;
  15320. this._edge.scaleInPlace(f);
  15321. p3.addToRef(this._edge, this._collisionPoint);
  15322. }
  15323. }
  15324. }
  15325. if (found) {
  15326. var distToCollision = t * this.velocity.length();
  15327. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  15328. if (!this.intersectionPoint) {
  15329. this.intersectionPoint = this._collisionPoint.clone();
  15330. }
  15331. else {
  15332. this.intersectionPoint.copyFrom(this._collisionPoint);
  15333. }
  15334. this.nearestDistance = distToCollision;
  15335. this.collisionFound = true;
  15336. }
  15337. }
  15338. };
  15339. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  15340. for (var i = indexStart; i < indexEnd; i += 3) {
  15341. var p1 = pts[indices[i] - decal];
  15342. var p2 = pts[indices[i + 1] - decal];
  15343. var p3 = pts[indices[i + 2] - decal];
  15344. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  15345. }
  15346. };
  15347. Collider.prototype._getResponse = function (pos, vel) {
  15348. pos.addToRef(vel, this._destinationPoint);
  15349. vel.scaleInPlace((this.nearestDistance / vel.length()));
  15350. this.basePoint.addToRef(vel, pos);
  15351. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  15352. this._slidePlaneNormal.normalize();
  15353. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  15354. pos.addInPlace(this._displacementVector);
  15355. this.intersectionPoint.addInPlace(this._displacementVector);
  15356. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  15357. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  15358. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  15359. };
  15360. return Collider;
  15361. }());
  15362. BABYLON.Collider = Collider;
  15363. })(BABYLON || (BABYLON = {}));
  15364. //# sourceMappingURL=babylon.collider.js.map
  15365. var BABYLON;
  15366. (function (BABYLON) {
  15367. //WebWorker code will be inserted to this variable.
  15368. BABYLON.CollisionWorker = "";
  15369. var WorkerTaskType;
  15370. (function (WorkerTaskType) {
  15371. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  15372. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  15373. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  15374. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  15375. var WorkerReplyType;
  15376. (function (WorkerReplyType) {
  15377. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  15378. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  15379. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  15380. var CollisionCoordinatorWorker = (function () {
  15381. function CollisionCoordinatorWorker() {
  15382. var _this = this;
  15383. this._scaledPosition = BABYLON.Vector3.Zero();
  15384. this._scaledVelocity = BABYLON.Vector3.Zero();
  15385. this.onMeshUpdated = function (mesh) {
  15386. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  15387. };
  15388. this.onGeometryUpdated = function (geometry) {
  15389. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  15390. };
  15391. this._afterRender = function () {
  15392. if (!_this._init)
  15393. return;
  15394. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  15395. return;
  15396. }
  15397. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  15398. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  15399. if (_this._runningUpdated > 4) {
  15400. return;
  15401. }
  15402. ++_this._runningUpdated;
  15403. var payload = {
  15404. updatedMeshes: _this._addUpdateMeshesList,
  15405. updatedGeometries: _this._addUpdateGeometriesList,
  15406. removedGeometries: _this._toRemoveGeometryArray,
  15407. removedMeshes: _this._toRemoveMeshesArray
  15408. };
  15409. var message = {
  15410. payload: payload,
  15411. taskType: WorkerTaskType.UPDATE
  15412. };
  15413. var serializable = [];
  15414. for (var id in payload.updatedGeometries) {
  15415. if (payload.updatedGeometries.hasOwnProperty(id)) {
  15416. //prepare transferables
  15417. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  15418. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  15419. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  15420. }
  15421. }
  15422. _this._worker.postMessage(message, serializable);
  15423. _this._addUpdateMeshesList = {};
  15424. _this._addUpdateGeometriesList = {};
  15425. _this._toRemoveGeometryArray = [];
  15426. _this._toRemoveMeshesArray = [];
  15427. };
  15428. this._onMessageFromWorker = function (e) {
  15429. var returnData = e.data;
  15430. if (returnData.error != WorkerReplyType.SUCCESS) {
  15431. //TODO what errors can be returned from the worker?
  15432. BABYLON.Tools.Warn("error returned from worker!");
  15433. return;
  15434. }
  15435. switch (returnData.taskType) {
  15436. case WorkerTaskType.INIT:
  15437. _this._init = true;
  15438. //Update the worked with ALL of the scene's current state
  15439. _this._scene.meshes.forEach(function (mesh) {
  15440. _this.onMeshAdded(mesh);
  15441. });
  15442. _this._scene.getGeometries().forEach(function (geometry) {
  15443. _this.onGeometryAdded(geometry);
  15444. });
  15445. break;
  15446. case WorkerTaskType.UPDATE:
  15447. _this._runningUpdated--;
  15448. break;
  15449. case WorkerTaskType.COLLIDE:
  15450. _this._runningCollisionTask = false;
  15451. var returnPayload = returnData.payload;
  15452. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  15453. return;
  15454. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  15455. //cleanup
  15456. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  15457. break;
  15458. }
  15459. };
  15460. this._collisionsCallbackArray = [];
  15461. this._init = false;
  15462. this._runningUpdated = 0;
  15463. this._runningCollisionTask = false;
  15464. this._addUpdateMeshesList = {};
  15465. this._addUpdateGeometriesList = {};
  15466. this._toRemoveGeometryArray = [];
  15467. this._toRemoveMeshesArray = [];
  15468. }
  15469. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15470. if (!this._init)
  15471. return;
  15472. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  15473. return;
  15474. position.divideToRef(collider.radius, this._scaledPosition);
  15475. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15476. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  15477. var payload = {
  15478. collider: {
  15479. position: this._scaledPosition.asArray(),
  15480. velocity: this._scaledVelocity.asArray(),
  15481. radius: collider.radius.asArray()
  15482. },
  15483. collisionId: collisionIndex,
  15484. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  15485. maximumRetry: maximumRetry
  15486. };
  15487. var message = {
  15488. payload: payload,
  15489. taskType: WorkerTaskType.COLLIDE
  15490. };
  15491. this._worker.postMessage(message);
  15492. };
  15493. CollisionCoordinatorWorker.prototype.init = function (scene) {
  15494. this._scene = scene;
  15495. this._scene.registerAfterRender(this._afterRender);
  15496. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  15497. this._worker = new Worker(workerUrl);
  15498. this._worker.onmessage = this._onMessageFromWorker;
  15499. var message = {
  15500. payload: {},
  15501. taskType: WorkerTaskType.INIT
  15502. };
  15503. this._worker.postMessage(message);
  15504. };
  15505. CollisionCoordinatorWorker.prototype.destroy = function () {
  15506. this._scene.unregisterAfterRender(this._afterRender);
  15507. this._worker.terminate();
  15508. };
  15509. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  15510. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  15511. this.onMeshUpdated(mesh);
  15512. };
  15513. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  15514. this._toRemoveMeshesArray.push(mesh.uniqueId);
  15515. };
  15516. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  15517. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  15518. geometry.onGeometryUpdated = this.onGeometryUpdated;
  15519. this.onGeometryUpdated(geometry);
  15520. };
  15521. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  15522. this._toRemoveGeometryArray.push(geometry.id);
  15523. };
  15524. return CollisionCoordinatorWorker;
  15525. }());
  15526. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  15527. var submeshes = [];
  15528. if (mesh.subMeshes) {
  15529. submeshes = mesh.subMeshes.map(function (sm, idx) {
  15530. return {
  15531. position: idx,
  15532. verticesStart: sm.verticesStart,
  15533. verticesCount: sm.verticesCount,
  15534. indexStart: sm.indexStart,
  15535. indexCount: sm.indexCount,
  15536. hasMaterial: !!sm.getMaterial(),
  15537. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15538. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  15539. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15540. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  15541. };
  15542. });
  15543. }
  15544. var geometryId = null;
  15545. if (mesh instanceof BABYLON.Mesh) {
  15546. geometryId = mesh.geometry ? mesh.geometry.id : null;
  15547. }
  15548. else if (mesh instanceof BABYLON.InstancedMesh) {
  15549. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  15550. }
  15551. return {
  15552. uniqueId: mesh.uniqueId,
  15553. id: mesh.id,
  15554. name: mesh.name,
  15555. geometryId: geometryId,
  15556. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15557. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  15558. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15559. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  15560. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  15561. subMeshes: submeshes,
  15562. checkCollisions: mesh.checkCollisions
  15563. };
  15564. };
  15565. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  15566. return {
  15567. id: geometry.id,
  15568. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  15569. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  15570. indices: new Uint32Array(geometry.getIndices() || []),
  15571. };
  15572. };
  15573. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  15574. var CollisionCoordinatorLegacy = (function () {
  15575. function CollisionCoordinatorLegacy() {
  15576. this._scaledPosition = BABYLON.Vector3.Zero();
  15577. this._scaledVelocity = BABYLON.Vector3.Zero();
  15578. this._finalPosition = BABYLON.Vector3.Zero();
  15579. }
  15580. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15581. position.divideToRef(collider.radius, this._scaledPosition);
  15582. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15583. collider.collidedMesh = null;
  15584. collider.retry = 0;
  15585. collider.initialVelocity = this._scaledVelocity;
  15586. collider.initialPosition = this._scaledPosition;
  15587. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  15588. this._finalPosition.multiplyInPlace(collider.radius);
  15589. //run the callback
  15590. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  15591. };
  15592. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  15593. this._scene = scene;
  15594. };
  15595. CollisionCoordinatorLegacy.prototype.destroy = function () {
  15596. //Legacy need no destruction method.
  15597. };
  15598. //No update in legacy mode
  15599. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  15600. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  15601. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  15602. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  15603. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  15604. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  15605. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  15606. if (excludedMesh === void 0) { excludedMesh = null; }
  15607. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  15608. if (collider.retry >= maximumRetry) {
  15609. finalPosition.copyFrom(position);
  15610. return;
  15611. }
  15612. // Check if this is a mesh else camera or -1
  15613. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  15614. collider._initialize(position, velocity, closeDistance);
  15615. // Check all meshes
  15616. for (var index = 0; index < this._scene.meshes.length; index++) {
  15617. var mesh = this._scene.meshes[index];
  15618. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  15619. mesh._checkCollision(collider);
  15620. }
  15621. }
  15622. if (!collider.collisionFound) {
  15623. position.addToRef(velocity, finalPosition);
  15624. return;
  15625. }
  15626. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  15627. collider._getResponse(position, velocity);
  15628. }
  15629. if (velocity.length() <= closeDistance) {
  15630. finalPosition.copyFrom(position);
  15631. return;
  15632. }
  15633. collider.retry++;
  15634. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  15635. };
  15636. return CollisionCoordinatorLegacy;
  15637. }());
  15638. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  15639. })(BABYLON || (BABYLON = {}));
  15640. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  15641. var BABYLON;
  15642. (function (BABYLON) {
  15643. var Camera = (function (_super) {
  15644. __extends(Camera, _super);
  15645. function Camera(name, position, scene) {
  15646. var _this = _super.call(this, name, scene) || this;
  15647. _this.upVector = BABYLON.Vector3.Up();
  15648. _this.orthoLeft = null;
  15649. _this.orthoRight = null;
  15650. _this.orthoBottom = null;
  15651. _this.orthoTop = null;
  15652. _this.fov = 0.8;
  15653. _this.minZ = 1.0;
  15654. _this.maxZ = 10000.0;
  15655. _this.inertia = 0.9;
  15656. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15657. _this.isIntermediate = false;
  15658. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15659. _this.layerMask = 0x0FFFFFFF;
  15660. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15661. // Camera rig members
  15662. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15663. _this._rigCameras = new Array();
  15664. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15665. // Cache
  15666. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15667. _this._projectionMatrix = new BABYLON.Matrix();
  15668. _this._doNotComputeProjectionMatrix = false;
  15669. _this._postProcesses = new Array();
  15670. _this._transformMatrix = BABYLON.Matrix.Zero();
  15671. _this._activeMeshes = new BABYLON.SmartArray(256);
  15672. _this._globalPosition = BABYLON.Vector3.Zero();
  15673. _this._refreshFrustumPlanes = true;
  15674. _this.getScene().addCamera(_this);
  15675. if (!_this.getScene().activeCamera) {
  15676. _this.getScene().activeCamera = _this;
  15677. }
  15678. _this.position = position;
  15679. return _this;
  15680. }
  15681. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15682. get: function () {
  15683. return Camera._PERSPECTIVE_CAMERA;
  15684. },
  15685. enumerable: true,
  15686. configurable: true
  15687. });
  15688. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15689. get: function () {
  15690. return Camera._ORTHOGRAPHIC_CAMERA;
  15691. },
  15692. enumerable: true,
  15693. configurable: true
  15694. });
  15695. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15696. get: function () {
  15697. return Camera._FOVMODE_VERTICAL_FIXED;
  15698. },
  15699. enumerable: true,
  15700. configurable: true
  15701. });
  15702. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15703. get: function () {
  15704. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15705. },
  15706. enumerable: true,
  15707. configurable: true
  15708. });
  15709. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15710. get: function () {
  15711. return Camera._RIG_MODE_NONE;
  15712. },
  15713. enumerable: true,
  15714. configurable: true
  15715. });
  15716. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15717. get: function () {
  15718. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15719. },
  15720. enumerable: true,
  15721. configurable: true
  15722. });
  15723. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15724. get: function () {
  15725. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15726. },
  15727. enumerable: true,
  15728. configurable: true
  15729. });
  15730. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15731. get: function () {
  15732. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15733. },
  15734. enumerable: true,
  15735. configurable: true
  15736. });
  15737. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15738. get: function () {
  15739. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15740. },
  15741. enumerable: true,
  15742. configurable: true
  15743. });
  15744. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15745. get: function () {
  15746. return Camera._RIG_MODE_VR;
  15747. },
  15748. enumerable: true,
  15749. configurable: true
  15750. });
  15751. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15752. get: function () {
  15753. return Camera._RIG_MODE_WEBVR;
  15754. },
  15755. enumerable: true,
  15756. configurable: true
  15757. });
  15758. Camera.prototype.getClassName = function () {
  15759. return "Camera";
  15760. };
  15761. /**
  15762. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15763. */
  15764. Camera.prototype.toString = function (fullDetails) {
  15765. var ret = "Name: " + this.name;
  15766. ret += ", type: " + this.getClassName();
  15767. if (this.animations) {
  15768. for (var i = 0; i < this.animations.length; i++) {
  15769. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15770. }
  15771. }
  15772. if (fullDetails) {
  15773. }
  15774. return ret;
  15775. };
  15776. Object.defineProperty(Camera.prototype, "globalPosition", {
  15777. get: function () {
  15778. return this._globalPosition;
  15779. },
  15780. enumerable: true,
  15781. configurable: true
  15782. });
  15783. Camera.prototype.getActiveMeshes = function () {
  15784. return this._activeMeshes;
  15785. };
  15786. Camera.prototype.isActiveMesh = function (mesh) {
  15787. return (this._activeMeshes.indexOf(mesh) !== -1);
  15788. };
  15789. //Cache
  15790. Camera.prototype._initCache = function () {
  15791. _super.prototype._initCache.call(this);
  15792. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15793. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15794. this._cache.mode = undefined;
  15795. this._cache.minZ = undefined;
  15796. this._cache.maxZ = undefined;
  15797. this._cache.fov = undefined;
  15798. this._cache.fovMode = undefined;
  15799. this._cache.aspectRatio = undefined;
  15800. this._cache.orthoLeft = undefined;
  15801. this._cache.orthoRight = undefined;
  15802. this._cache.orthoBottom = undefined;
  15803. this._cache.orthoTop = undefined;
  15804. this._cache.renderWidth = undefined;
  15805. this._cache.renderHeight = undefined;
  15806. };
  15807. Camera.prototype._updateCache = function (ignoreParentClass) {
  15808. if (!ignoreParentClass) {
  15809. _super.prototype._updateCache.call(this);
  15810. }
  15811. var engine = this.getEngine();
  15812. this._cache.position.copyFrom(this.position);
  15813. this._cache.upVector.copyFrom(this.upVector);
  15814. this._cache.mode = this.mode;
  15815. this._cache.minZ = this.minZ;
  15816. this._cache.maxZ = this.maxZ;
  15817. this._cache.fov = this.fov;
  15818. this._cache.fovMode = this.fovMode;
  15819. this._cache.aspectRatio = engine.getAspectRatio(this);
  15820. this._cache.orthoLeft = this.orthoLeft;
  15821. this._cache.orthoRight = this.orthoRight;
  15822. this._cache.orthoBottom = this.orthoBottom;
  15823. this._cache.orthoTop = this.orthoTop;
  15824. this._cache.renderWidth = engine.getRenderWidth();
  15825. this._cache.renderHeight = engine.getRenderHeight();
  15826. };
  15827. Camera.prototype._updateFromScene = function () {
  15828. this.updateCache();
  15829. this.update();
  15830. };
  15831. // Synchronized
  15832. Camera.prototype._isSynchronized = function () {
  15833. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15834. };
  15835. Camera.prototype._isSynchronizedViewMatrix = function () {
  15836. if (!_super.prototype._isSynchronized.call(this))
  15837. return false;
  15838. return this._cache.position.equals(this.position)
  15839. && this._cache.upVector.equals(this.upVector)
  15840. && this.isSynchronizedWithParent();
  15841. };
  15842. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15843. var check = this._cache.mode === this.mode
  15844. && this._cache.minZ === this.minZ
  15845. && this._cache.maxZ === this.maxZ;
  15846. if (!check) {
  15847. return false;
  15848. }
  15849. var engine = this.getEngine();
  15850. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15851. check = this._cache.fov === this.fov
  15852. && this._cache.fovMode === this.fovMode
  15853. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15854. }
  15855. else {
  15856. check = this._cache.orthoLeft === this.orthoLeft
  15857. && this._cache.orthoRight === this.orthoRight
  15858. && this._cache.orthoBottom === this.orthoBottom
  15859. && this._cache.orthoTop === this.orthoTop
  15860. && this._cache.renderWidth === engine.getRenderWidth()
  15861. && this._cache.renderHeight === engine.getRenderHeight();
  15862. }
  15863. return check;
  15864. };
  15865. // Controls
  15866. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15867. };
  15868. Camera.prototype.detachControl = function (element) {
  15869. };
  15870. Camera.prototype.update = function () {
  15871. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15872. this._updateRigCameras();
  15873. }
  15874. this._checkInputs();
  15875. };
  15876. Camera.prototype._checkInputs = function () {
  15877. };
  15878. Object.defineProperty(Camera.prototype, "rigCameras", {
  15879. get: function () {
  15880. return this._rigCameras;
  15881. },
  15882. enumerable: true,
  15883. configurable: true
  15884. });
  15885. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15886. get: function () {
  15887. return this._rigPostProcess;
  15888. },
  15889. enumerable: true,
  15890. configurable: true
  15891. });
  15892. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15893. // invalidate framebuffer
  15894. if (this._postProcesses.length > 0) {
  15895. this._postProcesses[0].markTextureDirty();
  15896. }
  15897. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15898. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15899. var cam = this._rigCameras[i];
  15900. var rigPostProcess = cam._rigPostProcess;
  15901. // for VR rig, there does not have to be a post process
  15902. if (rigPostProcess) {
  15903. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15904. if (isPass) {
  15905. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15906. cam.isIntermediate = this._postProcesses.length === 0;
  15907. }
  15908. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15909. rigPostProcess.markTextureDirty();
  15910. }
  15911. else {
  15912. cam._postProcesses = this._postProcesses.slice(0);
  15913. }
  15914. }
  15915. };
  15916. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15917. if (insertAt === void 0) { insertAt = null; }
  15918. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15919. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15920. return 0;
  15921. }
  15922. if (insertAt == null || insertAt < 0) {
  15923. this._postProcesses.push(postProcess);
  15924. }
  15925. else {
  15926. this._postProcesses.splice(insertAt, 0, postProcess);
  15927. }
  15928. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15929. return this._postProcesses.indexOf(postProcess);
  15930. };
  15931. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15932. if (atIndices === void 0) { atIndices = null; }
  15933. var result = [];
  15934. var i;
  15935. var index;
  15936. if (!atIndices) {
  15937. var idx = this._postProcesses.indexOf(postProcess);
  15938. if (idx !== -1) {
  15939. this._postProcesses.splice(idx, 1);
  15940. }
  15941. }
  15942. else {
  15943. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15944. // iterate descending, so can just splice as we go
  15945. for (i = atIndices.length - 1; i >= 0; i--) {
  15946. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15947. result.push(i);
  15948. continue;
  15949. }
  15950. index = atIndices[i];
  15951. this._postProcesses.splice(index, 1);
  15952. }
  15953. }
  15954. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15955. return result;
  15956. };
  15957. Camera.prototype.getWorldMatrix = function () {
  15958. if (!this._worldMatrix) {
  15959. this._worldMatrix = BABYLON.Matrix.Identity();
  15960. }
  15961. var viewMatrix = this.getViewMatrix();
  15962. viewMatrix.invertToRef(this._worldMatrix);
  15963. return this._worldMatrix;
  15964. };
  15965. Camera.prototype._getViewMatrix = function () {
  15966. return BABYLON.Matrix.Identity();
  15967. };
  15968. Camera.prototype.getViewMatrix = function (force) {
  15969. this._computedViewMatrix = this._computeViewMatrix(force);
  15970. if (!force && this._isSynchronizedViewMatrix()) {
  15971. return this._computedViewMatrix;
  15972. }
  15973. this._refreshFrustumPlanes = true;
  15974. if (!this.parent || !this.parent.getWorldMatrix) {
  15975. this._globalPosition.copyFrom(this.position);
  15976. }
  15977. else {
  15978. if (!this._worldMatrix) {
  15979. this._worldMatrix = BABYLON.Matrix.Identity();
  15980. }
  15981. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15982. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15983. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15984. this._computedViewMatrix.invert();
  15985. this._markSyncedWithParent();
  15986. }
  15987. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15988. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15989. }
  15990. this._currentRenderId = this.getScene().getRenderId();
  15991. return this._computedViewMatrix;
  15992. };
  15993. Camera.prototype._computeViewMatrix = function (force) {
  15994. if (!force && this._isSynchronizedViewMatrix()) {
  15995. return this._computedViewMatrix;
  15996. }
  15997. this._computedViewMatrix = this._getViewMatrix();
  15998. this._currentRenderId = this.getScene().getRenderId();
  15999. return this._computedViewMatrix;
  16000. };
  16001. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16002. this._doNotComputeProjectionMatrix = true;
  16003. if (projection !== undefined) {
  16004. this._projectionMatrix = projection;
  16005. }
  16006. };
  16007. ;
  16008. Camera.prototype.unfreezeProjectionMatrix = function () {
  16009. this._doNotComputeProjectionMatrix = false;
  16010. };
  16011. ;
  16012. Camera.prototype.getProjectionMatrix = function (force) {
  16013. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16014. return this._projectionMatrix;
  16015. }
  16016. this._refreshFrustumPlanes = true;
  16017. var engine = this.getEngine();
  16018. var scene = this.getScene();
  16019. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16020. if (this.minZ <= 0) {
  16021. this.minZ = 0.1;
  16022. }
  16023. if (scene.useRightHandedSystem) {
  16024. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16025. }
  16026. else {
  16027. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16028. }
  16029. return this._projectionMatrix;
  16030. }
  16031. var halfWidth = engine.getRenderWidth() / 2.0;
  16032. var halfHeight = engine.getRenderHeight() / 2.0;
  16033. if (scene.useRightHandedSystem) {
  16034. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16035. }
  16036. else {
  16037. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16038. }
  16039. return this._projectionMatrix;
  16040. };
  16041. Camera.prototype.getTranformationMatrix = function () {
  16042. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16043. return this._transformMatrix;
  16044. };
  16045. Camera.prototype.updateFrustumPlanes = function () {
  16046. if (!this._refreshFrustumPlanes) {
  16047. return;
  16048. }
  16049. this.getTranformationMatrix();
  16050. if (!this._frustumPlanes) {
  16051. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16052. }
  16053. else {
  16054. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16055. }
  16056. this._refreshFrustumPlanes = false;
  16057. };
  16058. Camera.prototype.isInFrustum = function (target) {
  16059. this.updateFrustumPlanes();
  16060. return target.isInFrustum(this._frustumPlanes);
  16061. };
  16062. Camera.prototype.isCompletelyInFrustum = function (target) {
  16063. this.updateFrustumPlanes();
  16064. return target.isCompletelyInFrustum(this._frustumPlanes);
  16065. };
  16066. Camera.prototype.dispose = function () {
  16067. // Animations
  16068. this.getScene().stopAnimation(this);
  16069. // Remove from scene
  16070. this.getScene().removeCamera(this);
  16071. while (this._rigCameras.length > 0) {
  16072. this._rigCameras.pop().dispose();
  16073. }
  16074. // Postprocesses
  16075. var i = this._postProcesses.length;
  16076. while (--i >= 0) {
  16077. this._postProcesses[i].dispose(this);
  16078. }
  16079. _super.prototype.dispose.call(this);
  16080. };
  16081. // ---- Camera rigs section ----
  16082. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16083. while (this._rigCameras.length > 0) {
  16084. this._rigCameras.pop().dispose();
  16085. }
  16086. this.cameraRigMode = mode;
  16087. this._cameraRigParams = {};
  16088. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16089. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16090. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16091. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16092. // create the rig cameras, unless none
  16093. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16094. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  16095. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  16096. }
  16097. switch (this.cameraRigMode) {
  16098. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16099. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16100. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16101. break;
  16102. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16103. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16104. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16105. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16106. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16107. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16108. break;
  16109. case Camera.RIG_MODE_VR:
  16110. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16111. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16112. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16113. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16114. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16115. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16116. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16117. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16118. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16119. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16120. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16121. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16122. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16123. if (metrics.compensateDistortion) {
  16124. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16125. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16126. }
  16127. break;
  16128. case Camera.RIG_MODE_WEBVR:
  16129. if (rigParams.vrDisplay) {
  16130. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16131. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16132. //Left eye
  16133. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16134. this._rigCameras[0].setCameraRigParameter("left", true);
  16135. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16136. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16137. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16138. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16139. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16140. this._rigCameras[0].parent = this;
  16141. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16142. //Right eye
  16143. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16144. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16145. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16146. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16147. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16148. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16149. this._rigCameras[1].parent = this;
  16150. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16151. }
  16152. break;
  16153. }
  16154. this._cascadePostProcessesToRigCams();
  16155. this.
  16156. update();
  16157. };
  16158. Camera.prototype._getVRProjectionMatrix = function () {
  16159. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16160. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16161. return this._projectionMatrix;
  16162. };
  16163. Camera.prototype._updateCameraRotationMatrix = function () {
  16164. //Here for WebVR
  16165. };
  16166. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16167. //Here for WebVR
  16168. };
  16169. /**
  16170. * This function MUST be overwritten by the different WebVR cameras available.
  16171. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16172. */
  16173. Camera.prototype._getWebVRProjectionMatrix = function () {
  16174. return BABYLON.Matrix.Identity();
  16175. };
  16176. /**
  16177. * This function MUST be overwritten by the different WebVR cameras available.
  16178. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16179. */
  16180. Camera.prototype._getWebVRViewMatrix = function () {
  16181. return BABYLON.Matrix.Identity();
  16182. };
  16183. Camera.prototype.setCameraRigParameter = function (name, value) {
  16184. if (!this._cameraRigParams) {
  16185. this._cameraRigParams = {};
  16186. }
  16187. this._cameraRigParams[name] = value;
  16188. //provisionnally:
  16189. if (name === "interaxialDistance") {
  16190. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16191. }
  16192. };
  16193. /**
  16194. * needs to be overridden by children so sub has required properties to be copied
  16195. */
  16196. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16197. return null;
  16198. };
  16199. /**
  16200. * May need to be overridden by children
  16201. */
  16202. Camera.prototype._updateRigCameras = function () {
  16203. for (var i = 0; i < this._rigCameras.length; i++) {
  16204. this._rigCameras[i].minZ = this.minZ;
  16205. this._rigCameras[i].maxZ = this.maxZ;
  16206. this._rigCameras[i].fov = this.fov;
  16207. }
  16208. // only update viewport when ANAGLYPH
  16209. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16210. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16211. }
  16212. };
  16213. Camera.prototype._setupInputs = function () {
  16214. };
  16215. Camera.prototype.serialize = function () {
  16216. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16217. // Type
  16218. serializationObject.type = this.getClassName();
  16219. // Parent
  16220. if (this.parent) {
  16221. serializationObject.parentId = this.parent.id;
  16222. }
  16223. if (this.inputs) {
  16224. this.inputs.serialize(serializationObject);
  16225. }
  16226. // Animations
  16227. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16228. serializationObject.ranges = this.serializeAnimationRanges();
  16229. return serializationObject;
  16230. };
  16231. Camera.prototype.clone = function (name) {
  16232. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16233. };
  16234. Camera.prototype.getDirection = function (localAxis) {
  16235. var result = BABYLON.Vector3.Zero();
  16236. this.getDirectionToRef(localAxis, result);
  16237. return result;
  16238. };
  16239. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16240. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16241. };
  16242. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16243. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16244. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16245. switch (type) {
  16246. case "ArcRotateCamera":
  16247. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16248. case "DeviceOrientationCamera":
  16249. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16250. case "FollowCamera":
  16251. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16252. case "ArcFollowCamera":
  16253. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16254. case "GamepadCamera":
  16255. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16256. case "TouchCamera":
  16257. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16258. case "VirtualJoysticksCamera":
  16259. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16260. case "WebVRFreeCamera":
  16261. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16262. case "WebVRGamepadCamera":
  16263. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16264. case "VRDeviceOrientationFreeCamera":
  16265. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16266. case "VRDeviceOrientationGamepadCamera":
  16267. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16268. case "AnaglyphArcRotateCamera":
  16269. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16270. case "AnaglyphFreeCamera":
  16271. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16272. case "AnaglyphGamepadCamera":
  16273. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16274. case "AnaglyphUniversalCamera":
  16275. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16276. case "StereoscopicArcRotateCamera":
  16277. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16278. case "StereoscopicFreeCamera":
  16279. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16280. case "StereoscopicGamepadCamera":
  16281. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16282. case "StereoscopicUniversalCamera":
  16283. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16284. case "FreeCamera":
  16285. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16286. default:
  16287. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16288. }
  16289. };
  16290. Camera.Parse = function (parsedCamera, scene) {
  16291. var type = parsedCamera.type;
  16292. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16293. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16294. // Parent
  16295. if (parsedCamera.parentId) {
  16296. camera._waitingParentId = parsedCamera.parentId;
  16297. }
  16298. //If camera has an input manager, let it parse inputs settings
  16299. if (camera.inputs) {
  16300. camera.inputs.parse(parsedCamera);
  16301. camera._setupInputs();
  16302. }
  16303. // Target
  16304. if (parsedCamera.target) {
  16305. if (camera.setTarget) {
  16306. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16307. }
  16308. }
  16309. // Apply 3d rig, when found
  16310. if (parsedCamera.cameraRigMode) {
  16311. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16312. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16313. }
  16314. // Animations
  16315. if (parsedCamera.animations) {
  16316. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16317. var parsedAnimation = parsedCamera.animations[animationIndex];
  16318. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16319. }
  16320. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16321. }
  16322. if (parsedCamera.autoAnimate) {
  16323. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16324. }
  16325. return camera;
  16326. };
  16327. return Camera;
  16328. }(BABYLON.Node));
  16329. // Statics
  16330. Camera._PERSPECTIVE_CAMERA = 0;
  16331. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16332. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16333. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16334. Camera._RIG_MODE_NONE = 0;
  16335. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16336. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16337. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16338. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16339. Camera._RIG_MODE_VR = 20;
  16340. Camera._RIG_MODE_WEBVR = 21;
  16341. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16342. __decorate([
  16343. BABYLON.serializeAsVector3()
  16344. ], Camera.prototype, "position", void 0);
  16345. __decorate([
  16346. BABYLON.serializeAsVector3()
  16347. ], Camera.prototype, "upVector", void 0);
  16348. __decorate([
  16349. BABYLON.serialize()
  16350. ], Camera.prototype, "orthoLeft", void 0);
  16351. __decorate([
  16352. BABYLON.serialize()
  16353. ], Camera.prototype, "orthoRight", void 0);
  16354. __decorate([
  16355. BABYLON.serialize()
  16356. ], Camera.prototype, "orthoBottom", void 0);
  16357. __decorate([
  16358. BABYLON.serialize()
  16359. ], Camera.prototype, "orthoTop", void 0);
  16360. __decorate([
  16361. BABYLON.serialize()
  16362. ], Camera.prototype, "fov", void 0);
  16363. __decorate([
  16364. BABYLON.serialize()
  16365. ], Camera.prototype, "minZ", void 0);
  16366. __decorate([
  16367. BABYLON.serialize()
  16368. ], Camera.prototype, "maxZ", void 0);
  16369. __decorate([
  16370. BABYLON.serialize()
  16371. ], Camera.prototype, "inertia", void 0);
  16372. __decorate([
  16373. BABYLON.serialize()
  16374. ], Camera.prototype, "mode", void 0);
  16375. __decorate([
  16376. BABYLON.serialize()
  16377. ], Camera.prototype, "layerMask", void 0);
  16378. __decorate([
  16379. BABYLON.serialize()
  16380. ], Camera.prototype, "fovMode", void 0);
  16381. __decorate([
  16382. BABYLON.serialize()
  16383. ], Camera.prototype, "cameraRigMode", void 0);
  16384. __decorate([
  16385. BABYLON.serialize()
  16386. ], Camera.prototype, "interaxialDistance", void 0);
  16387. __decorate([
  16388. BABYLON.serialize()
  16389. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16390. BABYLON.Camera = Camera;
  16391. })(BABYLON || (BABYLON = {}));
  16392. //# sourceMappingURL=babylon.camera.js.map
  16393. var BABYLON;
  16394. (function (BABYLON) {
  16395. BABYLON.CameraInputTypes = {};
  16396. var CameraInputsManager = (function () {
  16397. function CameraInputsManager(camera) {
  16398. this.attached = {};
  16399. this.camera = camera;
  16400. this.checkInputs = function () { };
  16401. }
  16402. CameraInputsManager.prototype.add = function (input) {
  16403. var type = input.getSimpleName();
  16404. if (this.attached[type]) {
  16405. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  16406. return;
  16407. }
  16408. this.attached[type] = input;
  16409. input.camera = this.camera;
  16410. //for checkInputs, we are dynamically creating a function
  16411. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  16412. if (input.checkInputs) {
  16413. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16414. }
  16415. if (this.attachedElement) {
  16416. input.attachControl(this.attachedElement);
  16417. }
  16418. };
  16419. CameraInputsManager.prototype.remove = function (inputToRemove) {
  16420. for (var cam in this.attached) {
  16421. var input = this.attached[cam];
  16422. if (input === inputToRemove) {
  16423. input.detachControl(this.attachedElement);
  16424. delete this.attached[cam];
  16425. this.rebuildInputCheck();
  16426. }
  16427. }
  16428. };
  16429. CameraInputsManager.prototype.removeByType = function (inputType) {
  16430. for (var cam in this.attached) {
  16431. var input = this.attached[cam];
  16432. if (input.getTypeName() === inputType) {
  16433. input.detachControl(this.attachedElement);
  16434. delete this.attached[cam];
  16435. this.rebuildInputCheck();
  16436. }
  16437. }
  16438. };
  16439. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  16440. var current = this.checkInputs;
  16441. return function () {
  16442. current();
  16443. fn();
  16444. };
  16445. };
  16446. CameraInputsManager.prototype.attachInput = function (input) {
  16447. input.attachControl(this.attachedElement, this.noPreventDefault);
  16448. };
  16449. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  16450. if (this.attachedElement) {
  16451. return;
  16452. }
  16453. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  16454. this.attachedElement = element;
  16455. this.noPreventDefault = noPreventDefault;
  16456. for (var cam in this.attached) {
  16457. var input = this.attached[cam];
  16458. this.attached[cam].attachControl(element, noPreventDefault);
  16459. }
  16460. };
  16461. CameraInputsManager.prototype.detachElement = function (element) {
  16462. if (this.attachedElement !== element) {
  16463. return;
  16464. }
  16465. for (var cam in this.attached) {
  16466. var input = this.attached[cam];
  16467. this.attached[cam].detachControl(element);
  16468. }
  16469. this.attachedElement = null;
  16470. };
  16471. CameraInputsManager.prototype.rebuildInputCheck = function () {
  16472. this.checkInputs = function () { };
  16473. for (var cam in this.attached) {
  16474. var input = this.attached[cam];
  16475. if (input.checkInputs) {
  16476. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16477. }
  16478. }
  16479. };
  16480. CameraInputsManager.prototype.clear = function () {
  16481. if (this.attachedElement) {
  16482. this.detachElement(this.attachedElement);
  16483. }
  16484. this.attached = {};
  16485. this.attachedElement = null;
  16486. this.checkInputs = function () { };
  16487. };
  16488. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  16489. var inputs = {};
  16490. for (var cam in this.attached) {
  16491. var input = this.attached[cam];
  16492. var res = BABYLON.SerializationHelper.Serialize(input);
  16493. inputs[input.getTypeName()] = res;
  16494. }
  16495. serializedCamera.inputsmgr = inputs;
  16496. };
  16497. CameraInputsManager.prototype.parse = function (parsedCamera) {
  16498. var parsedInputs = parsedCamera.inputsmgr;
  16499. if (parsedInputs) {
  16500. this.clear();
  16501. for (var n in parsedInputs) {
  16502. var construct = BABYLON.CameraInputTypes[n];
  16503. if (construct) {
  16504. var parsedinput = parsedInputs[n];
  16505. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  16506. this.add(input);
  16507. }
  16508. }
  16509. }
  16510. else {
  16511. //2016-03-08 this part is for managing backward compatibility
  16512. for (var n in this.attached) {
  16513. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  16514. if (construct) {
  16515. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  16516. this.remove(this.attached[n]);
  16517. this.add(input);
  16518. }
  16519. }
  16520. }
  16521. };
  16522. return CameraInputsManager;
  16523. }());
  16524. BABYLON.CameraInputsManager = CameraInputsManager;
  16525. })(BABYLON || (BABYLON = {}));
  16526. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  16527. var BABYLON;
  16528. (function (BABYLON) {
  16529. var FreeCameraMouseInput = (function () {
  16530. function FreeCameraMouseInput(touchEnabled) {
  16531. if (touchEnabled === void 0) { touchEnabled = true; }
  16532. this.touchEnabled = touchEnabled;
  16533. this.buttons = [0, 1, 2];
  16534. this.angularSensibility = 2000.0;
  16535. }
  16536. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  16537. var _this = this;
  16538. var engine = this.camera.getEngine();
  16539. if (!this._pointerInput) {
  16540. this._pointerInput = function (p, s) {
  16541. var evt = p.event;
  16542. if (!_this.touchEnabled && evt.pointerType === "touch") {
  16543. return;
  16544. }
  16545. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16546. return;
  16547. }
  16548. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16549. try {
  16550. evt.srcElement.setPointerCapture(evt.pointerId);
  16551. }
  16552. catch (e) {
  16553. }
  16554. _this.previousPosition = {
  16555. x: evt.clientX,
  16556. y: evt.clientY
  16557. };
  16558. if (!noPreventDefault) {
  16559. evt.preventDefault();
  16560. element.focus();
  16561. }
  16562. }
  16563. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16564. try {
  16565. evt.srcElement.releasePointerCapture(evt.pointerId);
  16566. }
  16567. catch (e) {
  16568. }
  16569. _this.previousPosition = null;
  16570. if (!noPreventDefault) {
  16571. evt.preventDefault();
  16572. }
  16573. }
  16574. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16575. if (!_this.previousPosition || engine.isPointerLock) {
  16576. return;
  16577. }
  16578. var offsetX = evt.clientX - _this.previousPosition.x;
  16579. var offsetY = evt.clientY - _this.previousPosition.y;
  16580. if (_this.camera.getScene().useRightHandedSystem) {
  16581. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16582. }
  16583. else {
  16584. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16585. }
  16586. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16587. _this.previousPosition = {
  16588. x: evt.clientX,
  16589. y: evt.clientY
  16590. };
  16591. if (!noPreventDefault) {
  16592. evt.preventDefault();
  16593. }
  16594. }
  16595. };
  16596. }
  16597. this._onMouseMove = function (evt) {
  16598. if (!engine.isPointerLock) {
  16599. return;
  16600. }
  16601. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  16602. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  16603. if (_this.camera.getScene().useRightHandedSystem) {
  16604. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16605. }
  16606. else {
  16607. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16608. }
  16609. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16610. _this.previousPosition = null;
  16611. if (!noPreventDefault) {
  16612. evt.preventDefault();
  16613. }
  16614. };
  16615. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16616. element.addEventListener("mousemove", this._onMouseMove, false);
  16617. };
  16618. FreeCameraMouseInput.prototype.detachControl = function (element) {
  16619. if (this._observer && element) {
  16620. this.camera.getScene().onPointerObservable.remove(this._observer);
  16621. element.removeEventListener("mousemove", this._onMouseMove);
  16622. this._observer = null;
  16623. this._onMouseMove = null;
  16624. this.previousPosition = null;
  16625. }
  16626. };
  16627. FreeCameraMouseInput.prototype.getTypeName = function () {
  16628. return "FreeCameraMouseInput";
  16629. };
  16630. FreeCameraMouseInput.prototype.getSimpleName = function () {
  16631. return "mouse";
  16632. };
  16633. return FreeCameraMouseInput;
  16634. }());
  16635. __decorate([
  16636. BABYLON.serialize()
  16637. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  16638. __decorate([
  16639. BABYLON.serialize()
  16640. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  16641. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  16642. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  16643. })(BABYLON || (BABYLON = {}));
  16644. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  16645. var BABYLON;
  16646. (function (BABYLON) {
  16647. var FreeCameraKeyboardMoveInput = (function () {
  16648. function FreeCameraKeyboardMoveInput() {
  16649. this._keys = [];
  16650. this.keysUp = [38];
  16651. this.keysDown = [40];
  16652. this.keysLeft = [37];
  16653. this.keysRight = [39];
  16654. }
  16655. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16656. var _this = this;
  16657. if (!this._onKeyDown) {
  16658. element.tabIndex = 1;
  16659. this._onKeyDown = function (evt) {
  16660. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16661. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16662. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16663. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16664. var index = _this._keys.indexOf(evt.keyCode);
  16665. if (index === -1) {
  16666. _this._keys.push(evt.keyCode);
  16667. }
  16668. if (!noPreventDefault) {
  16669. evt.preventDefault();
  16670. }
  16671. }
  16672. };
  16673. this._onKeyUp = function (evt) {
  16674. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16675. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16676. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16677. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16678. var index = _this._keys.indexOf(evt.keyCode);
  16679. if (index >= 0) {
  16680. _this._keys.splice(index, 1);
  16681. }
  16682. if (!noPreventDefault) {
  16683. evt.preventDefault();
  16684. }
  16685. }
  16686. };
  16687. element.addEventListener("keydown", this._onKeyDown, false);
  16688. element.addEventListener("keyup", this._onKeyUp, false);
  16689. BABYLON.Tools.RegisterTopRootEvents([
  16690. { name: "blur", handler: this._onLostFocus }
  16691. ]);
  16692. }
  16693. };
  16694. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16695. if (this._onKeyDown) {
  16696. element.removeEventListener("keydown", this._onKeyDown);
  16697. element.removeEventListener("keyup", this._onKeyUp);
  16698. BABYLON.Tools.UnregisterTopRootEvents([
  16699. { name: "blur", handler: this._onLostFocus }
  16700. ]);
  16701. this._keys = [];
  16702. this._onKeyDown = null;
  16703. this._onKeyUp = null;
  16704. }
  16705. };
  16706. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16707. if (this._onKeyDown) {
  16708. var camera = this.camera;
  16709. // Keyboard
  16710. for (var index = 0; index < this._keys.length; index++) {
  16711. var keyCode = this._keys[index];
  16712. var speed = camera._computeLocalCameraSpeed();
  16713. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16714. camera._localDirection.copyFromFloats(-speed, 0, 0);
  16715. }
  16716. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16717. camera._localDirection.copyFromFloats(0, 0, speed);
  16718. }
  16719. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16720. camera._localDirection.copyFromFloats(speed, 0, 0);
  16721. }
  16722. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16723. camera._localDirection.copyFromFloats(0, 0, -speed);
  16724. }
  16725. if (camera.getScene().useRightHandedSystem) {
  16726. camera._localDirection.z *= -1;
  16727. }
  16728. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  16729. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  16730. camera.cameraDirection.addInPlace(camera._transformedDirection);
  16731. }
  16732. }
  16733. };
  16734. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16735. return "FreeCameraKeyboardMoveInput";
  16736. };
  16737. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  16738. this._keys = [];
  16739. };
  16740. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16741. return "keyboard";
  16742. };
  16743. return FreeCameraKeyboardMoveInput;
  16744. }());
  16745. __decorate([
  16746. BABYLON.serialize()
  16747. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16748. __decorate([
  16749. BABYLON.serialize()
  16750. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16751. __decorate([
  16752. BABYLON.serialize()
  16753. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  16754. __decorate([
  16755. BABYLON.serialize()
  16756. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  16757. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  16758. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  16759. })(BABYLON || (BABYLON = {}));
  16760. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  16761. var BABYLON;
  16762. (function (BABYLON) {
  16763. var FreeCameraTouchInput = (function () {
  16764. function FreeCameraTouchInput() {
  16765. this._offsetX = null;
  16766. this._offsetY = null;
  16767. this._pointerCount = 0;
  16768. this._pointerPressed = [];
  16769. this.touchAngularSensibility = 200000.0;
  16770. this.touchMoveSensibility = 250.0;
  16771. }
  16772. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  16773. var _this = this;
  16774. var previousPosition;
  16775. if (this._pointerInput === undefined) {
  16776. this._onLostFocus = function (evt) {
  16777. _this._offsetX = null;
  16778. _this._offsetY = null;
  16779. };
  16780. this._pointerInput = function (p, s) {
  16781. var evt = p.event;
  16782. if (evt.pointerType === "mouse") {
  16783. return;
  16784. }
  16785. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16786. if (!noPreventDefault) {
  16787. evt.preventDefault();
  16788. }
  16789. _this._pointerPressed.push(evt.pointerId);
  16790. if (_this._pointerPressed.length !== 1) {
  16791. return;
  16792. }
  16793. previousPosition = {
  16794. x: evt.clientX,
  16795. y: evt.clientY
  16796. };
  16797. }
  16798. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16799. if (!noPreventDefault) {
  16800. evt.preventDefault();
  16801. }
  16802. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16803. if (index === -1) {
  16804. return;
  16805. }
  16806. _this._pointerPressed.splice(index, 1);
  16807. if (index != 0) {
  16808. return;
  16809. }
  16810. previousPosition = null;
  16811. _this._offsetX = null;
  16812. _this._offsetY = null;
  16813. }
  16814. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16815. if (!noPreventDefault) {
  16816. evt.preventDefault();
  16817. }
  16818. if (!previousPosition) {
  16819. return;
  16820. }
  16821. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16822. if (index != 0) {
  16823. return;
  16824. }
  16825. _this._offsetX = evt.clientX - previousPosition.x;
  16826. _this._offsetY = -(evt.clientY - previousPosition.y);
  16827. }
  16828. };
  16829. }
  16830. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16831. element.addEventListener("blur", this._onLostFocus);
  16832. };
  16833. FreeCameraTouchInput.prototype.detachControl = function (element) {
  16834. if (this._pointerInput && element) {
  16835. this.camera.getScene().onPointerObservable.remove(this._observer);
  16836. this._observer = null;
  16837. element.removeEventListener("blur", this._onLostFocus);
  16838. this._onLostFocus = null;
  16839. this._pointerPressed = [];
  16840. this._offsetX = null;
  16841. this._offsetY = null;
  16842. this._pointerCount = 0;
  16843. }
  16844. };
  16845. FreeCameraTouchInput.prototype.checkInputs = function () {
  16846. if (this._offsetX) {
  16847. var camera = this.camera;
  16848. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  16849. if (this._pointerPressed.length > 1) {
  16850. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  16851. }
  16852. else {
  16853. var speed = camera._computeLocalCameraSpeed();
  16854. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  16855. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  16856. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  16857. }
  16858. }
  16859. };
  16860. FreeCameraTouchInput.prototype.getTypeName = function () {
  16861. return "FreeCameraTouchInput";
  16862. };
  16863. FreeCameraTouchInput.prototype.getSimpleName = function () {
  16864. return "touch";
  16865. };
  16866. return FreeCameraTouchInput;
  16867. }());
  16868. __decorate([
  16869. BABYLON.serialize()
  16870. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  16871. __decorate([
  16872. BABYLON.serialize()
  16873. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  16874. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  16875. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  16876. })(BABYLON || (BABYLON = {}));
  16877. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  16878. var BABYLON;
  16879. (function (BABYLON) {
  16880. var FreeCameraDeviceOrientationInput = (function () {
  16881. function FreeCameraDeviceOrientationInput() {
  16882. var _this = this;
  16883. this._screenOrientationAngle = 0;
  16884. this._screenQuaternion = new BABYLON.Quaternion();
  16885. this._alpha = 0;
  16886. this._beta = 0;
  16887. this._gamma = 0;
  16888. this._orientationChanged = function () {
  16889. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  16890. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  16891. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  16892. };
  16893. this._deviceOrientation = function (evt) {
  16894. _this._alpha = evt.alpha;
  16895. _this._beta = evt.beta;
  16896. _this._gamma = evt.gamma;
  16897. };
  16898. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  16899. this._orientationChanged();
  16900. }
  16901. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  16902. get: function () {
  16903. return this._camera;
  16904. },
  16905. set: function (camera) {
  16906. this._camera = camera;
  16907. if (!this._camera.rotationQuaternion)
  16908. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  16909. },
  16910. enumerable: true,
  16911. configurable: true
  16912. });
  16913. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  16914. window.addEventListener("orientationchange", this._orientationChanged);
  16915. window.addEventListener("deviceorientation", this._deviceOrientation);
  16916. //In certain cases, the attach control is called AFTER orientation was changed,
  16917. //So this is needed.
  16918. this._orientationChanged();
  16919. };
  16920. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  16921. window.removeEventListener("orientationchange", this._orientationChanged);
  16922. window.removeEventListener("deviceorientation", this._deviceOrientation);
  16923. };
  16924. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  16925. //if no device orientation provided, don't update the rotation.
  16926. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  16927. if (!this._alpha)
  16928. return;
  16929. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  16930. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  16931. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  16932. //Mirror on XY Plane
  16933. this._camera.rotationQuaternion.z *= -1;
  16934. this._camera.rotationQuaternion.w *= -1;
  16935. };
  16936. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  16937. return "FreeCameraDeviceOrientationInput";
  16938. };
  16939. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  16940. return "deviceOrientation";
  16941. };
  16942. return FreeCameraDeviceOrientationInput;
  16943. }());
  16944. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  16945. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  16946. })(BABYLON || (BABYLON = {}));
  16947. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  16948. var BABYLON;
  16949. (function (BABYLON) {
  16950. var FreeCameraGamepadInput = (function () {
  16951. function FreeCameraGamepadInput() {
  16952. this.gamepadAngularSensibility = 200;
  16953. this.gamepadMoveSensibility = 40;
  16954. // private members
  16955. this._cameraTransform = BABYLON.Matrix.Identity();
  16956. this._deltaTransform = BABYLON.Vector3.Zero();
  16957. this._vector3 = BABYLON.Vector3.Zero();
  16958. this._vector2 = BABYLON.Vector2.Zero();
  16959. }
  16960. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  16961. var _this = this;
  16962. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  16963. };
  16964. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  16965. if (this._gamepads) {
  16966. this._gamepads.dispose();
  16967. }
  16968. this.gamepad = null;
  16969. };
  16970. FreeCameraGamepadInput.prototype.checkInputs = function () {
  16971. if (this.gamepad && this.gamepad.leftStick) {
  16972. var camera = this.camera;
  16973. var LSValues = this.gamepad.leftStick;
  16974. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  16975. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  16976. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  16977. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  16978. var RSValues = this.gamepad.rightStick;
  16979. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  16980. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  16981. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  16982. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  16983. if (!camera.rotationQuaternion) {
  16984. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  16985. }
  16986. else {
  16987. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  16988. }
  16989. var speed = camera._computeLocalCameraSpeed() * 50.0;
  16990. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  16991. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  16992. camera.cameraDirection.addInPlace(this._deltaTransform);
  16993. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  16994. camera.cameraRotation.addInPlace(this._vector2);
  16995. }
  16996. };
  16997. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  16998. // Only the first gamepad found can control the camera
  16999. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17000. // prioritize XBOX gamepads.
  17001. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17002. this.gamepad = gamepad;
  17003. }
  17004. }
  17005. };
  17006. FreeCameraGamepadInput.prototype.getTypeName = function () {
  17007. return "FreeCameraGamepadInput";
  17008. };
  17009. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  17010. return "gamepad";
  17011. };
  17012. return FreeCameraGamepadInput;
  17013. }());
  17014. __decorate([
  17015. BABYLON.serialize()
  17016. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  17017. __decorate([
  17018. BABYLON.serialize()
  17019. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17020. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  17021. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  17022. })(BABYLON || (BABYLON = {}));
  17023. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  17024. var BABYLON;
  17025. (function (BABYLON) {
  17026. var ArcRotateCameraKeyboardMoveInput = (function () {
  17027. function ArcRotateCameraKeyboardMoveInput() {
  17028. this._keys = [];
  17029. this.keysUp = [38];
  17030. this.keysDown = [40];
  17031. this.keysLeft = [37];
  17032. this.keysRight = [39];
  17033. }
  17034. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  17035. var _this = this;
  17036. element.tabIndex = 1;
  17037. this._onKeyDown = function (evt) {
  17038. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17039. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17040. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17041. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17042. var index = _this._keys.indexOf(evt.keyCode);
  17043. if (index === -1) {
  17044. _this._keys.push(evt.keyCode);
  17045. }
  17046. if (evt.preventDefault) {
  17047. if (!noPreventDefault) {
  17048. evt.preventDefault();
  17049. }
  17050. }
  17051. }
  17052. };
  17053. this._onKeyUp = function (evt) {
  17054. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17055. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17056. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17057. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17058. var index = _this._keys.indexOf(evt.keyCode);
  17059. if (index >= 0) {
  17060. _this._keys.splice(index, 1);
  17061. }
  17062. if (evt.preventDefault) {
  17063. if (!noPreventDefault) {
  17064. evt.preventDefault();
  17065. }
  17066. }
  17067. }
  17068. };
  17069. this._onLostFocus = function () {
  17070. _this._keys = [];
  17071. };
  17072. element.addEventListener("keydown", this._onKeyDown, false);
  17073. element.addEventListener("keyup", this._onKeyUp, false);
  17074. BABYLON.Tools.RegisterTopRootEvents([
  17075. { name: "blur", handler: this._onLostFocus }
  17076. ]);
  17077. };
  17078. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  17079. if (element) {
  17080. element.removeEventListener("keydown", this._onKeyDown);
  17081. element.removeEventListener("keyup", this._onKeyUp);
  17082. }
  17083. BABYLON.Tools.UnregisterTopRootEvents([
  17084. { name: "blur", handler: this._onLostFocus }
  17085. ]);
  17086. this._keys = [];
  17087. this._onKeyDown = null;
  17088. this._onKeyUp = null;
  17089. this._onLostFocus = null;
  17090. };
  17091. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  17092. if (this._onKeyDown) {
  17093. var camera = this.camera;
  17094. for (var index = 0; index < this._keys.length; index++) {
  17095. var keyCode = this._keys[index];
  17096. if (this.keysLeft.indexOf(keyCode) !== -1) {
  17097. camera.inertialAlphaOffset -= 0.01;
  17098. }
  17099. else if (this.keysUp.indexOf(keyCode) !== -1) {
  17100. camera.inertialBetaOffset -= 0.01;
  17101. }
  17102. else if (this.keysRight.indexOf(keyCode) !== -1) {
  17103. camera.inertialAlphaOffset += 0.01;
  17104. }
  17105. else if (this.keysDown.indexOf(keyCode) !== -1) {
  17106. camera.inertialBetaOffset += 0.01;
  17107. }
  17108. }
  17109. }
  17110. };
  17111. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  17112. return "ArcRotateCameraKeyboardMoveInput";
  17113. };
  17114. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  17115. return "keyboard";
  17116. };
  17117. return ArcRotateCameraKeyboardMoveInput;
  17118. }());
  17119. __decorate([
  17120. BABYLON.serialize()
  17121. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  17122. __decorate([
  17123. BABYLON.serialize()
  17124. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  17125. __decorate([
  17126. BABYLON.serialize()
  17127. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  17128. __decorate([
  17129. BABYLON.serialize()
  17130. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  17131. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  17132. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  17133. })(BABYLON || (BABYLON = {}));
  17134. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  17135. var BABYLON;
  17136. (function (BABYLON) {
  17137. var ArcRotateCameraMouseWheelInput = (function () {
  17138. function ArcRotateCameraMouseWheelInput() {
  17139. this.wheelPrecision = 3.0;
  17140. }
  17141. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  17142. var _this = this;
  17143. this._wheel = function (p, s) {
  17144. //sanity check - this should be a PointerWheel event.
  17145. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  17146. return;
  17147. var event = p.event;
  17148. var delta = 0;
  17149. if (event.wheelDelta) {
  17150. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  17151. }
  17152. else if (event.detail) {
  17153. delta = -event.detail / _this.wheelPrecision;
  17154. }
  17155. if (delta)
  17156. _this.camera.inertialRadiusOffset += delta;
  17157. if (event.preventDefault) {
  17158. if (!noPreventDefault) {
  17159. event.preventDefault();
  17160. }
  17161. }
  17162. };
  17163. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  17164. };
  17165. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  17166. if (this._observer && element) {
  17167. this.camera.getScene().onPointerObservable.remove(this._observer);
  17168. this._observer = null;
  17169. this._wheel = null;
  17170. }
  17171. };
  17172. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  17173. return "ArcRotateCameraMouseWheelInput";
  17174. };
  17175. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  17176. return "mousewheel";
  17177. };
  17178. return ArcRotateCameraMouseWheelInput;
  17179. }());
  17180. __decorate([
  17181. BABYLON.serialize()
  17182. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  17183. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  17184. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  17185. })(BABYLON || (BABYLON = {}));
  17186. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  17187. var BABYLON;
  17188. (function (BABYLON) {
  17189. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17190. var ArcRotateCameraPointersInput = (function () {
  17191. function ArcRotateCameraPointersInput() {
  17192. this.buttons = [0, 1, 2];
  17193. this.angularSensibilityX = 1000.0;
  17194. this.angularSensibilityY = 1000.0;
  17195. this.pinchPrecision = 6.0;
  17196. this.panningSensibility = 50.0;
  17197. this._isPanClick = false;
  17198. this.pinchInwards = true;
  17199. }
  17200. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  17201. var _this = this;
  17202. var engine = this.camera.getEngine();
  17203. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  17204. var pointA, pointB;
  17205. var previousPinchDistance = 0;
  17206. this._pointerInput = function (p, s) {
  17207. var evt = p.event;
  17208. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  17209. return;
  17210. }
  17211. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17212. try {
  17213. evt.srcElement.setPointerCapture(evt.pointerId);
  17214. }
  17215. catch (e) {
  17216. }
  17217. // Manage panning with pan button click
  17218. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  17219. // manage pointers
  17220. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  17221. if (pointA === undefined) {
  17222. pointA = cacheSoloPointer;
  17223. }
  17224. else if (pointB === undefined) {
  17225. pointB = cacheSoloPointer;
  17226. }
  17227. if (!noPreventDefault) {
  17228. evt.preventDefault();
  17229. element.focus();
  17230. }
  17231. }
  17232. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17233. try {
  17234. evt.srcElement.releasePointerCapture(evt.pointerId);
  17235. }
  17236. catch (e) {
  17237. }
  17238. cacheSoloPointer = null;
  17239. previousPinchDistance = 0;
  17240. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  17241. //but emptying completly pointers collection is required to fix a bug on iPhone :
  17242. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  17243. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  17244. pointA = pointB = undefined;
  17245. if (!noPreventDefault) {
  17246. evt.preventDefault();
  17247. }
  17248. }
  17249. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17250. if (!noPreventDefault) {
  17251. evt.preventDefault();
  17252. }
  17253. // One button down
  17254. if (pointA && pointB === undefined) {
  17255. if (_this.panningSensibility !== 0 &&
  17256. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  17257. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  17258. _this.camera
  17259. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  17260. _this.camera
  17261. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  17262. }
  17263. else {
  17264. var offsetX = evt.clientX - cacheSoloPointer.x;
  17265. var offsetY = evt.clientY - cacheSoloPointer.y;
  17266. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17267. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17268. }
  17269. cacheSoloPointer.x = evt.clientX;
  17270. cacheSoloPointer.y = evt.clientY;
  17271. }
  17272. else if (pointA && pointB) {
  17273. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  17274. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  17275. ed.x = evt.clientX;
  17276. ed.y = evt.clientY;
  17277. var direction = _this.pinchInwards ? 1 : -1;
  17278. var distX = pointA.x - pointB.x;
  17279. var distY = pointA.y - pointB.y;
  17280. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  17281. if (previousPinchDistance === 0) {
  17282. previousPinchDistance = pinchSquaredDistance;
  17283. return;
  17284. }
  17285. if (pinchSquaredDistance !== previousPinchDistance) {
  17286. _this.camera
  17287. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  17288. (_this.pinchPrecision *
  17289. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  17290. direction);
  17291. previousPinchDistance = pinchSquaredDistance;
  17292. }
  17293. }
  17294. }
  17295. };
  17296. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17297. this._onContextMenu = function (evt) {
  17298. evt.preventDefault();
  17299. };
  17300. if (!this.camera._useCtrlForPanning) {
  17301. element.addEventListener("contextmenu", this._onContextMenu, false);
  17302. }
  17303. this._onLostFocus = function () {
  17304. //this._keys = [];
  17305. pointA = pointB = undefined;
  17306. previousPinchDistance = 0;
  17307. cacheSoloPointer = null;
  17308. };
  17309. this._onMouseMove = function (evt) {
  17310. if (!engine.isPointerLock) {
  17311. return;
  17312. }
  17313. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17314. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17315. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17316. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17317. if (!noPreventDefault) {
  17318. evt.preventDefault();
  17319. }
  17320. };
  17321. this._onGestureStart = function (e) {
  17322. if (window.MSGesture === undefined) {
  17323. return;
  17324. }
  17325. if (!_this._MSGestureHandler) {
  17326. _this._MSGestureHandler = new MSGesture();
  17327. _this._MSGestureHandler.target = element;
  17328. }
  17329. _this._MSGestureHandler.addPointer(e.pointerId);
  17330. };
  17331. this._onGesture = function (e) {
  17332. _this.camera.radius *= e.scale;
  17333. if (e.preventDefault) {
  17334. if (!noPreventDefault) {
  17335. e.stopPropagation();
  17336. e.preventDefault();
  17337. }
  17338. }
  17339. };
  17340. element.addEventListener("mousemove", this._onMouseMove, false);
  17341. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  17342. element.addEventListener("MSGestureChange", this._onGesture, false);
  17343. element.addEventListener("keydown", this._onKeyDown, false);
  17344. element.addEventListener("keyup", this._onKeyUp, false);
  17345. BABYLON.Tools.RegisterTopRootEvents([
  17346. { name: "blur", handler: this._onLostFocus }
  17347. ]);
  17348. };
  17349. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  17350. if (element && this._observer) {
  17351. this.camera.getScene().onPointerObservable.remove(this._observer);
  17352. this._observer = null;
  17353. element.removeEventListener("contextmenu", this._onContextMenu);
  17354. element.removeEventListener("mousemove", this._onMouseMove);
  17355. element.removeEventListener("MSPointerDown", this._onGestureStart);
  17356. element.removeEventListener("MSGestureChange", this._onGesture);
  17357. element.removeEventListener("keydown", this._onKeyDown);
  17358. element.removeEventListener("keyup", this._onKeyUp);
  17359. this._isPanClick = false;
  17360. this.pinchInwards = true;
  17361. this._onKeyDown = null;
  17362. this._onKeyUp = null;
  17363. this._onMouseMove = null;
  17364. this._onGestureStart = null;
  17365. this._onGesture = null;
  17366. this._MSGestureHandler = null;
  17367. this._onLostFocus = null;
  17368. this._onContextMenu = null;
  17369. }
  17370. BABYLON.Tools.UnregisterTopRootEvents([
  17371. { name: "blur", handler: this._onLostFocus }
  17372. ]);
  17373. };
  17374. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  17375. return "ArcRotateCameraPointersInput";
  17376. };
  17377. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  17378. return "pointers";
  17379. };
  17380. return ArcRotateCameraPointersInput;
  17381. }());
  17382. __decorate([
  17383. BABYLON.serialize()
  17384. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  17385. __decorate([
  17386. BABYLON.serialize()
  17387. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  17388. __decorate([
  17389. BABYLON.serialize()
  17390. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  17391. __decorate([
  17392. BABYLON.serialize()
  17393. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  17394. __decorate([
  17395. BABYLON.serialize()
  17396. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  17397. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  17398. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  17399. })(BABYLON || (BABYLON = {}));
  17400. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  17401. var BABYLON;
  17402. (function (BABYLON) {
  17403. var ArcRotateCameraGamepadInput = (function () {
  17404. function ArcRotateCameraGamepadInput() {
  17405. this.gamepadRotationSensibility = 80;
  17406. this.gamepadMoveSensibility = 40;
  17407. }
  17408. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17409. var _this = this;
  17410. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17411. };
  17412. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  17413. if (this._gamepads) {
  17414. this._gamepads.dispose();
  17415. }
  17416. this.gamepad = null;
  17417. };
  17418. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  17419. if (this.gamepad) {
  17420. var camera = this.camera;
  17421. var RSValues = this.gamepad.rightStick;
  17422. if (RSValues.x != 0) {
  17423. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  17424. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  17425. camera.inertialAlphaOffset += normalizedRX;
  17426. }
  17427. }
  17428. if (RSValues.y != 0) {
  17429. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  17430. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  17431. camera.inertialBetaOffset += normalizedRY;
  17432. }
  17433. }
  17434. var LSValues = this.gamepad.leftStick;
  17435. if (LSValues.y != 0) {
  17436. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17437. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  17438. this.camera.inertialRadiusOffset -= normalizedLY;
  17439. }
  17440. }
  17441. }
  17442. };
  17443. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17444. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17445. // prioritize XBOX gamepads.
  17446. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17447. this.gamepad = gamepad;
  17448. }
  17449. }
  17450. };
  17451. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  17452. return "ArcRotateCameraGamepadInput";
  17453. };
  17454. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  17455. return "gamepad";
  17456. };
  17457. return ArcRotateCameraGamepadInput;
  17458. }());
  17459. __decorate([
  17460. BABYLON.serialize()
  17461. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  17462. __decorate([
  17463. BABYLON.serialize()
  17464. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17465. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  17466. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  17467. })(BABYLON || (BABYLON = {}));
  17468. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  17469. var BABYLON;
  17470. (function (BABYLON) {
  17471. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  17472. function ArcRotateCameraVRDeviceOrientationInput() {
  17473. this.alphaCorrection = 1;
  17474. this.betaCorrection = 1;
  17475. this.gammaCorrection = 1;
  17476. this._alpha = 0;
  17477. this._beta = 0;
  17478. this._gamma = 0;
  17479. this._dirty = false;
  17480. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17481. }
  17482. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17483. this.camera.attachControl(element, noPreventDefault);
  17484. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17485. };
  17486. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  17487. var camera = this.camera;
  17488. this._alpha = +evt.alpha | 0;
  17489. this._beta = +evt.beta | 0;
  17490. this._gamma = +evt.gamma | 0;
  17491. this._dirty = true;
  17492. };
  17493. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  17494. if (this._dirty) {
  17495. this._dirty = false;
  17496. if (this._gamma < 0) {
  17497. this._gamma = 180 + this._gamma;
  17498. }
  17499. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  17500. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  17501. }
  17502. };
  17503. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  17504. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17505. };
  17506. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  17507. return "ArcRotateCameraVRDeviceOrientationInput";
  17508. };
  17509. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  17510. return "VRDeviceOrientation";
  17511. };
  17512. return ArcRotateCameraVRDeviceOrientationInput;
  17513. }());
  17514. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  17515. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  17516. })(BABYLON || (BABYLON = {}));
  17517. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  17518. /// <reference path="babylon.camera.ts" />
  17519. var BABYLON;
  17520. (function (BABYLON) {
  17521. var TargetCamera = (function (_super) {
  17522. __extends(TargetCamera, _super);
  17523. function TargetCamera(name, position, scene) {
  17524. var _this = _super.call(this, name, position, scene) || this;
  17525. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17526. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  17527. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  17528. _this.speed = 2.0;
  17529. _this.noRotationConstraint = false;
  17530. _this.lockedTarget = null;
  17531. _this._currentTarget = BABYLON.Vector3.Zero();
  17532. _this._viewMatrix = BABYLON.Matrix.Zero();
  17533. _this._camMatrix = BABYLON.Matrix.Zero();
  17534. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  17535. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  17536. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  17537. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  17538. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  17539. _this._lookAtTemp = BABYLON.Matrix.Zero();
  17540. _this._tempMatrix = BABYLON.Matrix.Zero();
  17541. return _this;
  17542. }
  17543. TargetCamera.prototype.getFrontPosition = function (distance) {
  17544. var direction = this.getTarget().subtract(this.position);
  17545. direction.normalize();
  17546. direction.scaleInPlace(distance);
  17547. return this.globalPosition.add(direction);
  17548. };
  17549. TargetCamera.prototype._getLockedTargetPosition = function () {
  17550. if (!this.lockedTarget) {
  17551. return null;
  17552. }
  17553. if (this.lockedTarget.absolutePosition) {
  17554. this.lockedTarget.computeWorldMatrix();
  17555. }
  17556. return this.lockedTarget.absolutePosition || this.lockedTarget;
  17557. };
  17558. // Cache
  17559. TargetCamera.prototype._initCache = function () {
  17560. _super.prototype._initCache.call(this);
  17561. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17562. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17563. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17564. };
  17565. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  17566. if (!ignoreParentClass) {
  17567. _super.prototype._updateCache.call(this);
  17568. }
  17569. var lockedTargetPosition = this._getLockedTargetPosition();
  17570. if (!lockedTargetPosition) {
  17571. this._cache.lockedTarget = null;
  17572. }
  17573. else {
  17574. if (!this._cache.lockedTarget) {
  17575. this._cache.lockedTarget = lockedTargetPosition.clone();
  17576. }
  17577. else {
  17578. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  17579. }
  17580. }
  17581. this._cache.rotation.copyFrom(this.rotation);
  17582. if (this.rotationQuaternion)
  17583. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17584. };
  17585. // Synchronized
  17586. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  17587. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  17588. return false;
  17589. }
  17590. var lockedTargetPosition = this._getLockedTargetPosition();
  17591. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  17592. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  17593. };
  17594. // Methods
  17595. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  17596. var engine = this.getEngine();
  17597. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  17598. };
  17599. // Target
  17600. TargetCamera.prototype.setTarget = function (target) {
  17601. this.upVector.normalize();
  17602. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  17603. this._camMatrix.invert();
  17604. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  17605. var vDir = target.subtract(this.position);
  17606. if (vDir.x >= 0.0) {
  17607. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  17608. }
  17609. else {
  17610. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  17611. }
  17612. this.rotation.z = 0;
  17613. if (isNaN(this.rotation.x)) {
  17614. this.rotation.x = 0;
  17615. }
  17616. if (isNaN(this.rotation.y)) {
  17617. this.rotation.y = 0;
  17618. }
  17619. if (isNaN(this.rotation.z)) {
  17620. this.rotation.z = 0;
  17621. }
  17622. if (this.rotationQuaternion) {
  17623. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17624. }
  17625. };
  17626. /**
  17627. * Return the current target position of the camera. This value is expressed in local space.
  17628. */
  17629. TargetCamera.prototype.getTarget = function () {
  17630. return this._currentTarget;
  17631. };
  17632. TargetCamera.prototype._decideIfNeedsToMove = function () {
  17633. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17634. };
  17635. TargetCamera.prototype._updatePosition = function () {
  17636. if (this.parent) {
  17637. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  17638. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  17639. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  17640. return;
  17641. }
  17642. this.position.addInPlace(this.cameraDirection);
  17643. };
  17644. TargetCamera.prototype._checkInputs = function () {
  17645. var needToMove = this._decideIfNeedsToMove();
  17646. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  17647. // Move
  17648. if (needToMove) {
  17649. this._updatePosition();
  17650. }
  17651. // Rotate
  17652. if (needToRotate) {
  17653. this.rotation.x += this.cameraRotation.x;
  17654. this.rotation.y += this.cameraRotation.y;
  17655. //rotate, if quaternion is set and rotation was used
  17656. if (this.rotationQuaternion) {
  17657. var len = this.rotation.lengthSquared();
  17658. if (len) {
  17659. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17660. }
  17661. }
  17662. if (!this.noRotationConstraint) {
  17663. var limit = (Math.PI / 2) * 0.95;
  17664. if (this.rotation.x > limit)
  17665. this.rotation.x = limit;
  17666. if (this.rotation.x < -limit)
  17667. this.rotation.x = -limit;
  17668. }
  17669. }
  17670. // Inertia
  17671. if (needToMove) {
  17672. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  17673. this.cameraDirection.x = 0;
  17674. }
  17675. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  17676. this.cameraDirection.y = 0;
  17677. }
  17678. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  17679. this.cameraDirection.z = 0;
  17680. }
  17681. this.cameraDirection.scaleInPlace(this.inertia);
  17682. }
  17683. if (needToRotate) {
  17684. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  17685. this.cameraRotation.x = 0;
  17686. }
  17687. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  17688. this.cameraRotation.y = 0;
  17689. }
  17690. this.cameraRotation.scaleInPlace(this.inertia);
  17691. }
  17692. _super.prototype._checkInputs.call(this);
  17693. };
  17694. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  17695. if (this.rotationQuaternion) {
  17696. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  17697. //update the up vector!
  17698. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  17699. }
  17700. else {
  17701. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17702. }
  17703. };
  17704. TargetCamera.prototype._getViewMatrix = function () {
  17705. if (!this.lockedTarget) {
  17706. // Compute
  17707. this._updateCameraRotationMatrix();
  17708. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17709. // Computing target and final matrix
  17710. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17711. }
  17712. else {
  17713. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  17714. }
  17715. if (this.getScene().useRightHandedSystem) {
  17716. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17717. }
  17718. else {
  17719. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17720. }
  17721. return this._viewMatrix;
  17722. };
  17723. /**
  17724. * @override
  17725. * Override Camera.createRigCamera
  17726. */
  17727. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  17728. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  17729. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  17730. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  17731. if (!this.rotationQuaternion) {
  17732. this.rotationQuaternion = new BABYLON.Quaternion();
  17733. }
  17734. rigCamera._cameraRigParams = {};
  17735. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  17736. }
  17737. return rigCamera;
  17738. }
  17739. return null;
  17740. };
  17741. /**
  17742. * @override
  17743. * Override Camera._updateRigCameras
  17744. */
  17745. TargetCamera.prototype._updateRigCameras = function () {
  17746. var camLeft = this._rigCameras[0];
  17747. var camRight = this._rigCameras[1];
  17748. switch (this.cameraRigMode) {
  17749. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17750. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17751. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17752. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17753. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  17754. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  17755. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  17756. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  17757. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  17758. camLeft.setTarget(this.getTarget());
  17759. camRight.setTarget(this.getTarget());
  17760. break;
  17761. case BABYLON.Camera.RIG_MODE_VR:
  17762. if (camLeft.rotationQuaternion) {
  17763. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17764. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17765. }
  17766. else {
  17767. camLeft.rotation.copyFrom(this.rotation);
  17768. camRight.rotation.copyFrom(this.rotation);
  17769. }
  17770. camLeft.position.copyFrom(this.position);
  17771. camRight.position.copyFrom(this.position);
  17772. break;
  17773. }
  17774. _super.prototype._updateRigCameras.call(this);
  17775. };
  17776. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  17777. if (!this._rigCamTransformMatrix) {
  17778. this._rigCamTransformMatrix = new BABYLON.Matrix();
  17779. }
  17780. var target = this.getTarget();
  17781. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  17782. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17783. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  17784. };
  17785. TargetCamera.prototype.getClassName = function () {
  17786. return "TargetCamera";
  17787. };
  17788. return TargetCamera;
  17789. }(BABYLON.Camera));
  17790. __decorate([
  17791. BABYLON.serializeAsVector3()
  17792. ], TargetCamera.prototype, "rotation", void 0);
  17793. __decorate([
  17794. BABYLON.serialize()
  17795. ], TargetCamera.prototype, "speed", void 0);
  17796. __decorate([
  17797. BABYLON.serializeAsMeshReference("lockedTargetId")
  17798. ], TargetCamera.prototype, "lockedTarget", void 0);
  17799. BABYLON.TargetCamera = TargetCamera;
  17800. })(BABYLON || (BABYLON = {}));
  17801. //# sourceMappingURL=babylon.targetCamera.js.map
  17802. var BABYLON;
  17803. (function (BABYLON) {
  17804. var FreeCamera = (function (_super) {
  17805. __extends(FreeCamera, _super);
  17806. function FreeCamera(name, position, scene) {
  17807. var _this = _super.call(this, name, position, scene) || this;
  17808. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17809. _this.checkCollisions = false;
  17810. _this.applyGravity = false;
  17811. _this._collider = new BABYLON.Collider();
  17812. _this._needMoveForGravity = false;
  17813. _this._oldPosition = BABYLON.Vector3.Zero();
  17814. _this._diffPosition = BABYLON.Vector3.Zero();
  17815. _this._newPosition = BABYLON.Vector3.Zero();
  17816. // Collisions
  17817. _this._collisionMask = -1;
  17818. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17819. if (collidedMesh === void 0) { collidedMesh = null; }
  17820. //TODO move this to the collision coordinator!
  17821. if (_this.getScene().workerCollisions)
  17822. newPosition.multiplyInPlace(_this._collider.radius);
  17823. var updatePosition = function (newPos) {
  17824. _this._newPosition.copyFrom(newPos);
  17825. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  17826. var oldPosition = _this.position.clone();
  17827. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  17828. _this.position.addInPlace(_this._diffPosition);
  17829. if (_this.onCollide && collidedMesh) {
  17830. _this.onCollide(collidedMesh);
  17831. }
  17832. }
  17833. };
  17834. updatePosition(newPosition);
  17835. };
  17836. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  17837. _this.inputs.addKeyboard().addMouse();
  17838. return _this;
  17839. }
  17840. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  17841. //-- begin properties for backward compatibility for inputs
  17842. get: function () {
  17843. var mouse = this.inputs.attached["mouse"];
  17844. if (mouse)
  17845. return mouse.angularSensibility;
  17846. },
  17847. set: function (value) {
  17848. var mouse = this.inputs.attached["mouse"];
  17849. if (mouse)
  17850. mouse.angularSensibility = value;
  17851. },
  17852. enumerable: true,
  17853. configurable: true
  17854. });
  17855. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  17856. get: function () {
  17857. var keyboard = this.inputs.attached["keyboard"];
  17858. if (keyboard)
  17859. return keyboard.keysUp;
  17860. },
  17861. set: function (value) {
  17862. var keyboard = this.inputs.attached["keyboard"];
  17863. if (keyboard)
  17864. keyboard.keysUp = value;
  17865. },
  17866. enumerable: true,
  17867. configurable: true
  17868. });
  17869. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  17870. get: function () {
  17871. var keyboard = this.inputs.attached["keyboard"];
  17872. if (keyboard)
  17873. return keyboard.keysDown;
  17874. },
  17875. set: function (value) {
  17876. var keyboard = this.inputs.attached["keyboard"];
  17877. if (keyboard)
  17878. keyboard.keysDown = value;
  17879. },
  17880. enumerable: true,
  17881. configurable: true
  17882. });
  17883. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  17884. get: function () {
  17885. var keyboard = this.inputs.attached["keyboard"];
  17886. if (keyboard)
  17887. return keyboard.keysLeft;
  17888. },
  17889. set: function (value) {
  17890. var keyboard = this.inputs.attached["keyboard"];
  17891. if (keyboard)
  17892. keyboard.keysLeft = value;
  17893. },
  17894. enumerable: true,
  17895. configurable: true
  17896. });
  17897. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  17898. get: function () {
  17899. var keyboard = this.inputs.attached["keyboard"];
  17900. if (keyboard)
  17901. return keyboard.keysRight;
  17902. },
  17903. set: function (value) {
  17904. var keyboard = this.inputs.attached["keyboard"];
  17905. if (keyboard)
  17906. keyboard.keysRight = value;
  17907. },
  17908. enumerable: true,
  17909. configurable: true
  17910. });
  17911. // Controls
  17912. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  17913. this.inputs.attachElement(element, noPreventDefault);
  17914. };
  17915. FreeCamera.prototype.detachControl = function (element) {
  17916. this.inputs.detachElement(element);
  17917. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17918. this.cameraRotation = new BABYLON.Vector2(0, 0);
  17919. };
  17920. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  17921. get: function () {
  17922. return this._collisionMask;
  17923. },
  17924. set: function (mask) {
  17925. this._collisionMask = !isNaN(mask) ? mask : -1;
  17926. },
  17927. enumerable: true,
  17928. configurable: true
  17929. });
  17930. FreeCamera.prototype._collideWithWorld = function (velocity) {
  17931. var globalPosition;
  17932. if (this.parent) {
  17933. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  17934. }
  17935. else {
  17936. globalPosition = this.position;
  17937. }
  17938. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  17939. this._collider.radius = this.ellipsoid;
  17940. this._collider.collisionMask = this._collisionMask;
  17941. //no need for clone, as long as gravity is not on.
  17942. var actualVelocity = velocity;
  17943. //add gravity to the velocity to prevent the dual-collision checking
  17944. if (this.applyGravity) {
  17945. //this prevents mending with cameraDirection, a global variable of the free camera class.
  17946. actualVelocity = velocity.add(this.getScene().gravity);
  17947. }
  17948. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  17949. };
  17950. FreeCamera.prototype._checkInputs = function () {
  17951. if (!this._localDirection) {
  17952. this._localDirection = BABYLON.Vector3.Zero();
  17953. this._transformedDirection = BABYLON.Vector3.Zero();
  17954. }
  17955. this.inputs.checkInputs();
  17956. _super.prototype._checkInputs.call(this);
  17957. };
  17958. FreeCamera.prototype._decideIfNeedsToMove = function () {
  17959. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17960. };
  17961. FreeCamera.prototype._updatePosition = function () {
  17962. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  17963. this._collideWithWorld(this.cameraDirection);
  17964. }
  17965. else {
  17966. _super.prototype._updatePosition.call(this);
  17967. }
  17968. };
  17969. FreeCamera.prototype.dispose = function () {
  17970. this.inputs.clear();
  17971. _super.prototype.dispose.call(this);
  17972. };
  17973. FreeCamera.prototype.getClassName = function () {
  17974. return "FreeCamera";
  17975. };
  17976. return FreeCamera;
  17977. }(BABYLON.TargetCamera));
  17978. __decorate([
  17979. BABYLON.serializeAsVector3()
  17980. ], FreeCamera.prototype, "ellipsoid", void 0);
  17981. __decorate([
  17982. BABYLON.serialize()
  17983. ], FreeCamera.prototype, "checkCollisions", void 0);
  17984. __decorate([
  17985. BABYLON.serialize()
  17986. ], FreeCamera.prototype, "applyGravity", void 0);
  17987. BABYLON.FreeCamera = FreeCamera;
  17988. })(BABYLON || (BABYLON = {}));
  17989. //# sourceMappingURL=babylon.freeCamera.js.map
  17990. var BABYLON;
  17991. (function (BABYLON) {
  17992. var FreeCameraInputsManager = (function (_super) {
  17993. __extends(FreeCameraInputsManager, _super);
  17994. function FreeCameraInputsManager(camera) {
  17995. return _super.call(this, camera) || this;
  17996. }
  17997. FreeCameraInputsManager.prototype.addKeyboard = function () {
  17998. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  17999. return this;
  18000. };
  18001. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  18002. if (touchEnabled === void 0) { touchEnabled = true; }
  18003. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  18004. return this;
  18005. };
  18006. FreeCameraInputsManager.prototype.addGamepad = function () {
  18007. this.add(new BABYLON.FreeCameraGamepadInput());
  18008. return this;
  18009. };
  18010. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  18011. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  18012. return this;
  18013. };
  18014. FreeCameraInputsManager.prototype.addTouch = function () {
  18015. this.add(new BABYLON.FreeCameraTouchInput());
  18016. return this;
  18017. };
  18018. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  18019. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  18020. return this;
  18021. };
  18022. return FreeCameraInputsManager;
  18023. }(BABYLON.CameraInputsManager));
  18024. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  18025. })(BABYLON || (BABYLON = {}));
  18026. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  18027. /// <reference path="babylon.targetCamera.ts" />
  18028. var BABYLON;
  18029. (function (BABYLON) {
  18030. var FollowCamera = (function (_super) {
  18031. __extends(FollowCamera, _super);
  18032. function FollowCamera(name, position, scene, lockedTarget) {
  18033. var _this = _super.call(this, name, position, scene) || this;
  18034. _this.radius = 12;
  18035. _this.rotationOffset = 0;
  18036. _this.heightOffset = 4;
  18037. _this.cameraAcceleration = 0.05;
  18038. _this.maxCameraSpeed = 20;
  18039. _this.lockedTarget = lockedTarget;
  18040. return _this;
  18041. }
  18042. FollowCamera.prototype.getRadians = function (degrees) {
  18043. return degrees * Math.PI / 180;
  18044. };
  18045. FollowCamera.prototype.follow = function (cameraTarget) {
  18046. if (!cameraTarget)
  18047. return;
  18048. var yRotation;
  18049. if (cameraTarget.rotationQuaternion) {
  18050. var rotMatrix = new BABYLON.Matrix();
  18051. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  18052. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  18053. }
  18054. else {
  18055. yRotation = cameraTarget.rotation.y;
  18056. }
  18057. var radians = this.getRadians(this.rotationOffset) + yRotation;
  18058. var targetPosition = cameraTarget.getAbsolutePosition();
  18059. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  18060. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  18061. var dx = targetX - this.position.x;
  18062. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  18063. var dz = (targetZ) - this.position.z;
  18064. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  18065. var vy = dy * this.cameraAcceleration;
  18066. var vz = dz * this.cameraAcceleration * 2;
  18067. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  18068. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18069. }
  18070. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  18071. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18072. }
  18073. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  18074. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18075. }
  18076. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  18077. this.setTarget(targetPosition);
  18078. };
  18079. FollowCamera.prototype._checkInputs = function () {
  18080. _super.prototype._checkInputs.call(this);
  18081. this.follow(this.lockedTarget);
  18082. };
  18083. FollowCamera.prototype.getClassName = function () {
  18084. return "FollowCamera";
  18085. };
  18086. return FollowCamera;
  18087. }(BABYLON.TargetCamera));
  18088. __decorate([
  18089. BABYLON.serialize()
  18090. ], FollowCamera.prototype, "radius", void 0);
  18091. __decorate([
  18092. BABYLON.serialize()
  18093. ], FollowCamera.prototype, "rotationOffset", void 0);
  18094. __decorate([
  18095. BABYLON.serialize()
  18096. ], FollowCamera.prototype, "heightOffset", void 0);
  18097. __decorate([
  18098. BABYLON.serialize()
  18099. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  18100. __decorate([
  18101. BABYLON.serialize()
  18102. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  18103. __decorate([
  18104. BABYLON.serializeAsMeshReference("lockedTargetId")
  18105. ], FollowCamera.prototype, "lockedTarget", void 0);
  18106. BABYLON.FollowCamera = FollowCamera;
  18107. var ArcFollowCamera = (function (_super) {
  18108. __extends(ArcFollowCamera, _super);
  18109. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  18110. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18111. _this.alpha = alpha;
  18112. _this.beta = beta;
  18113. _this.radius = radius;
  18114. _this.target = target;
  18115. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  18116. _this.follow();
  18117. return _this;
  18118. }
  18119. ArcFollowCamera.prototype.follow = function () {
  18120. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  18121. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  18122. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  18123. var targetPosition = this.target.getAbsolutePosition();
  18124. this.position = targetPosition.add(this._cartesianCoordinates);
  18125. this.setTarget(targetPosition);
  18126. };
  18127. ArcFollowCamera.prototype._checkInputs = function () {
  18128. _super.prototype._checkInputs.call(this);
  18129. this.follow();
  18130. };
  18131. ArcFollowCamera.prototype.getClassName = function () {
  18132. return "ArcFollowCamera";
  18133. };
  18134. return ArcFollowCamera;
  18135. }(BABYLON.TargetCamera));
  18136. BABYLON.ArcFollowCamera = ArcFollowCamera;
  18137. })(BABYLON || (BABYLON = {}));
  18138. //# sourceMappingURL=babylon.followCamera.js.map
  18139. /// <reference path="babylon.freeCamera.ts" />
  18140. var BABYLON;
  18141. (function (BABYLON) {
  18142. // We're mainly based on the logic defined into the FreeCamera code
  18143. var TouchCamera = (function (_super) {
  18144. __extends(TouchCamera, _super);
  18145. //-- end properties for backward compatibility for inputs
  18146. function TouchCamera(name, position, scene) {
  18147. var _this = _super.call(this, name, position, scene) || this;
  18148. _this.inputs.addTouch();
  18149. _this._setupInputs();
  18150. return _this;
  18151. }
  18152. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  18153. //-- Begin properties for backward compatibility for inputs
  18154. get: function () {
  18155. var touch = this.inputs.attached["touch"];
  18156. if (touch)
  18157. return touch.touchAngularSensibility;
  18158. },
  18159. set: function (value) {
  18160. var touch = this.inputs.attached["touch"];
  18161. if (touch)
  18162. touch.touchAngularSensibility = value;
  18163. },
  18164. enumerable: true,
  18165. configurable: true
  18166. });
  18167. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  18168. get: function () {
  18169. var touch = this.inputs.attached["touch"];
  18170. if (touch)
  18171. return touch.touchMoveSensibility;
  18172. },
  18173. set: function (value) {
  18174. var touch = this.inputs.attached["touch"];
  18175. if (touch)
  18176. touch.touchMoveSensibility = value;
  18177. },
  18178. enumerable: true,
  18179. configurable: true
  18180. });
  18181. TouchCamera.prototype.getClassName = function () {
  18182. return "TouchCamera";
  18183. };
  18184. TouchCamera.prototype._setupInputs = function () {
  18185. var mouse = this.inputs.attached["mouse"];
  18186. if (mouse) {
  18187. mouse.touchEnabled = false;
  18188. }
  18189. };
  18190. return TouchCamera;
  18191. }(BABYLON.FreeCamera));
  18192. BABYLON.TouchCamera = TouchCamera;
  18193. })(BABYLON || (BABYLON = {}));
  18194. //# sourceMappingURL=babylon.touchCamera.js.map
  18195. /// <reference path="babylon.targetCamera.ts" />
  18196. /// <reference path="..\Tools\babylon.tools.ts" />
  18197. var BABYLON;
  18198. (function (BABYLON) {
  18199. var ArcRotateCamera = (function (_super) {
  18200. __extends(ArcRotateCamera, _super);
  18201. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  18202. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18203. _this.inertialAlphaOffset = 0;
  18204. _this.inertialBetaOffset = 0;
  18205. _this.inertialRadiusOffset = 0;
  18206. _this.lowerAlphaLimit = null;
  18207. _this.upperAlphaLimit = null;
  18208. _this.lowerBetaLimit = 0.01;
  18209. _this.upperBetaLimit = Math.PI;
  18210. _this.lowerRadiusLimit = null;
  18211. _this.upperRadiusLimit = null;
  18212. _this.inertialPanningX = 0;
  18213. _this.inertialPanningY = 0;
  18214. //-- end properties for backward compatibility for inputs
  18215. _this.zoomOnFactor = 1;
  18216. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  18217. _this.allowUpsideDown = true;
  18218. _this._viewMatrix = new BABYLON.Matrix();
  18219. // Panning
  18220. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  18221. _this.checkCollisions = false;
  18222. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  18223. _this._collider = new BABYLON.Collider();
  18224. _this._previousPosition = BABYLON.Vector3.Zero();
  18225. _this._collisionVelocity = BABYLON.Vector3.Zero();
  18226. _this._newPosition = BABYLON.Vector3.Zero();
  18227. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18228. if (collidedMesh === void 0) { collidedMesh = null; }
  18229. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  18230. newPosition.multiplyInPlace(_this._collider.radius);
  18231. }
  18232. if (!collidedMesh) {
  18233. _this._previousPosition.copyFrom(_this.position);
  18234. }
  18235. else {
  18236. _this.setPosition(newPosition);
  18237. if (_this.onCollide) {
  18238. _this.onCollide(collidedMesh);
  18239. }
  18240. }
  18241. // Recompute because of constraints
  18242. var cosa = Math.cos(_this.alpha);
  18243. var sina = Math.sin(_this.alpha);
  18244. var cosb = Math.cos(_this.beta);
  18245. var sinb = Math.sin(_this.beta);
  18246. if (sinb === 0) {
  18247. sinb = 0.0001;
  18248. }
  18249. var target = _this._getTargetPosition();
  18250. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  18251. _this.position.copyFrom(_this._newPosition);
  18252. var up = _this.upVector;
  18253. if (_this.allowUpsideDown && _this.beta < 0) {
  18254. up = up.clone();
  18255. up = up.negate();
  18256. }
  18257. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  18258. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  18259. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  18260. _this._collisionTriggered = false;
  18261. };
  18262. if (!target) {
  18263. _this.target = BABYLON.Vector3.Zero();
  18264. }
  18265. else {
  18266. _this.target = target;
  18267. }
  18268. _this.alpha = alpha;
  18269. _this.beta = beta;
  18270. _this.radius = radius;
  18271. _this.getViewMatrix();
  18272. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  18273. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  18274. return _this;
  18275. }
  18276. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  18277. //-- begin properties for backward compatibility for inputs
  18278. get: function () {
  18279. var pointers = this.inputs.attached["pointers"];
  18280. if (pointers)
  18281. return pointers.angularSensibilityX;
  18282. },
  18283. set: function (value) {
  18284. var pointers = this.inputs.attached["pointers"];
  18285. if (pointers) {
  18286. pointers.angularSensibilityX = value;
  18287. }
  18288. },
  18289. enumerable: true,
  18290. configurable: true
  18291. });
  18292. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  18293. get: function () {
  18294. var pointers = this.inputs.attached["pointers"];
  18295. if (pointers)
  18296. return pointers.angularSensibilityY;
  18297. },
  18298. set: function (value) {
  18299. var pointers = this.inputs.attached["pointers"];
  18300. if (pointers) {
  18301. pointers.angularSensibilityY = value;
  18302. }
  18303. },
  18304. enumerable: true,
  18305. configurable: true
  18306. });
  18307. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  18308. get: function () {
  18309. var pointers = this.inputs.attached["pointers"];
  18310. if (pointers)
  18311. return pointers.pinchPrecision;
  18312. },
  18313. set: function (value) {
  18314. var pointers = this.inputs.attached["pointers"];
  18315. if (pointers) {
  18316. pointers.pinchPrecision = value;
  18317. }
  18318. },
  18319. enumerable: true,
  18320. configurable: true
  18321. });
  18322. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  18323. get: function () {
  18324. var pointers = this.inputs.attached["pointers"];
  18325. if (pointers)
  18326. return pointers.panningSensibility;
  18327. },
  18328. set: function (value) {
  18329. var pointers = this.inputs.attached["pointers"];
  18330. if (pointers) {
  18331. pointers.panningSensibility = value;
  18332. }
  18333. },
  18334. enumerable: true,
  18335. configurable: true
  18336. });
  18337. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  18338. get: function () {
  18339. var keyboard = this.inputs.attached["keyboard"];
  18340. if (keyboard)
  18341. return keyboard.keysUp;
  18342. },
  18343. set: function (value) {
  18344. var keyboard = this.inputs.attached["keyboard"];
  18345. if (keyboard)
  18346. keyboard.keysUp = value;
  18347. },
  18348. enumerable: true,
  18349. configurable: true
  18350. });
  18351. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  18352. get: function () {
  18353. var keyboard = this.inputs.attached["keyboard"];
  18354. if (keyboard)
  18355. return keyboard.keysDown;
  18356. },
  18357. set: function (value) {
  18358. var keyboard = this.inputs.attached["keyboard"];
  18359. if (keyboard)
  18360. keyboard.keysDown = value;
  18361. },
  18362. enumerable: true,
  18363. configurable: true
  18364. });
  18365. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  18366. get: function () {
  18367. var keyboard = this.inputs.attached["keyboard"];
  18368. if (keyboard)
  18369. return keyboard.keysLeft;
  18370. },
  18371. set: function (value) {
  18372. var keyboard = this.inputs.attached["keyboard"];
  18373. if (keyboard)
  18374. keyboard.keysLeft = value;
  18375. },
  18376. enumerable: true,
  18377. configurable: true
  18378. });
  18379. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  18380. get: function () {
  18381. var keyboard = this.inputs.attached["keyboard"];
  18382. if (keyboard)
  18383. return keyboard.keysRight;
  18384. },
  18385. set: function (value) {
  18386. var keyboard = this.inputs.attached["keyboard"];
  18387. if (keyboard)
  18388. keyboard.keysRight = value;
  18389. },
  18390. enumerable: true,
  18391. configurable: true
  18392. });
  18393. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  18394. get: function () {
  18395. var mousewheel = this.inputs.attached["mousewheel"];
  18396. if (mousewheel)
  18397. return mousewheel.wheelPrecision;
  18398. },
  18399. set: function (value) {
  18400. var mousewheel = this.inputs.attached["mousewheel"];
  18401. if (mousewheel)
  18402. mousewheel.wheelPrecision = value;
  18403. },
  18404. enumerable: true,
  18405. configurable: true
  18406. });
  18407. // Cache
  18408. ArcRotateCamera.prototype._initCache = function () {
  18409. _super.prototype._initCache.call(this);
  18410. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18411. this._cache.alpha = undefined;
  18412. this._cache.beta = undefined;
  18413. this._cache.radius = undefined;
  18414. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  18415. };
  18416. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  18417. if (!ignoreParentClass) {
  18418. _super.prototype._updateCache.call(this);
  18419. }
  18420. this._cache.target.copyFrom(this._getTargetPosition());
  18421. this._cache.alpha = this.alpha;
  18422. this._cache.beta = this.beta;
  18423. this._cache.radius = this.radius;
  18424. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  18425. };
  18426. ArcRotateCamera.prototype._getTargetPosition = function () {
  18427. if (this.target.getAbsolutePosition) {
  18428. var pos = this.target.getAbsolutePosition();
  18429. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  18430. }
  18431. return this.target;
  18432. };
  18433. // Synchronized
  18434. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  18435. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  18436. return false;
  18437. return this._cache.target.equals(this.target)
  18438. && this._cache.alpha === this.alpha
  18439. && this._cache.beta === this.beta
  18440. && this._cache.radius === this.radius
  18441. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  18442. };
  18443. // Methods
  18444. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  18445. var _this = this;
  18446. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  18447. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  18448. this._useCtrlForPanning = useCtrlForPanning;
  18449. this._panningMouseButton = panningMouseButton;
  18450. this.inputs.attachElement(element, noPreventDefault);
  18451. this._reset = function () {
  18452. _this.inertialAlphaOffset = 0;
  18453. _this.inertialBetaOffset = 0;
  18454. _this.inertialRadiusOffset = 0;
  18455. };
  18456. };
  18457. ArcRotateCamera.prototype.detachControl = function (element) {
  18458. this.inputs.detachElement(element);
  18459. if (this._reset) {
  18460. this._reset();
  18461. }
  18462. };
  18463. ArcRotateCamera.prototype._checkInputs = function () {
  18464. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  18465. if (this._collisionTriggered) {
  18466. return;
  18467. }
  18468. this.inputs.checkInputs();
  18469. // Inertia
  18470. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  18471. if (this.getScene().useRightHandedSystem) {
  18472. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18473. }
  18474. else {
  18475. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18476. }
  18477. this.beta += this.inertialBetaOffset;
  18478. this.radius -= this.inertialRadiusOffset;
  18479. this.inertialAlphaOffset *= this.inertia;
  18480. this.inertialBetaOffset *= this.inertia;
  18481. this.inertialRadiusOffset *= this.inertia;
  18482. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  18483. this.inertialAlphaOffset = 0;
  18484. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  18485. this.inertialBetaOffset = 0;
  18486. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  18487. this.inertialRadiusOffset = 0;
  18488. }
  18489. // Panning inertia
  18490. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  18491. if (!this._localDirection) {
  18492. this._localDirection = BABYLON.Vector3.Zero();
  18493. this._transformedDirection = BABYLON.Vector3.Zero();
  18494. }
  18495. this.inertialPanningX *= this.inertia;
  18496. this.inertialPanningY *= this.inertia;
  18497. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  18498. this.inertialPanningX = 0;
  18499. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  18500. this.inertialPanningY = 0;
  18501. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  18502. this._localDirection.multiplyInPlace(this.panningAxis);
  18503. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  18504. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  18505. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  18506. if (!this.panningAxis.y) {
  18507. this._transformedDirection.y = 0;
  18508. }
  18509. if (!this.target.getAbsolutePosition) {
  18510. this.target.addInPlace(this._transformedDirection);
  18511. }
  18512. }
  18513. // Limits
  18514. this._checkLimits();
  18515. _super.prototype._checkInputs.call(this);
  18516. };
  18517. ArcRotateCamera.prototype._checkLimits = function () {
  18518. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  18519. if (this.allowUpsideDown && this.beta > Math.PI) {
  18520. this.beta = this.beta - (2 * Math.PI);
  18521. }
  18522. }
  18523. else {
  18524. if (this.beta < this.lowerBetaLimit) {
  18525. this.beta = this.lowerBetaLimit;
  18526. }
  18527. }
  18528. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  18529. if (this.allowUpsideDown && this.beta < -Math.PI) {
  18530. this.beta = this.beta + (2 * Math.PI);
  18531. }
  18532. }
  18533. else {
  18534. if (this.beta > this.upperBetaLimit) {
  18535. this.beta = this.upperBetaLimit;
  18536. }
  18537. }
  18538. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  18539. this.alpha = this.lowerAlphaLimit;
  18540. }
  18541. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  18542. this.alpha = this.upperAlphaLimit;
  18543. }
  18544. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  18545. this.radius = this.lowerRadiusLimit;
  18546. }
  18547. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  18548. this.radius = this.upperRadiusLimit;
  18549. }
  18550. };
  18551. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  18552. var radiusv3 = this.position.subtract(this._getTargetPosition());
  18553. this.radius = radiusv3.length();
  18554. // Alpha
  18555. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  18556. if (radiusv3.z < 0) {
  18557. this.alpha = 2 * Math.PI - this.alpha;
  18558. }
  18559. // Beta
  18560. this.beta = Math.acos(radiusv3.y / this.radius);
  18561. this._checkLimits();
  18562. };
  18563. ArcRotateCamera.prototype.setPosition = function (position) {
  18564. if (this.position.equals(position)) {
  18565. return;
  18566. }
  18567. this.position.copyFrom(position);
  18568. this.rebuildAnglesAndRadius();
  18569. };
  18570. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  18571. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  18572. if (allowSamePosition === void 0) { allowSamePosition = false; }
  18573. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  18574. return;
  18575. }
  18576. if (toBoundingCenter && target.getBoundingInfo) {
  18577. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  18578. }
  18579. else {
  18580. this._targetBoundingCenter = null;
  18581. }
  18582. this.target = target;
  18583. this.rebuildAnglesAndRadius();
  18584. };
  18585. ArcRotateCamera.prototype._getViewMatrix = function () {
  18586. // Compute
  18587. var cosa = Math.cos(this.alpha);
  18588. var sina = Math.sin(this.alpha);
  18589. var cosb = Math.cos(this.beta);
  18590. var sinb = Math.sin(this.beta);
  18591. if (sinb === 0) {
  18592. sinb = 0.0001;
  18593. }
  18594. var target = this._getTargetPosition();
  18595. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  18596. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  18597. this._collider.radius = this.collisionRadius;
  18598. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  18599. this._collisionTriggered = true;
  18600. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18601. }
  18602. else {
  18603. this.position.copyFrom(this._newPosition);
  18604. var up = this.upVector;
  18605. if (this.allowUpsideDown && sinb < 0) {
  18606. up = up.clone();
  18607. up = up.negate();
  18608. }
  18609. if (this.getScene().useRightHandedSystem) {
  18610. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  18611. }
  18612. else {
  18613. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  18614. }
  18615. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  18616. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  18617. }
  18618. this._currentTarget = target;
  18619. return this._viewMatrix;
  18620. };
  18621. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  18622. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18623. meshes = meshes || this.getScene().meshes;
  18624. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  18625. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  18626. this.radius = distance * this.zoomOnFactor;
  18627. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  18628. };
  18629. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  18630. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18631. var meshesOrMinMaxVector;
  18632. var distance;
  18633. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  18634. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  18635. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  18636. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  18637. }
  18638. else {
  18639. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  18640. distance = meshesOrMinMaxVectorAndDistance.distance;
  18641. }
  18642. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  18643. if (!doNotUpdateMaxZ) {
  18644. this.maxZ = distance * 2;
  18645. }
  18646. };
  18647. /**
  18648. * @override
  18649. * Override Camera.createRigCamera
  18650. */
  18651. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  18652. var alphaShift;
  18653. switch (this.cameraRigMode) {
  18654. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18655. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18656. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18657. case BABYLON.Camera.RIG_MODE_VR:
  18658. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  18659. break;
  18660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18661. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  18662. break;
  18663. }
  18664. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  18665. rigCam._cameraRigParams = {};
  18666. return rigCam;
  18667. };
  18668. /**
  18669. * @override
  18670. * Override Camera._updateRigCameras
  18671. */
  18672. ArcRotateCamera.prototype._updateRigCameras = function () {
  18673. var camLeft = this._rigCameras[0];
  18674. var camRight = this._rigCameras[1];
  18675. camLeft.beta = camRight.beta = this.beta;
  18676. camLeft.radius = camRight.radius = this.radius;
  18677. switch (this.cameraRigMode) {
  18678. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18679. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18680. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18681. case BABYLON.Camera.RIG_MODE_VR:
  18682. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18683. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18684. break;
  18685. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18686. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18687. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18688. break;
  18689. }
  18690. _super.prototype._updateRigCameras.call(this);
  18691. };
  18692. ArcRotateCamera.prototype.dispose = function () {
  18693. this.inputs.clear();
  18694. _super.prototype.dispose.call(this);
  18695. };
  18696. ArcRotateCamera.prototype.getClassName = function () {
  18697. return "ArcRotateCamera";
  18698. };
  18699. return ArcRotateCamera;
  18700. }(BABYLON.TargetCamera));
  18701. __decorate([
  18702. BABYLON.serialize()
  18703. ], ArcRotateCamera.prototype, "alpha", void 0);
  18704. __decorate([
  18705. BABYLON.serialize()
  18706. ], ArcRotateCamera.prototype, "beta", void 0);
  18707. __decorate([
  18708. BABYLON.serialize()
  18709. ], ArcRotateCamera.prototype, "radius", void 0);
  18710. __decorate([
  18711. BABYLON.serializeAsVector3()
  18712. ], ArcRotateCamera.prototype, "target", void 0);
  18713. __decorate([
  18714. BABYLON.serialize()
  18715. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  18716. __decorate([
  18717. BABYLON.serialize()
  18718. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  18719. __decorate([
  18720. BABYLON.serialize()
  18721. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  18722. __decorate([
  18723. BABYLON.serialize()
  18724. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  18725. __decorate([
  18726. BABYLON.serialize()
  18727. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  18728. __decorate([
  18729. BABYLON.serialize()
  18730. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  18731. __decorate([
  18732. BABYLON.serialize()
  18733. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  18734. __decorate([
  18735. BABYLON.serialize()
  18736. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  18737. __decorate([
  18738. BABYLON.serialize()
  18739. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  18740. __decorate([
  18741. BABYLON.serialize()
  18742. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  18743. __decorate([
  18744. BABYLON.serialize()
  18745. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  18746. __decorate([
  18747. BABYLON.serialize()
  18748. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  18749. __decorate([
  18750. BABYLON.serialize()
  18751. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  18752. BABYLON.ArcRotateCamera = ArcRotateCamera;
  18753. })(BABYLON || (BABYLON = {}));
  18754. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  18755. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  18756. var BABYLON;
  18757. (function (BABYLON) {
  18758. var ArcRotateCameraInputsManager = (function (_super) {
  18759. __extends(ArcRotateCameraInputsManager, _super);
  18760. function ArcRotateCameraInputsManager(camera) {
  18761. return _super.call(this, camera) || this;
  18762. }
  18763. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  18764. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  18765. return this;
  18766. };
  18767. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  18768. this.add(new BABYLON.ArcRotateCameraPointersInput());
  18769. return this;
  18770. };
  18771. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  18772. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  18773. return this;
  18774. };
  18775. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  18776. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  18777. return this;
  18778. };
  18779. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  18780. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  18781. return this;
  18782. };
  18783. return ArcRotateCameraInputsManager;
  18784. }(BABYLON.CameraInputsManager));
  18785. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  18786. })(BABYLON || (BABYLON = {}));
  18787. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  18788. var BABYLON;
  18789. (function (BABYLON) {
  18790. var RenderingManager = (function () {
  18791. function RenderingManager(scene) {
  18792. this._renderingGroups = new Array();
  18793. this._autoClearDepthStencil = {};
  18794. this._customOpaqueSortCompareFn = {};
  18795. this._customAlphaTestSortCompareFn = {};
  18796. this._customTransparentSortCompareFn = {};
  18797. this._renderinGroupInfo = null;
  18798. this._scene = scene;
  18799. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18800. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18801. }
  18802. }
  18803. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18804. if (depth === void 0) { depth = true; }
  18805. if (stencil === void 0) { stencil = true; }
  18806. if (this._depthStencilBufferAlreadyCleaned) {
  18807. return;
  18808. }
  18809. this._scene.getEngine().clear(null, false, depth, stencil);
  18810. this._depthStencilBufferAlreadyCleaned = true;
  18811. };
  18812. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18813. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18814. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18815. var info = null;
  18816. if (observable) {
  18817. if (!this._renderinGroupInfo) {
  18818. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18819. }
  18820. info = this._renderinGroupInfo;
  18821. info.scene = this._scene;
  18822. info.camera = this._scene.activeCamera;
  18823. }
  18824. // Dispatch sprites
  18825. if (renderSprites) {
  18826. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18827. var manager = this._scene.spriteManagers[index];
  18828. this.dispatchSprites(manager);
  18829. }
  18830. }
  18831. // Render
  18832. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18833. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18834. var renderingGroup = this._renderingGroups[index];
  18835. if (!renderingGroup && !observable)
  18836. continue;
  18837. this._currentIndex = index;
  18838. var renderingGroupMask = 0;
  18839. // Fire PRECLEAR stage
  18840. if (observable) {
  18841. renderingGroupMask = Math.pow(2, index);
  18842. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18843. info.renderingGroupId = index;
  18844. observable.notifyObservers(info, renderingGroupMask);
  18845. }
  18846. // Clear depth/stencil if needed
  18847. var autoClear = this._autoClearDepthStencil[index];
  18848. if (autoClear && autoClear.autoClear) {
  18849. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18850. }
  18851. if (observable) {
  18852. // Fire PREOPAQUE stage
  18853. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18854. observable.notifyObservers(info, renderingGroupMask);
  18855. // Fire PRETRANSPARENT stage
  18856. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18857. observable.notifyObservers(info, renderingGroupMask);
  18858. }
  18859. if (renderingGroup)
  18860. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18861. // Fire POSTTRANSPARENT stage
  18862. if (observable) {
  18863. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18864. observable.notifyObservers(info, renderingGroupMask);
  18865. }
  18866. }
  18867. };
  18868. RenderingManager.prototype.reset = function () {
  18869. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18870. var renderingGroup = this._renderingGroups[index];
  18871. if (renderingGroup) {
  18872. renderingGroup.prepare();
  18873. }
  18874. }
  18875. };
  18876. RenderingManager.prototype.dispose = function () {
  18877. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18878. var renderingGroup = this._renderingGroups[index];
  18879. if (renderingGroup) {
  18880. renderingGroup.dispose();
  18881. }
  18882. }
  18883. this._renderingGroups.length = 0;
  18884. };
  18885. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18886. if (!this._renderingGroups[renderingGroupId]) {
  18887. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18888. }
  18889. };
  18890. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18891. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18892. this._prepareRenderingGroup(renderingGroupId);
  18893. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18894. };
  18895. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18896. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18897. this._prepareRenderingGroup(renderingGroupId);
  18898. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18899. };
  18900. RenderingManager.prototype.dispatch = function (subMesh) {
  18901. var mesh = subMesh.getMesh();
  18902. var renderingGroupId = mesh.renderingGroupId || 0;
  18903. this._prepareRenderingGroup(renderingGroupId);
  18904. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  18905. };
  18906. /**
  18907. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18908. * This allowed control for front to back rendering or reversly depending of the special needs.
  18909. *
  18910. * @param renderingGroupId The rendering group id corresponding to its index
  18911. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18912. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18913. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18914. */
  18915. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18916. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18917. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18918. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18919. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18920. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18921. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18922. if (this._renderingGroups[renderingGroupId]) {
  18923. var group = this._renderingGroups[renderingGroupId];
  18924. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18925. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18926. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18927. }
  18928. };
  18929. /**
  18930. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18931. *
  18932. * @param renderingGroupId The rendering group id corresponding to its index
  18933. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18934. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18935. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18936. */
  18937. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18938. if (depth === void 0) { depth = true; }
  18939. if (stencil === void 0) { stencil = true; }
  18940. this._autoClearDepthStencil[renderingGroupId] = {
  18941. autoClear: autoClearDepthStencil,
  18942. depth: depth,
  18943. stencil: stencil
  18944. };
  18945. };
  18946. return RenderingManager;
  18947. }());
  18948. /**
  18949. * The max id used for rendering groups (not included)
  18950. */
  18951. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18952. /**
  18953. * The min id used for rendering groups (included)
  18954. */
  18955. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18956. BABYLON.RenderingManager = RenderingManager;
  18957. })(BABYLON || (BABYLON = {}));
  18958. //# sourceMappingURL=babylon.renderingManager.js.map
  18959. var BABYLON;
  18960. (function (BABYLON) {
  18961. var RenderingGroup = (function () {
  18962. /**
  18963. * Creates a new rendering group.
  18964. * @param index The rendering group index
  18965. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18966. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18967. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18968. */
  18969. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18970. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18971. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18972. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18973. this.index = index;
  18974. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18975. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18976. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18977. this._particleSystems = new BABYLON.SmartArray(256);
  18978. this._spriteManagers = new BABYLON.SmartArray(256);
  18979. this._scene = scene;
  18980. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18981. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18982. this.transparentSortCompareFn = transparentSortCompareFn;
  18983. }
  18984. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18985. /**
  18986. * Set the opaque sort comparison function.
  18987. * If null the sub meshes will be render in the order they were created
  18988. */
  18989. set: function (value) {
  18990. this._opaqueSortCompareFn = value;
  18991. if (value) {
  18992. this._renderOpaque = this.renderOpaqueSorted;
  18993. }
  18994. else {
  18995. this._renderOpaque = RenderingGroup.renderUnsorted;
  18996. }
  18997. },
  18998. enumerable: true,
  18999. configurable: true
  19000. });
  19001. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19002. /**
  19003. * Set the alpha test sort comparison function.
  19004. * If null the sub meshes will be render in the order they were created
  19005. */
  19006. set: function (value) {
  19007. this._alphaTestSortCompareFn = value;
  19008. if (value) {
  19009. this._renderAlphaTest = this.renderAlphaTestSorted;
  19010. }
  19011. else {
  19012. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19013. }
  19014. },
  19015. enumerable: true,
  19016. configurable: true
  19017. });
  19018. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19019. /**
  19020. * Set the transparent sort comparison function.
  19021. * If null the sub meshes will be render in the order they were created
  19022. */
  19023. set: function (value) {
  19024. if (value) {
  19025. this._transparentSortCompareFn = value;
  19026. }
  19027. else {
  19028. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19029. }
  19030. this._renderTransparent = this.renderTransparentSorted;
  19031. },
  19032. enumerable: true,
  19033. configurable: true
  19034. });
  19035. /**
  19036. * Render all the sub meshes contained in the group.
  19037. * @param customRenderFunction Used to override the default render behaviour of the group.
  19038. * @returns true if rendered some submeshes.
  19039. */
  19040. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19041. if (customRenderFunction) {
  19042. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  19043. return;
  19044. }
  19045. var engine = this._scene.getEngine();
  19046. // Opaque
  19047. if (this._opaqueSubMeshes.length !== 0) {
  19048. this._renderOpaque(this._opaqueSubMeshes);
  19049. }
  19050. // Alpha test
  19051. if (this._alphaTestSubMeshes.length !== 0) {
  19052. engine.setAlphaTesting(true);
  19053. this._renderAlphaTest(this._alphaTestSubMeshes);
  19054. engine.setAlphaTesting(false);
  19055. }
  19056. // Sprites
  19057. if (renderSprites) {
  19058. this._renderSprites();
  19059. }
  19060. // Particles
  19061. if (renderParticles) {
  19062. this._renderParticles(activeMeshes);
  19063. }
  19064. if (this.onBeforeTransparentRendering) {
  19065. this.onBeforeTransparentRendering();
  19066. }
  19067. // Transparent
  19068. if (this._transparentSubMeshes.length !== 0) {
  19069. this._renderTransparent(this._transparentSubMeshes);
  19070. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19071. }
  19072. };
  19073. /**
  19074. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19075. * @param subMeshes The submeshes to render
  19076. */
  19077. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19078. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19079. };
  19080. /**
  19081. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19082. * @param subMeshes The submeshes to render
  19083. */
  19084. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19085. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19086. };
  19087. /**
  19088. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19089. * @param subMeshes The submeshes to render
  19090. */
  19091. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19092. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  19093. };
  19094. /**
  19095. * Renders the submeshes in a specified order.
  19096. * @param subMeshes The submeshes to sort before render
  19097. * @param sortCompareFn The comparison function use to sort
  19098. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19099. * @param transparent Specifies to activate blending if true
  19100. */
  19101. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  19102. var subIndex = 0;
  19103. var subMesh;
  19104. for (; subIndex < subMeshes.length; subIndex++) {
  19105. subMesh = subMeshes.data[subIndex];
  19106. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19107. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19108. }
  19109. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19110. sortedArray.sort(sortCompareFn);
  19111. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19112. subMesh = sortedArray[subIndex];
  19113. subMesh.render(transparent);
  19114. }
  19115. };
  19116. /**
  19117. * Renders the submeshes in the order they were dispatched (no sort applied).
  19118. * @param subMeshes The submeshes to render
  19119. */
  19120. RenderingGroup.renderUnsorted = function (subMeshes) {
  19121. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19122. var submesh = subMeshes.data[subIndex];
  19123. submesh.render(false);
  19124. }
  19125. };
  19126. /**
  19127. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19128. * are rendered back to front if in the same alpha index.
  19129. *
  19130. * @param a The first submesh
  19131. * @param b The second submesh
  19132. * @returns The result of the comparison
  19133. */
  19134. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19135. // Alpha index first
  19136. if (a._alphaIndex > b._alphaIndex) {
  19137. return 1;
  19138. }
  19139. if (a._alphaIndex < b._alphaIndex) {
  19140. return -1;
  19141. }
  19142. // Then distance to camera
  19143. return RenderingGroup.backToFrontSortCompare(a, b);
  19144. };
  19145. /**
  19146. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19147. * are rendered back to front.
  19148. *
  19149. * @param a The first submesh
  19150. * @param b The second submesh
  19151. * @returns The result of the comparison
  19152. */
  19153. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19154. // Then distance to camera
  19155. if (a._distanceToCamera < b._distanceToCamera) {
  19156. return 1;
  19157. }
  19158. if (a._distanceToCamera > b._distanceToCamera) {
  19159. return -1;
  19160. }
  19161. return 0;
  19162. };
  19163. /**
  19164. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19165. * are rendered front to back (prevent overdraw).
  19166. *
  19167. * @param a The first submesh
  19168. * @param b The second submesh
  19169. * @returns The result of the comparison
  19170. */
  19171. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19172. // Then distance to camera
  19173. if (a._distanceToCamera < b._distanceToCamera) {
  19174. return -1;
  19175. }
  19176. if (a._distanceToCamera > b._distanceToCamera) {
  19177. return 1;
  19178. }
  19179. return 0;
  19180. };
  19181. /**
  19182. * Resets the different lists of submeshes to prepare a new frame.
  19183. */
  19184. RenderingGroup.prototype.prepare = function () {
  19185. this._opaqueSubMeshes.reset();
  19186. this._transparentSubMeshes.reset();
  19187. this._alphaTestSubMeshes.reset();
  19188. this._particleSystems.reset();
  19189. this._spriteManagers.reset();
  19190. };
  19191. RenderingGroup.prototype.dispose = function () {
  19192. this._opaqueSubMeshes.dispose();
  19193. this._transparentSubMeshes.dispose();
  19194. this._alphaTestSubMeshes.dispose();
  19195. this._particleSystems.dispose();
  19196. this._spriteManagers.dispose();
  19197. };
  19198. /**
  19199. * Inserts the submesh in its correct queue depending on its material.
  19200. * @param subMesh The submesh to dispatch
  19201. */
  19202. RenderingGroup.prototype.dispatch = function (subMesh) {
  19203. var material = subMesh.getMaterial();
  19204. var mesh = subMesh.getMesh();
  19205. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  19206. this._transparentSubMeshes.push(subMesh);
  19207. }
  19208. else if (material.needAlphaTesting()) {
  19209. this._alphaTestSubMeshes.push(subMesh);
  19210. }
  19211. else {
  19212. this._opaqueSubMeshes.push(subMesh); // Opaque
  19213. }
  19214. };
  19215. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19216. this._spriteManagers.push(spriteManager);
  19217. };
  19218. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19219. this._particleSystems.push(particleSystem);
  19220. };
  19221. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19222. if (this._particleSystems.length === 0) {
  19223. return;
  19224. }
  19225. // Particles
  19226. var activeCamera = this._scene.activeCamera;
  19227. this._scene._particlesDuration.beginMonitoring();
  19228. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19229. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19230. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19231. continue;
  19232. }
  19233. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  19234. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19235. }
  19236. }
  19237. this._scene._particlesDuration.endMonitoring(false);
  19238. };
  19239. RenderingGroup.prototype._renderSprites = function () {
  19240. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19241. return;
  19242. }
  19243. // Sprites
  19244. var activeCamera = this._scene.activeCamera;
  19245. this._scene._spritesDuration.beginMonitoring();
  19246. for (var id = 0; id < this._spriteManagers.length; id++) {
  19247. var spriteManager = this._spriteManagers.data[id];
  19248. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19249. spriteManager.render();
  19250. }
  19251. }
  19252. this._scene._spritesDuration.endMonitoring(false);
  19253. };
  19254. return RenderingGroup;
  19255. }());
  19256. BABYLON.RenderingGroup = RenderingGroup;
  19257. })(BABYLON || (BABYLON = {}));
  19258. //# sourceMappingURL=babylon.renderingGroup.js.map
  19259. var BABYLON;
  19260. (function (BABYLON) {
  19261. var ClickInfo = (function () {
  19262. function ClickInfo() {
  19263. this._singleClick = false;
  19264. this._doubleClick = false;
  19265. this._hasSwiped = false;
  19266. this._ignore = false;
  19267. }
  19268. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19269. get: function () {
  19270. return this._singleClick;
  19271. },
  19272. set: function (b) {
  19273. this._singleClick = b;
  19274. },
  19275. enumerable: true,
  19276. configurable: true
  19277. });
  19278. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19279. get: function () {
  19280. return this._doubleClick;
  19281. },
  19282. set: function (b) {
  19283. this._doubleClick = b;
  19284. },
  19285. enumerable: true,
  19286. configurable: true
  19287. });
  19288. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19289. get: function () {
  19290. return this._hasSwiped;
  19291. },
  19292. set: function (b) {
  19293. this._hasSwiped = b;
  19294. },
  19295. enumerable: true,
  19296. configurable: true
  19297. });
  19298. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19299. get: function () {
  19300. return this._ignore;
  19301. },
  19302. set: function (b) {
  19303. this._ignore = b;
  19304. },
  19305. enumerable: true,
  19306. configurable: true
  19307. });
  19308. return ClickInfo;
  19309. }());
  19310. var PointerEventTypes = (function () {
  19311. function PointerEventTypes() {
  19312. }
  19313. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  19314. get: function () {
  19315. return PointerEventTypes._POINTERDOWN;
  19316. },
  19317. enumerable: true,
  19318. configurable: true
  19319. });
  19320. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  19321. get: function () {
  19322. return PointerEventTypes._POINTERUP;
  19323. },
  19324. enumerable: true,
  19325. configurable: true
  19326. });
  19327. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  19328. get: function () {
  19329. return PointerEventTypes._POINTERMOVE;
  19330. },
  19331. enumerable: true,
  19332. configurable: true
  19333. });
  19334. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  19335. get: function () {
  19336. return PointerEventTypes._POINTERWHEEL;
  19337. },
  19338. enumerable: true,
  19339. configurable: true
  19340. });
  19341. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  19342. get: function () {
  19343. return PointerEventTypes._POINTERPICK;
  19344. },
  19345. enumerable: true,
  19346. configurable: true
  19347. });
  19348. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  19349. get: function () {
  19350. return PointerEventTypes._POINTERTAP;
  19351. },
  19352. enumerable: true,
  19353. configurable: true
  19354. });
  19355. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  19356. get: function () {
  19357. return PointerEventTypes._POINTERDOUBLETAP;
  19358. },
  19359. enumerable: true,
  19360. configurable: true
  19361. });
  19362. return PointerEventTypes;
  19363. }());
  19364. PointerEventTypes._POINTERDOWN = 0x01;
  19365. PointerEventTypes._POINTERUP = 0x02;
  19366. PointerEventTypes._POINTERMOVE = 0x04;
  19367. PointerEventTypes._POINTERWHEEL = 0x08;
  19368. PointerEventTypes._POINTERPICK = 0x10;
  19369. PointerEventTypes._POINTERTAP = 0x20;
  19370. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  19371. BABYLON.PointerEventTypes = PointerEventTypes;
  19372. var PointerInfoBase = (function () {
  19373. function PointerInfoBase(type, event) {
  19374. this.type = type;
  19375. this.event = event;
  19376. }
  19377. return PointerInfoBase;
  19378. }());
  19379. BABYLON.PointerInfoBase = PointerInfoBase;
  19380. /**
  19381. * This class is used to store pointer related info for the onPrePointerObservable event.
  19382. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  19383. */
  19384. var PointerInfoPre = (function (_super) {
  19385. __extends(PointerInfoPre, _super);
  19386. function PointerInfoPre(type, event, localX, localY) {
  19387. var _this = _super.call(this, type, event) || this;
  19388. _this.skipOnPointerObservable = false;
  19389. _this.localPosition = new BABYLON.Vector2(localX, localY);
  19390. return _this;
  19391. }
  19392. return PointerInfoPre;
  19393. }(PointerInfoBase));
  19394. BABYLON.PointerInfoPre = PointerInfoPre;
  19395. /**
  19396. * This type contains all the data related to a pointer event in Babylon.js.
  19397. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  19398. */
  19399. var PointerInfo = (function (_super) {
  19400. __extends(PointerInfo, _super);
  19401. function PointerInfo(type, event, pickInfo) {
  19402. var _this = _super.call(this, type, event) || this;
  19403. _this.pickInfo = pickInfo;
  19404. return _this;
  19405. }
  19406. return PointerInfo;
  19407. }(PointerInfoBase));
  19408. BABYLON.PointerInfo = PointerInfo;
  19409. /**
  19410. * This class is used by the onRenderingGroupObservable
  19411. */
  19412. var RenderingGroupInfo = (function () {
  19413. function RenderingGroupInfo() {
  19414. }
  19415. return RenderingGroupInfo;
  19416. }());
  19417. /**
  19418. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19419. * This stage will be fired no matter what
  19420. */
  19421. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19422. /**
  19423. * Called before opaque object are rendered.
  19424. * This stage will be fired only if there's 3D Opaque content to render
  19425. */
  19426. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19427. /**
  19428. * Called after the opaque objects are rendered and before the transparent ones
  19429. * This stage will be fired only if there's 3D transparent content to render
  19430. */
  19431. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19432. /**
  19433. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19434. * This stage will be fired no matter what
  19435. */
  19436. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19437. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19438. /**
  19439. * Represents a scene to be rendered by the engine.
  19440. * @see http://doc.babylonjs.com/page.php?p=21911
  19441. */
  19442. var Scene = (function () {
  19443. /**
  19444. * @constructor
  19445. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19446. */
  19447. function Scene(engine) {
  19448. // Members
  19449. this.autoClear = true;
  19450. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19451. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19452. this.forceWireframe = false;
  19453. this.forcePointsCloud = false;
  19454. this.forceShowBoundingBoxes = false;
  19455. this.animationsEnabled = true;
  19456. this.constantlyUpdateMeshUnderPointer = false;
  19457. this.useRightHandedSystem = false;
  19458. this.hoverCursor = "pointer";
  19459. // Metadata
  19460. this.metadata = null;
  19461. // Events
  19462. /**
  19463. * An event triggered when the scene is disposed.
  19464. * @type {BABYLON.Observable}
  19465. */
  19466. this.onDisposeObservable = new BABYLON.Observable();
  19467. /**
  19468. * An event triggered before rendering the scene
  19469. * @type {BABYLON.Observable}
  19470. */
  19471. this.onBeforeRenderObservable = new BABYLON.Observable();
  19472. /**
  19473. * An event triggered after rendering the scene
  19474. * @type {BABYLON.Observable}
  19475. */
  19476. this.onAfterRenderObservable = new BABYLON.Observable();
  19477. /**
  19478. * An event triggered when the scene is ready
  19479. * @type {BABYLON.Observable}
  19480. */
  19481. this.onReadyObservable = new BABYLON.Observable();
  19482. /**
  19483. * An event triggered before rendering a camera
  19484. * @type {BABYLON.Observable}
  19485. */
  19486. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19487. /**
  19488. * An event triggered after rendering a camera
  19489. * @type {BABYLON.Observable}
  19490. */
  19491. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19492. /**
  19493. * An event triggered when a camera is created
  19494. * @type {BABYLON.Observable}
  19495. */
  19496. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19497. /**
  19498. * An event triggered when a camera is removed
  19499. * @type {BABYLON.Observable}
  19500. */
  19501. this.onCameraRemovedObservable = new BABYLON.Observable();
  19502. /**
  19503. * An event triggered when a light is created
  19504. * @type {BABYLON.Observable}
  19505. */
  19506. this.onNewLightAddedObservable = new BABYLON.Observable();
  19507. /**
  19508. * An event triggered when a light is removed
  19509. * @type {BABYLON.Observable}
  19510. */
  19511. this.onLightRemovedObservable = new BABYLON.Observable();
  19512. /**
  19513. * An event triggered when a geometry is created
  19514. * @type {BABYLON.Observable}
  19515. */
  19516. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19517. /**
  19518. * An event triggered when a geometry is removed
  19519. * @type {BABYLON.Observable}
  19520. */
  19521. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19522. /**
  19523. * An event triggered when a mesh is created
  19524. * @type {BABYLON.Observable}
  19525. */
  19526. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19527. /**
  19528. * An event triggered when a mesh is removed
  19529. * @type {BABYLON.Observable}
  19530. */
  19531. this.onMeshRemovedObservable = new BABYLON.Observable();
  19532. /**
  19533. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19534. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19535. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  19536. */
  19537. this.onRenderingGroupObservable = new BABYLON.Observable();
  19538. // Animations
  19539. this.animations = [];
  19540. /**
  19541. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  19542. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  19543. */
  19544. this.onPrePointerObservable = new BABYLON.Observable();
  19545. /**
  19546. * Observable event triggered each time an input event is received from the rendering canvas
  19547. */
  19548. this.onPointerObservable = new BABYLON.Observable();
  19549. this._meshPickProceed = false;
  19550. this._previousHasSwiped = false;
  19551. this._currentPickResult = null;
  19552. this._previousPickResult = null;
  19553. this._isButtonPressed = false;
  19554. this._doubleClickOccured = false;
  19555. 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
  19556. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19557. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19558. this._startingPointerTime = 0;
  19559. this._previousStartingPointerTime = 0;
  19560. // Fog
  19561. /**
  19562. * is fog enabled on this scene.
  19563. * @type {boolean}
  19564. */
  19565. this.fogEnabled = true;
  19566. this.fogMode = Scene.FOGMODE_NONE;
  19567. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19568. this.fogDensity = 0.1;
  19569. this.fogStart = 0;
  19570. this.fogEnd = 1000.0;
  19571. // Lights
  19572. /**
  19573. * is shadow enabled on this scene.
  19574. * @type {boolean}
  19575. */
  19576. this.shadowsEnabled = true;
  19577. /**
  19578. * is light enabled on this scene.
  19579. * @type {boolean}
  19580. */
  19581. this.lightsEnabled = true;
  19582. /**
  19583. * All of the lights added to this scene.
  19584. * @see BABYLON.Light
  19585. * @type {BABYLON.Light[]}
  19586. */
  19587. this.lights = new Array();
  19588. // Cameras
  19589. /**
  19590. * All of the cameras added to this scene.
  19591. * @see BABYLON.Camera
  19592. * @type {BABYLON.Camera[]}
  19593. */
  19594. this.cameras = new Array();
  19595. this.activeCameras = new Array();
  19596. // Meshes
  19597. /**
  19598. * All of the (abstract) meshes added to this scene.
  19599. * @see BABYLON.AbstractMesh
  19600. * @type {BABYLON.AbstractMesh[]}
  19601. */
  19602. this.meshes = new Array();
  19603. // Geometries
  19604. this._geometries = new Array();
  19605. this.materials = new Array();
  19606. this.multiMaterials = new Array();
  19607. // Textures
  19608. this.texturesEnabled = true;
  19609. this.textures = new Array();
  19610. // Particles
  19611. this.particlesEnabled = true;
  19612. this.particleSystems = new Array();
  19613. // Sprites
  19614. this.spritesEnabled = true;
  19615. this.spriteManagers = new Array();
  19616. // Layers
  19617. this.layers = new Array();
  19618. this.highlightLayers = new Array();
  19619. // Skeletons
  19620. this.skeletonsEnabled = true;
  19621. this.skeletons = new Array();
  19622. // Lens flares
  19623. this.lensFlaresEnabled = true;
  19624. this.lensFlareSystems = new Array();
  19625. // Collisions
  19626. this.collisionsEnabled = true;
  19627. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19628. // Postprocesses
  19629. this.postProcessesEnabled = true;
  19630. // Customs render targets
  19631. this.renderTargetsEnabled = true;
  19632. this.dumpNextRenderTargets = false;
  19633. this.customRenderTargets = new Array();
  19634. // Imported meshes
  19635. this.importedMeshesFiles = new Array();
  19636. // Probes
  19637. this.probesEnabled = true;
  19638. this.reflectionProbes = new Array();
  19639. this._actionManagers = new Array();
  19640. this._meshesForIntersections = new BABYLON.SmartArray(256);
  19641. // Procedural textures
  19642. this.proceduralTexturesEnabled = true;
  19643. this._proceduralTextures = new Array();
  19644. this.soundTracks = new Array();
  19645. this._audioEnabled = true;
  19646. this._headphone = false;
  19647. // Performance counters
  19648. this._totalMeshesCounter = new BABYLON.PerfCounter();
  19649. this._totalLightsCounter = new BABYLON.PerfCounter();
  19650. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  19651. this._totalTexturesCounter = new BABYLON.PerfCounter();
  19652. this._totalVertices = new BABYLON.PerfCounter();
  19653. this._activeIndices = new BABYLON.PerfCounter();
  19654. this._activeParticles = new BABYLON.PerfCounter();
  19655. this._lastFrameDuration = new BABYLON.PerfCounter();
  19656. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  19657. this._renderTargetsDuration = new BABYLON.PerfCounter();
  19658. this._particlesDuration = new BABYLON.PerfCounter();
  19659. this._renderDuration = new BABYLON.PerfCounter();
  19660. this._spritesDuration = new BABYLON.PerfCounter();
  19661. this._activeBones = new BABYLON.PerfCounter();
  19662. this._animationTime = 0;
  19663. this.animationTimeScale = 1;
  19664. this._renderId = 0;
  19665. this._executeWhenReadyTimeoutId = -1;
  19666. this._intermediateRendering = false;
  19667. this._toBeDisposed = new BABYLON.SmartArray(256);
  19668. this._pendingData = []; //ANY
  19669. this._activeMeshes = new BABYLON.SmartArray(256);
  19670. this._processedMaterials = new BABYLON.SmartArray(256);
  19671. this._renderTargets = new BABYLON.SmartArray(256);
  19672. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19673. this._activeSkeletons = new BABYLON.SmartArray(32);
  19674. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  19675. this._activeAnimatables = new Array();
  19676. this._transformMatrix = BABYLON.Matrix.Zero();
  19677. this._edgesRenderers = new BABYLON.SmartArray(16);
  19678. this._uniqueIdCounter = 0;
  19679. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19680. this._engine.scenes.push(this);
  19681. this._externalData = new BABYLON.StringDictionary();
  19682. this._uid = null;
  19683. this._renderingManager = new BABYLON.RenderingManager(this);
  19684. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19685. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19686. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19687. if (BABYLON.OutlineRenderer) {
  19688. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19689. }
  19690. this.attachControl();
  19691. if (BABYLON.SoundTrack) {
  19692. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19693. }
  19694. //simplification queue
  19695. if (BABYLON.SimplificationQueue) {
  19696. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19697. }
  19698. //collision coordinator initialization. For now legacy per default.
  19699. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19700. }
  19701. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19702. get: function () {
  19703. return Scene._FOGMODE_NONE;
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19709. get: function () {
  19710. return Scene._FOGMODE_EXP;
  19711. },
  19712. enumerable: true,
  19713. configurable: true
  19714. });
  19715. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19716. get: function () {
  19717. return Scene._FOGMODE_EXP2;
  19718. },
  19719. enumerable: true,
  19720. configurable: true
  19721. });
  19722. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19723. get: function () {
  19724. return Scene._FOGMODE_LINEAR;
  19725. },
  19726. enumerable: true,
  19727. configurable: true
  19728. });
  19729. Object.defineProperty(Scene.prototype, "onDispose", {
  19730. set: function (callback) {
  19731. if (this._onDisposeObserver) {
  19732. this.onDisposeObservable.remove(this._onDisposeObserver);
  19733. }
  19734. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19735. },
  19736. enumerable: true,
  19737. configurable: true
  19738. });
  19739. Object.defineProperty(Scene.prototype, "beforeRender", {
  19740. set: function (callback) {
  19741. if (this._onBeforeRenderObserver) {
  19742. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19743. }
  19744. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(Scene.prototype, "afterRender", {
  19750. set: function (callback) {
  19751. if (this._onAfterRenderObserver) {
  19752. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19753. }
  19754. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19755. },
  19756. enumerable: true,
  19757. configurable: true
  19758. });
  19759. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19760. set: function (callback) {
  19761. if (this._onBeforeCameraRenderObserver) {
  19762. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19763. }
  19764. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19765. },
  19766. enumerable: true,
  19767. configurable: true
  19768. });
  19769. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19770. set: function (callback) {
  19771. if (this._onAfterCameraRenderObserver) {
  19772. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19773. }
  19774. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19775. },
  19776. enumerable: true,
  19777. configurable: true
  19778. });
  19779. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19780. get: function () {
  19781. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19787. get: function () {
  19788. if (!this._defaultMaterial) {
  19789. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19790. }
  19791. return this._defaultMaterial;
  19792. },
  19793. enumerable: true,
  19794. configurable: true
  19795. });
  19796. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19797. get: function () {
  19798. return this._frustumPlanes;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(Scene.prototype, "debugLayer", {
  19804. // Properties
  19805. get: function () {
  19806. if (!this._debugLayer) {
  19807. this._debugLayer = new BABYLON.DebugLayer(this);
  19808. }
  19809. return this._debugLayer;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19815. get: function () {
  19816. return this._workerCollisions;
  19817. },
  19818. set: function (enabled) {
  19819. enabled = (enabled && !!Worker);
  19820. this._workerCollisions = enabled;
  19821. if (this.collisionCoordinator) {
  19822. this.collisionCoordinator.destroy();
  19823. }
  19824. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19825. this.collisionCoordinator.init(this);
  19826. },
  19827. enumerable: true,
  19828. configurable: true
  19829. });
  19830. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  19831. get: function () {
  19832. return this._selectionOctree;
  19833. },
  19834. enumerable: true,
  19835. configurable: true
  19836. });
  19837. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19838. /**
  19839. * The mesh that is currently under the pointer.
  19840. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19841. */
  19842. get: function () {
  19843. return this._pointerOverMesh;
  19844. },
  19845. enumerable: true,
  19846. configurable: true
  19847. });
  19848. Object.defineProperty(Scene.prototype, "pointerX", {
  19849. /**
  19850. * Current on-screen X position of the pointer
  19851. * @return {number} X position of the pointer
  19852. */
  19853. get: function () {
  19854. return this._pointerX;
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(Scene.prototype, "pointerY", {
  19860. /**
  19861. * Current on-screen Y position of the pointer
  19862. * @return {number} Y position of the pointer
  19863. */
  19864. get: function () {
  19865. return this._pointerY;
  19866. },
  19867. enumerable: true,
  19868. configurable: true
  19869. });
  19870. Scene.prototype.getCachedMaterial = function () {
  19871. return this._cachedMaterial;
  19872. };
  19873. Scene.prototype.getBoundingBoxRenderer = function () {
  19874. return this._boundingBoxRenderer;
  19875. };
  19876. Scene.prototype.getOutlineRenderer = function () {
  19877. return this._outlineRenderer;
  19878. };
  19879. Scene.prototype.getEngine = function () {
  19880. return this._engine;
  19881. };
  19882. Scene.prototype.getTotalVertices = function () {
  19883. return this._totalVertices.current;
  19884. };
  19885. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19886. get: function () {
  19887. return this._totalVertices;
  19888. },
  19889. enumerable: true,
  19890. configurable: true
  19891. });
  19892. Scene.prototype.getActiveIndices = function () {
  19893. return this._activeIndices.current;
  19894. };
  19895. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19896. get: function () {
  19897. return this._activeIndices;
  19898. },
  19899. enumerable: true,
  19900. configurable: true
  19901. });
  19902. Scene.prototype.getActiveParticles = function () {
  19903. return this._activeParticles.current;
  19904. };
  19905. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19906. get: function () {
  19907. return this._activeParticles;
  19908. },
  19909. enumerable: true,
  19910. configurable: true
  19911. });
  19912. Scene.prototype.getActiveBones = function () {
  19913. return this._activeBones.current;
  19914. };
  19915. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19916. get: function () {
  19917. return this._activeBones;
  19918. },
  19919. enumerable: true,
  19920. configurable: true
  19921. });
  19922. // Stats
  19923. Scene.prototype.getLastFrameDuration = function () {
  19924. return this._lastFrameDuration.current;
  19925. };
  19926. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  19927. get: function () {
  19928. return this._lastFrameDuration;
  19929. },
  19930. enumerable: true,
  19931. configurable: true
  19932. });
  19933. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  19934. return this._evaluateActiveMeshesDuration.current;
  19935. };
  19936. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  19937. get: function () {
  19938. return this._evaluateActiveMeshesDuration;
  19939. },
  19940. enumerable: true,
  19941. configurable: true
  19942. });
  19943. Scene.prototype.getActiveMeshes = function () {
  19944. return this._activeMeshes;
  19945. };
  19946. Scene.prototype.getRenderTargetsDuration = function () {
  19947. return this._renderTargetsDuration.current;
  19948. };
  19949. Scene.prototype.getRenderDuration = function () {
  19950. return this._renderDuration.current;
  19951. };
  19952. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  19953. get: function () {
  19954. return this._renderDuration;
  19955. },
  19956. enumerable: true,
  19957. configurable: true
  19958. });
  19959. Scene.prototype.getParticlesDuration = function () {
  19960. return this._particlesDuration.current;
  19961. };
  19962. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  19963. get: function () {
  19964. return this._particlesDuration;
  19965. },
  19966. enumerable: true,
  19967. configurable: true
  19968. });
  19969. Scene.prototype.getSpritesDuration = function () {
  19970. return this._spritesDuration.current;
  19971. };
  19972. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  19973. get: function () {
  19974. return this._spritesDuration;
  19975. },
  19976. enumerable: true,
  19977. configurable: true
  19978. });
  19979. Scene.prototype.getAnimationRatio = function () {
  19980. return this._animationRatio;
  19981. };
  19982. Scene.prototype.getRenderId = function () {
  19983. return this._renderId;
  19984. };
  19985. Scene.prototype.incrementRenderId = function () {
  19986. this._renderId++;
  19987. };
  19988. Scene.prototype._updatePointerPosition = function (evt) {
  19989. var canvasRect = this._engine.getRenderingCanvasClientRect();
  19990. this._pointerX = evt.clientX - canvasRect.left;
  19991. this._pointerY = evt.clientY - canvasRect.top;
  19992. this._unTranslatedPointerX = this._pointerX;
  19993. this._unTranslatedPointerY = this._pointerY;
  19994. if (this.cameraToUseForPointers) {
  19995. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  19996. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  19997. }
  19998. };
  19999. // Pointers handling
  20000. /**
  20001. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20002. * @param attachUp defines if you want to attach events to pointerup
  20003. * @param attachDown defines if you want to attach events to pointerdown
  20004. * @param attachMove defines if you want to attach events to pointermove
  20005. */
  20006. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20007. var _this = this;
  20008. if (attachUp === void 0) { attachUp = true; }
  20009. if (attachDown === void 0) { attachDown = true; }
  20010. if (attachMove === void 0) { attachMove = true; }
  20011. this._initActionManager = function (act, clickInfo) {
  20012. if (!_this._meshPickProceed) {
  20013. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20014. _this._currentPickResult = pickResult;
  20015. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20016. _this._meshPickProceed = true;
  20017. }
  20018. return act;
  20019. };
  20020. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20021. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20022. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20023. btn !== _this._previousButtonPressed) {
  20024. _this._doubleClickOccured = false;
  20025. clickInfo.singleClick = true;
  20026. clickInfo.ignore = false;
  20027. cb(clickInfo, _this._currentPickResult);
  20028. }
  20029. };
  20030. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20031. var clickInfo = new ClickInfo();
  20032. _this._currentPickResult = null;
  20033. var act;
  20034. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  20035. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  20036. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20037. if (!checkPicking && BABYLON.ActionManager.HasPickTriggers) {
  20038. act = _this._initActionManager(act, clickInfo);
  20039. if (act)
  20040. checkPicking = act.hasPickTriggers;
  20041. }
  20042. if (checkPicking) {
  20043. var btn = evt.button;
  20044. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20045. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20046. if (!clickInfo.hasSwiped) {
  20047. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20048. if (!checkSingleClickImmediately) {
  20049. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  20050. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20051. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20052. act = _this._initActionManager(act, clickInfo);
  20053. if (act)
  20054. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20055. }
  20056. }
  20057. if (checkSingleClickImmediately) {
  20058. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20059. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20060. btn !== _this._previousButtonPressed) {
  20061. clickInfo.singleClick = true;
  20062. cb(clickInfo, _this._currentPickResult);
  20063. }
  20064. }
  20065. else {
  20066. // wait that no double click has been raised during the double click delay
  20067. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20068. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20069. }
  20070. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  20071. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20072. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20073. act = _this._initActionManager(act, clickInfo);
  20074. if (act)
  20075. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20076. }
  20077. if (checkDoubleClick) {
  20078. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20079. if (btn === _this._previousButtonPressed &&
  20080. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20081. !_this._doubleClickOccured) {
  20082. // pointer has not moved for 2 clicks, it's a double click
  20083. if (!clickInfo.hasSwiped &&
  20084. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20085. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20086. _this._previousStartingPointerTime = 0;
  20087. _this._doubleClickOccured = true;
  20088. clickInfo.doubleClick = true;
  20089. clickInfo.ignore = false;
  20090. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  20091. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20092. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20093. cb(clickInfo, _this._currentPickResult);
  20094. }
  20095. else {
  20096. _this._doubleClickOccured = false;
  20097. _this._previousStartingPointerTime = _this._startingPointerTime;
  20098. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20099. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20100. _this._previousButtonPressed = btn;
  20101. _this._previousHasSwiped = clickInfo.hasSwiped;
  20102. if (Scene.ExclusiveDoubleClickMode) {
  20103. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  20104. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20105. }
  20106. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20107. cb(clickInfo, _this._previousPickResult);
  20108. }
  20109. else {
  20110. cb(clickInfo, _this._currentPickResult);
  20111. }
  20112. }
  20113. }
  20114. else {
  20115. _this._doubleClickOccured = false;
  20116. _this._previousStartingPointerTime = _this._startingPointerTime;
  20117. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20118. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20119. _this._previousButtonPressed = btn;
  20120. _this._previousHasSwiped = clickInfo.hasSwiped;
  20121. }
  20122. }
  20123. }
  20124. }
  20125. clickInfo.ignore = true;
  20126. cb(clickInfo, _this._currentPickResult);
  20127. };
  20128. var spritePredicate = function (sprite) {
  20129. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20130. };
  20131. this._onPointerMove = function (evt) {
  20132. _this._updatePointerPosition(evt);
  20133. // PreObservable support
  20134. if (_this.onPrePointerObservable.hasObservers()) {
  20135. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20136. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20137. _this.onPrePointerObservable.notifyObservers(pi, type);
  20138. if (pi.skipOnPointerObservable) {
  20139. return;
  20140. }
  20141. }
  20142. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20143. return;
  20144. }
  20145. var canvas = _this._engine.getRenderingCanvas();
  20146. if (!_this.pointerMovePredicate) {
  20147. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20148. }
  20149. // Meshes
  20150. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20151. if (pickResult.hit && pickResult.pickedMesh) {
  20152. _this.setPointerOverSprite(null);
  20153. _this.setPointerOverMesh(pickResult.pickedMesh);
  20154. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20155. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  20156. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  20157. }
  20158. else {
  20159. canvas.style.cursor = _this.hoverCursor;
  20160. }
  20161. }
  20162. else {
  20163. canvas.style.cursor = "";
  20164. }
  20165. }
  20166. else {
  20167. _this.setPointerOverMesh(null);
  20168. // Sprites
  20169. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20170. if (pickResult.hit && pickResult.pickedSprite) {
  20171. _this.setPointerOverSprite(pickResult.pickedSprite);
  20172. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  20173. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  20174. }
  20175. else {
  20176. canvas.style.cursor = _this.hoverCursor;
  20177. }
  20178. }
  20179. else {
  20180. _this.setPointerOverSprite(null);
  20181. // Restore pointer
  20182. canvas.style.cursor = "";
  20183. }
  20184. }
  20185. if (_this.onPointerMove) {
  20186. _this.onPointerMove(evt, pickResult);
  20187. }
  20188. if (_this.onPointerObservable.hasObservers()) {
  20189. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20190. var pi = new PointerInfo(type, evt, pickResult);
  20191. _this.onPointerObservable.notifyObservers(pi, type);
  20192. }
  20193. };
  20194. this._onPointerDown = function (evt) {
  20195. _this._isButtonPressed = true;
  20196. _this._pickedDownMesh = null;
  20197. _this._meshPickProceed = false;
  20198. _this._updatePointerPosition(evt);
  20199. // PreObservable support
  20200. if (_this.onPrePointerObservable.hasObservers()) {
  20201. var type = PointerEventTypes.POINTERDOWN;
  20202. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20203. _this.onPrePointerObservable.notifyObservers(pi, type);
  20204. if (pi.skipOnPointerObservable) {
  20205. return;
  20206. }
  20207. }
  20208. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20209. return;
  20210. }
  20211. _this._startingPointerPosition.x = _this._pointerX;
  20212. _this._startingPointerPosition.y = _this._pointerY;
  20213. _this._startingPointerTime = new Date().getTime();
  20214. if (!_this.pointerDownPredicate) {
  20215. _this.pointerDownPredicate = function (mesh) {
  20216. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20217. };
  20218. }
  20219. // Meshes
  20220. _this._pickedDownMesh = null;
  20221. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20222. if (pickResult.hit && pickResult.pickedMesh) {
  20223. _this._pickedDownMesh = pickResult.pickedMesh;
  20224. var actionManager = pickResult.pickedMesh.actionManager;
  20225. if (actionManager) {
  20226. if (actionManager.hasPickTriggers) {
  20227. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20228. switch (evt.button) {
  20229. case 0:
  20230. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20231. break;
  20232. case 1:
  20233. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20234. break;
  20235. case 2:
  20236. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20237. break;
  20238. }
  20239. }
  20240. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20241. window.setTimeout((function () {
  20242. var _this = this;
  20243. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh; }, false, this.cameraToUseForPointers);
  20244. if (pickResult.hit && pickResult.pickedMesh) {
  20245. if (this._isButtonPressed &&
  20246. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  20247. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  20248. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  20249. this._startingPointerTime = 0;
  20250. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20251. }
  20252. }
  20253. }).bind(_this), Scene.LongPressDelay);
  20254. }
  20255. }
  20256. }
  20257. if (_this.onPointerDown) {
  20258. _this.onPointerDown(evt, pickResult);
  20259. }
  20260. if (_this.onPointerObservable.hasObservers()) {
  20261. var type = PointerEventTypes.POINTERDOWN;
  20262. var pi = new PointerInfo(type, evt, pickResult);
  20263. _this.onPointerObservable.notifyObservers(pi, type);
  20264. }
  20265. // Sprites
  20266. _this._pickedDownSprite = null;
  20267. if (_this.spriteManagers.length > 0) {
  20268. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20269. if (pickResult.hit && pickResult.pickedSprite) {
  20270. if (pickResult.pickedSprite.actionManager) {
  20271. _this._pickedDownSprite = pickResult.pickedSprite;
  20272. switch (evt.button) {
  20273. case 0:
  20274. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20275. break;
  20276. case 1:
  20277. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20278. break;
  20279. case 2:
  20280. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20281. break;
  20282. }
  20283. if (pickResult.pickedSprite.actionManager) {
  20284. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20285. }
  20286. }
  20287. }
  20288. }
  20289. };
  20290. this._onPointerUp = function (evt) {
  20291. _this._isButtonPressed = false;
  20292. _this._pickedUpMesh = null;
  20293. _this._meshPickProceed = false;
  20294. _this._updatePointerPosition(evt);
  20295. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  20296. // PreObservable support
  20297. if (this.onPrePointerObservable.hasObservers()) {
  20298. if (!clickInfo.ignore) {
  20299. if (!clickInfo.hasSwiped) {
  20300. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20301. var type = PointerEventTypes.POINTERTAP;
  20302. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20303. this.onPrePointerObservable.notifyObservers(pi, type);
  20304. if (pi.skipOnPointerObservable) {
  20305. return;
  20306. }
  20307. }
  20308. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20309. var type = PointerEventTypes.POINTERDOUBLETAP;
  20310. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20311. this.onPrePointerObservable.notifyObservers(pi, type);
  20312. if (pi.skipOnPointerObservable) {
  20313. return;
  20314. }
  20315. }
  20316. }
  20317. }
  20318. else {
  20319. var type = PointerEventTypes.POINTERUP;
  20320. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20321. this.onPrePointerObservable.notifyObservers(pi, type);
  20322. if (pi.skipOnPointerObservable) {
  20323. return;
  20324. }
  20325. }
  20326. }
  20327. if (!this.cameraToUseForPointers && !this.activeCamera) {
  20328. return;
  20329. }
  20330. if (!this.pointerUpPredicate) {
  20331. this.pointerUpPredicate = function (mesh) {
  20332. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20333. };
  20334. }
  20335. // Meshes
  20336. if (!this._meshPickProceed && BABYLON.ActionManager.HasTriggers) {
  20337. this._initActionManager(null, clickInfo);
  20338. }
  20339. if (!pickResult) {
  20340. pickResult = this._currentPickResult;
  20341. }
  20342. if (pickResult && pickResult.pickedMesh) {
  20343. this._pickedUpMesh = pickResult.pickedMesh;
  20344. if (this._pickedDownMesh === this._pickedUpMesh) {
  20345. if (this.onPointerPick) {
  20346. this.onPointerPick(evt, pickResult);
  20347. }
  20348. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20349. var type = PointerEventTypes.POINTERPICK;
  20350. var pi = new PointerInfo(type, evt, pickResult);
  20351. this.onPointerObservable.notifyObservers(pi, type);
  20352. }
  20353. }
  20354. if (pickResult.pickedMesh.actionManager) {
  20355. if (clickInfo.ignore) {
  20356. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20357. }
  20358. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20359. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20360. }
  20361. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20362. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20363. }
  20364. }
  20365. }
  20366. if (this._pickedDownMesh &&
  20367. this._pickedDownMesh.actionManager &&
  20368. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20369. this._pickedDownMesh !== this._pickedUpMesh) {
  20370. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20371. }
  20372. if (this.onPointerUp) {
  20373. this.onPointerUp(evt, pickResult);
  20374. }
  20375. if (this.onPointerObservable.hasObservers()) {
  20376. if (!clickInfo.ignore) {
  20377. if (!clickInfo.hasSwiped) {
  20378. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20379. var type = PointerEventTypes.POINTERTAP;
  20380. var pi = new PointerInfo(type, evt, pickResult);
  20381. this.onPointerObservable.notifyObservers(pi, type);
  20382. }
  20383. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20384. var type = PointerEventTypes.POINTERDOUBLETAP;
  20385. var pi = new PointerInfo(type, evt, pickResult);
  20386. this.onPointerObservable.notifyObservers(pi, type);
  20387. }
  20388. }
  20389. }
  20390. else {
  20391. var type = PointerEventTypes.POINTERUP;
  20392. var pi = new PointerInfo(type, evt, pickResult);
  20393. this.onPointerObservable.notifyObservers(pi, type);
  20394. }
  20395. }
  20396. // Sprites
  20397. if (this.spriteManagers.length > 0) {
  20398. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  20399. if (pickResult.hit && pickResult.pickedSprite) {
  20400. if (pickResult.pickedSprite.actionManager) {
  20401. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20402. if (pickResult.pickedSprite.actionManager) {
  20403. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  20404. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20405. }
  20406. }
  20407. }
  20408. }
  20409. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  20410. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  20411. }
  20412. }
  20413. this._previousPickResult = this._currentPickResult;
  20414. }).bind(_this));
  20415. };
  20416. this._onKeyDown = function (evt) {
  20417. if (_this.actionManager) {
  20418. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20419. }
  20420. };
  20421. this._onKeyUp = function (evt) {
  20422. if (_this.actionManager) {
  20423. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20424. }
  20425. };
  20426. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20427. var canvas = this._engine.getRenderingCanvas();
  20428. if (attachMove) {
  20429. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20430. // Wheel
  20431. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20432. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20433. }
  20434. if (attachDown) {
  20435. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20436. }
  20437. if (attachUp) {
  20438. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20439. }
  20440. canvas.tabIndex = 1;
  20441. canvas.addEventListener("keydown", this._onKeyDown, false);
  20442. canvas.addEventListener("keyup", this._onKeyUp, false);
  20443. };
  20444. Scene.prototype.detachControl = function () {
  20445. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20446. var canvas = this._engine.getRenderingCanvas();
  20447. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20448. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20449. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20450. // Wheel
  20451. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20452. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20453. canvas.removeEventListener("keydown", this._onKeyDown);
  20454. canvas.removeEventListener("keyup", this._onKeyUp);
  20455. };
  20456. // Ready
  20457. Scene.prototype.isReady = function () {
  20458. if (this._pendingData.length > 0) {
  20459. return false;
  20460. }
  20461. var index;
  20462. for (index = 0; index < this._geometries.length; index++) {
  20463. var geometry = this._geometries[index];
  20464. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20465. return false;
  20466. }
  20467. }
  20468. for (index = 0; index < this.meshes.length; index++) {
  20469. var mesh = this.meshes[index];
  20470. if (!mesh.isEnabled()) {
  20471. continue;
  20472. }
  20473. if (!mesh.isReady()) {
  20474. return false;
  20475. }
  20476. var mat = mesh.material;
  20477. if (mat) {
  20478. if (!mat.isReady(mesh)) {
  20479. return false;
  20480. }
  20481. }
  20482. }
  20483. return true;
  20484. };
  20485. Scene.prototype.resetCachedMaterial = function () {
  20486. this._cachedMaterial = null;
  20487. };
  20488. Scene.prototype.registerBeforeRender = function (func) {
  20489. this.onBeforeRenderObservable.add(func);
  20490. };
  20491. Scene.prototype.unregisterBeforeRender = function (func) {
  20492. this.onBeforeRenderObservable.removeCallback(func);
  20493. };
  20494. Scene.prototype.registerAfterRender = function (func) {
  20495. this.onAfterRenderObservable.add(func);
  20496. };
  20497. Scene.prototype.unregisterAfterRender = function (func) {
  20498. this.onAfterRenderObservable.removeCallback(func);
  20499. };
  20500. Scene.prototype._addPendingData = function (data) {
  20501. this._pendingData.push(data);
  20502. };
  20503. Scene.prototype._removePendingData = function (data) {
  20504. var index = this._pendingData.indexOf(data);
  20505. if (index !== -1) {
  20506. this._pendingData.splice(index, 1);
  20507. }
  20508. };
  20509. Scene.prototype.getWaitingItemsCount = function () {
  20510. return this._pendingData.length;
  20511. };
  20512. /**
  20513. * Registers a function to be executed when the scene is ready.
  20514. * @param {Function} func - the function to be executed.
  20515. */
  20516. Scene.prototype.executeWhenReady = function (func) {
  20517. var _this = this;
  20518. this.onReadyObservable.add(func);
  20519. if (this._executeWhenReadyTimeoutId !== -1) {
  20520. return;
  20521. }
  20522. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20523. _this._checkIsReady();
  20524. }, 150);
  20525. };
  20526. Scene.prototype._checkIsReady = function () {
  20527. var _this = this;
  20528. if (this.isReady()) {
  20529. this.onReadyObservable.notifyObservers(this);
  20530. this.onReadyObservable.clear();
  20531. this._executeWhenReadyTimeoutId = -1;
  20532. return;
  20533. }
  20534. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20535. _this._checkIsReady();
  20536. }, 150);
  20537. };
  20538. // Animations
  20539. /**
  20540. * Will start the animation sequence of a given target
  20541. * @param target - the target
  20542. * @param {number} from - from which frame should animation start
  20543. * @param {number} to - till which frame should animation run.
  20544. * @param {boolean} [loop] - should the animation loop
  20545. * @param {number} [speedRatio] - the speed in which to run the animation
  20546. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20547. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20548. * @return {BABYLON.Animatable} the animatable object created for this animation
  20549. * @see BABYLON.Animatable
  20550. * @see http://doc.babylonjs.com/page.php?p=22081
  20551. */
  20552. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20553. if (speedRatio === void 0) { speedRatio = 1.0; }
  20554. this.stopAnimation(target);
  20555. if (!animatable) {
  20556. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20557. }
  20558. // Local animations
  20559. if (target.animations) {
  20560. animatable.appendAnimations(target, target.animations);
  20561. }
  20562. // Children animations
  20563. if (target.getAnimatables) {
  20564. var animatables = target.getAnimatables();
  20565. for (var index = 0; index < animatables.length; index++) {
  20566. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20567. }
  20568. }
  20569. animatable.reset();
  20570. return animatable;
  20571. };
  20572. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20573. if (speedRatio === undefined) {
  20574. speedRatio = 1.0;
  20575. }
  20576. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20577. return animatable;
  20578. };
  20579. Scene.prototype.getAnimatableByTarget = function (target) {
  20580. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20581. if (this._activeAnimatables[index].target === target) {
  20582. return this._activeAnimatables[index];
  20583. }
  20584. }
  20585. return null;
  20586. };
  20587. Object.defineProperty(Scene.prototype, "Animatables", {
  20588. get: function () {
  20589. return this._activeAnimatables;
  20590. },
  20591. enumerable: true,
  20592. configurable: true
  20593. });
  20594. /**
  20595. * Will stop the animation of the given target
  20596. * @param target - the target
  20597. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20598. * @see beginAnimation
  20599. */
  20600. Scene.prototype.stopAnimation = function (target, animationName) {
  20601. var animatable = this.getAnimatableByTarget(target);
  20602. if (animatable) {
  20603. animatable.stop(animationName);
  20604. }
  20605. };
  20606. Scene.prototype._animate = function () {
  20607. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20608. return;
  20609. }
  20610. // Getting time
  20611. var now = BABYLON.Tools.Now;
  20612. if (!this._animationTimeLast) {
  20613. if (this._pendingData.length > 0) {
  20614. return;
  20615. }
  20616. this._animationTimeLast = now;
  20617. }
  20618. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  20619. this._animationTime += deltaTime;
  20620. this._animationTimeLast = now;
  20621. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20622. this._activeAnimatables[index]._animate(this._animationTime);
  20623. }
  20624. };
  20625. // Matrix
  20626. Scene.prototype.getViewMatrix = function () {
  20627. return this._viewMatrix;
  20628. };
  20629. Scene.prototype.getProjectionMatrix = function () {
  20630. return this._projectionMatrix;
  20631. };
  20632. Scene.prototype.getTransformMatrix = function () {
  20633. return this._transformMatrix;
  20634. };
  20635. Scene.prototype.setTransformMatrix = function (view, projection) {
  20636. this._viewMatrix = view;
  20637. this._projectionMatrix = projection;
  20638. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20639. // Update frustum
  20640. if (!this._frustumPlanes) {
  20641. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20642. }
  20643. else {
  20644. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20645. }
  20646. };
  20647. // Methods
  20648. Scene.prototype.addMesh = function (newMesh) {
  20649. newMesh.uniqueId = this._uniqueIdCounter++;
  20650. var position = this.meshes.push(newMesh);
  20651. //notify the collision coordinator
  20652. this.collisionCoordinator.onMeshAdded(newMesh);
  20653. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20654. };
  20655. Scene.prototype.removeMesh = function (toRemove) {
  20656. var index = this.meshes.indexOf(toRemove);
  20657. if (index !== -1) {
  20658. // Remove from the scene if mesh found
  20659. this.meshes.splice(index, 1);
  20660. }
  20661. //notify the collision coordinator
  20662. this.collisionCoordinator.onMeshRemoved(toRemove);
  20663. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20664. return index;
  20665. };
  20666. Scene.prototype.removeSkeleton = function (toRemove) {
  20667. var index = this.skeletons.indexOf(toRemove);
  20668. if (index !== -1) {
  20669. // Remove from the scene if mesh found
  20670. this.skeletons.splice(index, 1);
  20671. }
  20672. return index;
  20673. };
  20674. Scene.prototype.removeLight = function (toRemove) {
  20675. var index = this.lights.indexOf(toRemove);
  20676. if (index !== -1) {
  20677. // Remove from the scene if mesh found
  20678. this.lights.splice(index, 1);
  20679. }
  20680. this.onLightRemovedObservable.notifyObservers(toRemove);
  20681. return index;
  20682. };
  20683. Scene.prototype.removeCamera = function (toRemove) {
  20684. var index = this.cameras.indexOf(toRemove);
  20685. if (index !== -1) {
  20686. // Remove from the scene if mesh found
  20687. this.cameras.splice(index, 1);
  20688. }
  20689. // Remove from activeCameras
  20690. var index2 = this.activeCameras.indexOf(toRemove);
  20691. if (index2 !== -1) {
  20692. // Remove from the scene if mesh found
  20693. this.activeCameras.splice(index2, 1);
  20694. }
  20695. // Reset the activeCamera
  20696. if (this.activeCamera === toRemove) {
  20697. if (this.cameras.length > 0) {
  20698. this.activeCamera = this.cameras[0];
  20699. }
  20700. else {
  20701. this.activeCamera = null;
  20702. }
  20703. }
  20704. this.onCameraRemovedObservable.notifyObservers(toRemove);
  20705. return index;
  20706. };
  20707. Scene.prototype.addLight = function (newLight) {
  20708. newLight.uniqueId = this._uniqueIdCounter++;
  20709. var position = this.lights.push(newLight);
  20710. this.onNewLightAddedObservable.notifyObservers(newLight);
  20711. };
  20712. Scene.prototype.addCamera = function (newCamera) {
  20713. newCamera.uniqueId = this._uniqueIdCounter++;
  20714. var position = this.cameras.push(newCamera);
  20715. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  20716. };
  20717. /**
  20718. * Switch active camera
  20719. * @param {Camera} newCamera - new active camera
  20720. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  20721. */
  20722. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  20723. if (attachControl === void 0) { attachControl = true; }
  20724. var canvas = this._engine.getRenderingCanvas();
  20725. this.activeCamera.detachControl(canvas);
  20726. this.activeCamera = newCamera;
  20727. if (attachControl) {
  20728. newCamera.attachControl(canvas);
  20729. }
  20730. };
  20731. /**
  20732. * sets the active camera of the scene using its ID
  20733. * @param {string} id - the camera's ID
  20734. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20735. * @see activeCamera
  20736. */
  20737. Scene.prototype.setActiveCameraByID = function (id) {
  20738. var camera = this.getCameraByID(id);
  20739. if (camera) {
  20740. this.activeCamera = camera;
  20741. return camera;
  20742. }
  20743. return null;
  20744. };
  20745. /**
  20746. * sets the active camera of the scene using its name
  20747. * @param {string} name - the camera's name
  20748. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20749. * @see activeCamera
  20750. */
  20751. Scene.prototype.setActiveCameraByName = function (name) {
  20752. var camera = this.getCameraByName(name);
  20753. if (camera) {
  20754. this.activeCamera = camera;
  20755. return camera;
  20756. }
  20757. return null;
  20758. };
  20759. /**
  20760. * get a material using its id
  20761. * @param {string} the material's ID
  20762. * @return {BABYLON.Material|null} the material or null if none found.
  20763. */
  20764. Scene.prototype.getMaterialByID = function (id) {
  20765. for (var index = 0; index < this.materials.length; index++) {
  20766. if (this.materials[index].id === id) {
  20767. return this.materials[index];
  20768. }
  20769. }
  20770. return null;
  20771. };
  20772. /**
  20773. * get a material using its name
  20774. * @param {string} the material's name
  20775. * @return {BABYLON.Material|null} the material or null if none found.
  20776. */
  20777. Scene.prototype.getMaterialByName = function (name) {
  20778. for (var index = 0; index < this.materials.length; index++) {
  20779. if (this.materials[index].name === name) {
  20780. return this.materials[index];
  20781. }
  20782. }
  20783. return null;
  20784. };
  20785. Scene.prototype.getLensFlareSystemByName = function (name) {
  20786. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20787. if (this.lensFlareSystems[index].name === name) {
  20788. return this.lensFlareSystems[index];
  20789. }
  20790. }
  20791. return null;
  20792. };
  20793. Scene.prototype.getLensFlareSystemByID = function (id) {
  20794. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20795. if (this.lensFlareSystems[index].id === id) {
  20796. return this.lensFlareSystems[index];
  20797. }
  20798. }
  20799. return null;
  20800. };
  20801. Scene.prototype.getCameraByID = function (id) {
  20802. for (var index = 0; index < this.cameras.length; index++) {
  20803. if (this.cameras[index].id === id) {
  20804. return this.cameras[index];
  20805. }
  20806. }
  20807. return null;
  20808. };
  20809. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20810. for (var index = 0; index < this.cameras.length; index++) {
  20811. if (this.cameras[index].uniqueId === uniqueId) {
  20812. return this.cameras[index];
  20813. }
  20814. }
  20815. return null;
  20816. };
  20817. /**
  20818. * get a camera using its name
  20819. * @param {string} the camera's name
  20820. * @return {BABYLON.Camera|null} the camera or null if none found.
  20821. */
  20822. Scene.prototype.getCameraByName = function (name) {
  20823. for (var index = 0; index < this.cameras.length; index++) {
  20824. if (this.cameras[index].name === name) {
  20825. return this.cameras[index];
  20826. }
  20827. }
  20828. return null;
  20829. };
  20830. /**
  20831. * get a bone using its id
  20832. * @param {string} the bone's id
  20833. * @return {BABYLON.Bone|null} the bone or null if not found
  20834. */
  20835. Scene.prototype.getBoneByID = function (id) {
  20836. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20837. var skeleton = this.skeletons[skeletonIndex];
  20838. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20839. if (skeleton.bones[boneIndex].id === id) {
  20840. return skeleton.bones[boneIndex];
  20841. }
  20842. }
  20843. }
  20844. return null;
  20845. };
  20846. /**
  20847. * get a bone using its id
  20848. * @param {string} the bone's name
  20849. * @return {BABYLON.Bone|null} the bone or null if not found
  20850. */
  20851. Scene.prototype.getBoneByName = function (name) {
  20852. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20853. var skeleton = this.skeletons[skeletonIndex];
  20854. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20855. if (skeleton.bones[boneIndex].name === name) {
  20856. return skeleton.bones[boneIndex];
  20857. }
  20858. }
  20859. }
  20860. return null;
  20861. };
  20862. /**
  20863. * get a light node using its name
  20864. * @param {string} the light's name
  20865. * @return {BABYLON.Light|null} the light or null if none found.
  20866. */
  20867. Scene.prototype.getLightByName = function (name) {
  20868. for (var index = 0; index < this.lights.length; index++) {
  20869. if (this.lights[index].name === name) {
  20870. return this.lights[index];
  20871. }
  20872. }
  20873. return null;
  20874. };
  20875. /**
  20876. * get a light node using its ID
  20877. * @param {string} the light's id
  20878. * @return {BABYLON.Light|null} the light or null if none found.
  20879. */
  20880. Scene.prototype.getLightByID = function (id) {
  20881. for (var index = 0; index < this.lights.length; index++) {
  20882. if (this.lights[index].id === id) {
  20883. return this.lights[index];
  20884. }
  20885. }
  20886. return null;
  20887. };
  20888. /**
  20889. * get a light node using its scene-generated unique ID
  20890. * @param {number} the light's unique id
  20891. * @return {BABYLON.Light|null} the light or null if none found.
  20892. */
  20893. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20894. for (var index = 0; index < this.lights.length; index++) {
  20895. if (this.lights[index].uniqueId === uniqueId) {
  20896. return this.lights[index];
  20897. }
  20898. }
  20899. return null;
  20900. };
  20901. /**
  20902. * get a particle system by id
  20903. * @param id {number} the particle system id
  20904. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  20905. */
  20906. Scene.prototype.getParticleSystemByID = function (id) {
  20907. for (var index = 0; index < this.particleSystems.length; index++) {
  20908. if (this.particleSystems[index].id === id) {
  20909. return this.particleSystems[index];
  20910. }
  20911. }
  20912. return null;
  20913. };
  20914. /**
  20915. * get a geometry using its ID
  20916. * @param {string} the geometry's id
  20917. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20918. */
  20919. Scene.prototype.getGeometryByID = function (id) {
  20920. for (var index = 0; index < this._geometries.length; index++) {
  20921. if (this._geometries[index].id === id) {
  20922. return this._geometries[index];
  20923. }
  20924. }
  20925. return null;
  20926. };
  20927. /**
  20928. * add a new geometry to this scene.
  20929. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20930. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20931. * @return {boolean} was the geometry added or not
  20932. */
  20933. Scene.prototype.pushGeometry = function (geometry, force) {
  20934. if (!force && this.getGeometryByID(geometry.id)) {
  20935. return false;
  20936. }
  20937. this._geometries.push(geometry);
  20938. //notify the collision coordinator
  20939. this.collisionCoordinator.onGeometryAdded(geometry);
  20940. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20941. return true;
  20942. };
  20943. /**
  20944. * Removes an existing geometry
  20945. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20946. * @return {boolean} was the geometry removed or not
  20947. */
  20948. Scene.prototype.removeGeometry = function (geometry) {
  20949. var index = this._geometries.indexOf(geometry);
  20950. if (index > -1) {
  20951. this._geometries.splice(index, 1);
  20952. //notify the collision coordinator
  20953. this.collisionCoordinator.onGeometryDeleted(geometry);
  20954. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20955. return true;
  20956. }
  20957. return false;
  20958. };
  20959. Scene.prototype.getGeometries = function () {
  20960. return this._geometries;
  20961. };
  20962. /**
  20963. * Get the first added mesh found of a given ID
  20964. * @param {string} id - the id to search for
  20965. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20966. */
  20967. Scene.prototype.getMeshByID = function (id) {
  20968. for (var index = 0; index < this.meshes.length; index++) {
  20969. if (this.meshes[index].id === id) {
  20970. return this.meshes[index];
  20971. }
  20972. }
  20973. return null;
  20974. };
  20975. Scene.prototype.getMeshesByID = function (id) {
  20976. return this.meshes.filter(function (m) {
  20977. return m.id === id;
  20978. });
  20979. };
  20980. /**
  20981. * Get a mesh with its auto-generated unique id
  20982. * @param {number} uniqueId - the unique id to search for
  20983. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20984. */
  20985. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20986. for (var index = 0; index < this.meshes.length; index++) {
  20987. if (this.meshes[index].uniqueId === uniqueId) {
  20988. return this.meshes[index];
  20989. }
  20990. }
  20991. return null;
  20992. };
  20993. /**
  20994. * Get a the last added mesh found of a given ID
  20995. * @param {string} id - the id to search for
  20996. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20997. */
  20998. Scene.prototype.getLastMeshByID = function (id) {
  20999. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21000. if (this.meshes[index].id === id) {
  21001. return this.meshes[index];
  21002. }
  21003. }
  21004. return null;
  21005. };
  21006. /**
  21007. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21008. * @param {string} id - the id to search for
  21009. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21010. */
  21011. Scene.prototype.getLastEntryByID = function (id) {
  21012. var index;
  21013. for (index = this.meshes.length - 1; index >= 0; index--) {
  21014. if (this.meshes[index].id === id) {
  21015. return this.meshes[index];
  21016. }
  21017. }
  21018. for (index = this.cameras.length - 1; index >= 0; index--) {
  21019. if (this.cameras[index].id === id) {
  21020. return this.cameras[index];
  21021. }
  21022. }
  21023. for (index = this.lights.length - 1; index >= 0; index--) {
  21024. if (this.lights[index].id === id) {
  21025. return this.lights[index];
  21026. }
  21027. }
  21028. return null;
  21029. };
  21030. Scene.prototype.getNodeByID = function (id) {
  21031. var mesh = this.getMeshByID(id);
  21032. if (mesh) {
  21033. return mesh;
  21034. }
  21035. var light = this.getLightByID(id);
  21036. if (light) {
  21037. return light;
  21038. }
  21039. var camera = this.getCameraByID(id);
  21040. if (camera) {
  21041. return camera;
  21042. }
  21043. var bone = this.getBoneByID(id);
  21044. return bone;
  21045. };
  21046. Scene.prototype.getNodeByName = function (name) {
  21047. var mesh = this.getMeshByName(name);
  21048. if (mesh) {
  21049. return mesh;
  21050. }
  21051. var light = this.getLightByName(name);
  21052. if (light) {
  21053. return light;
  21054. }
  21055. var camera = this.getCameraByName(name);
  21056. if (camera) {
  21057. return camera;
  21058. }
  21059. var bone = this.getBoneByName(name);
  21060. return bone;
  21061. };
  21062. Scene.prototype.getMeshByName = function (name) {
  21063. for (var index = 0; index < this.meshes.length; index++) {
  21064. if (this.meshes[index].name === name) {
  21065. return this.meshes[index];
  21066. }
  21067. }
  21068. return null;
  21069. };
  21070. Scene.prototype.getSoundByName = function (name) {
  21071. var index;
  21072. if (BABYLON.AudioEngine) {
  21073. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21074. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21075. return this.mainSoundTrack.soundCollection[index];
  21076. }
  21077. }
  21078. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21079. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21080. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21081. return this.soundTracks[sdIndex].soundCollection[index];
  21082. }
  21083. }
  21084. }
  21085. }
  21086. return null;
  21087. };
  21088. Scene.prototype.getLastSkeletonByID = function (id) {
  21089. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21090. if (this.skeletons[index].id === id) {
  21091. return this.skeletons[index];
  21092. }
  21093. }
  21094. return null;
  21095. };
  21096. Scene.prototype.getSkeletonById = function (id) {
  21097. for (var index = 0; index < this.skeletons.length; index++) {
  21098. if (this.skeletons[index].id === id) {
  21099. return this.skeletons[index];
  21100. }
  21101. }
  21102. return null;
  21103. };
  21104. Scene.prototype.getSkeletonByName = function (name) {
  21105. for (var index = 0; index < this.skeletons.length; index++) {
  21106. if (this.skeletons[index].name === name) {
  21107. return this.skeletons[index];
  21108. }
  21109. }
  21110. return null;
  21111. };
  21112. Scene.prototype.isActiveMesh = function (mesh) {
  21113. return (this._activeMeshes.indexOf(mesh) !== -1);
  21114. };
  21115. /**
  21116. * Return a the first highlight layer of the scene with a given name.
  21117. * @param name The name of the highlight layer to look for.
  21118. * @return The highlight layer if found otherwise null.
  21119. */
  21120. Scene.prototype.getHighlightLayerByName = function (name) {
  21121. for (var index = 0; index < this.highlightLayers.length; index++) {
  21122. if (this.highlightLayers[index].name === name) {
  21123. return this.highlightLayers[index];
  21124. }
  21125. }
  21126. return null;
  21127. };
  21128. Object.defineProperty(Scene.prototype, "uid", {
  21129. /**
  21130. * Return a unique id as a string which can serve as an identifier for the scene
  21131. */
  21132. get: function () {
  21133. if (!this._uid) {
  21134. this._uid = BABYLON.Tools.RandomId();
  21135. }
  21136. return this._uid;
  21137. },
  21138. enumerable: true,
  21139. configurable: true
  21140. });
  21141. /**
  21142. * Add an externaly attached data from its key.
  21143. * This method call will fail and return false, if such key already exists.
  21144. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21145. * @param key the unique key that identifies the data
  21146. * @param data the data object to associate to the key for this Engine instance
  21147. * @return true if no such key were already present and the data was added successfully, false otherwise
  21148. */
  21149. Scene.prototype.addExternalData = function (key, data) {
  21150. return this._externalData.add(key, data);
  21151. };
  21152. /**
  21153. * Get an externaly attached data from its key
  21154. * @param key the unique key that identifies the data
  21155. * @return the associated data, if present (can be null), or undefined if not present
  21156. */
  21157. Scene.prototype.getExternalData = function (key) {
  21158. return this._externalData.get(key);
  21159. };
  21160. /**
  21161. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21162. * @param key the unique key that identifies the data
  21163. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21164. * @return the associated data, can be null if the factory returned null.
  21165. */
  21166. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21167. return this._externalData.getOrAddWithFactory(key, factory);
  21168. };
  21169. /**
  21170. * Remove an externaly attached data from the Engine instance
  21171. * @param key the unique key that identifies the data
  21172. * @return true if the data was successfully removed, false if it doesn't exist
  21173. */
  21174. Scene.prototype.removeExternalData = function (key) {
  21175. return this._externalData.remove(key);
  21176. };
  21177. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21178. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21179. var material = subMesh.getMaterial();
  21180. if (mesh.showSubMeshesBoundingBox) {
  21181. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  21182. }
  21183. if (material) {
  21184. // Render targets
  21185. if (material.getRenderTargetTextures) {
  21186. if (this._processedMaterials.indexOf(material) === -1) {
  21187. this._processedMaterials.push(material);
  21188. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21189. }
  21190. }
  21191. // Dispatch
  21192. this._activeIndices.addCount(subMesh.indexCount, false);
  21193. this._renderingManager.dispatch(subMesh);
  21194. }
  21195. }
  21196. };
  21197. Scene.prototype._isInIntermediateRendering = function () {
  21198. return this._intermediateRendering;
  21199. };
  21200. Scene.prototype._evaluateActiveMeshes = function () {
  21201. this.activeCamera._activeMeshes.reset();
  21202. this._activeMeshes.reset();
  21203. this._renderingManager.reset();
  21204. this._processedMaterials.reset();
  21205. this._activeParticleSystems.reset();
  21206. this._activeSkeletons.reset();
  21207. this._softwareSkinnedMeshes.reset();
  21208. this._boundingBoxRenderer.reset();
  21209. this._edgesRenderers.reset();
  21210. // Meshes
  21211. var meshes;
  21212. var len;
  21213. if (this._selectionOctree) {
  21214. var selection = this._selectionOctree.select(this._frustumPlanes);
  21215. meshes = selection.data;
  21216. len = selection.length;
  21217. }
  21218. else {
  21219. len = this.meshes.length;
  21220. meshes = this.meshes;
  21221. }
  21222. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  21223. var mesh = meshes[meshIndex];
  21224. if (mesh.isBlocked) {
  21225. continue;
  21226. }
  21227. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21228. if (!mesh.isReady() || !mesh.isEnabled()) {
  21229. continue;
  21230. }
  21231. mesh.computeWorldMatrix();
  21232. // Intersections
  21233. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21234. this._meshesForIntersections.pushNoDuplicate(mesh);
  21235. }
  21236. // Switch to current LOD
  21237. var meshLOD = mesh.getLOD(this.activeCamera);
  21238. if (!meshLOD) {
  21239. continue;
  21240. }
  21241. mesh._preActivate();
  21242. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21243. this._activeMeshes.push(mesh);
  21244. this.activeCamera._activeMeshes.push(mesh);
  21245. mesh._activate(this._renderId);
  21246. this._activeMesh(mesh, meshLOD);
  21247. }
  21248. }
  21249. // Particle systems
  21250. this._particlesDuration.beginMonitoring();
  21251. var beforeParticlesDate = BABYLON.Tools.Now;
  21252. if (this.particlesEnabled) {
  21253. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  21254. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21255. var particleSystem = this.particleSystems[particleIndex];
  21256. if (!particleSystem.isStarted()) {
  21257. continue;
  21258. }
  21259. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  21260. this._activeParticleSystems.push(particleSystem);
  21261. particleSystem.animate();
  21262. this._renderingManager.dispatchParticles(particleSystem);
  21263. }
  21264. }
  21265. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  21266. }
  21267. this._particlesDuration.endMonitoring(false);
  21268. };
  21269. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21270. if (mesh.skeleton && this.skeletonsEnabled) {
  21271. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21272. mesh.skeleton.prepare();
  21273. }
  21274. if (!mesh.computeBonesUsingShaders) {
  21275. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21276. }
  21277. }
  21278. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21279. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  21280. }
  21281. if (sourceMesh._edgesRenderer) {
  21282. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  21283. }
  21284. if (mesh && mesh.subMeshes) {
  21285. // Submeshes Octrees
  21286. var len;
  21287. var subMeshes;
  21288. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  21289. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21290. len = intersections.length;
  21291. subMeshes = intersections.data;
  21292. }
  21293. else {
  21294. subMeshes = mesh.subMeshes;
  21295. len = subMeshes.length;
  21296. }
  21297. for (var subIndex = 0; subIndex < len; subIndex++) {
  21298. var subMesh = subMeshes[subIndex];
  21299. this._evaluateSubMesh(subMesh, mesh);
  21300. }
  21301. }
  21302. };
  21303. Scene.prototype.updateTransformMatrix = function (force) {
  21304. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21305. };
  21306. Scene.prototype._renderForCamera = function (camera) {
  21307. var engine = this._engine;
  21308. var startTime = BABYLON.Tools.Now;
  21309. this.activeCamera = camera;
  21310. if (!this.activeCamera)
  21311. throw new Error("Active camera not set");
  21312. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21313. // Viewport
  21314. engine.setViewport(this.activeCamera.viewport);
  21315. // Camera
  21316. this.resetCachedMaterial();
  21317. this._renderId++;
  21318. this.updateTransformMatrix();
  21319. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21320. // Meshes
  21321. this._evaluateActiveMeshesDuration.beginMonitoring();
  21322. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  21323. this._evaluateActiveMeshes();
  21324. this._evaluateActiveMeshesDuration.endMonitoring(false);
  21325. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  21326. // Software skinning
  21327. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21328. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21329. mesh.applySkeleton(mesh.skeleton);
  21330. }
  21331. // Render targets
  21332. this._renderTargetsDuration.beginMonitoring();
  21333. var needsRestoreFrameBuffer = false;
  21334. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21335. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21336. this._intermediateRendering = true;
  21337. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21338. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21339. var renderTarget = this._renderTargets.data[renderIndex];
  21340. if (renderTarget._shouldRender()) {
  21341. this._renderId++;
  21342. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21343. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21344. }
  21345. }
  21346. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21347. this._intermediateRendering = false;
  21348. this._renderId++;
  21349. needsRestoreFrameBuffer = true; // Restore back buffer
  21350. }
  21351. // Render HighlightLayer Texture
  21352. var stencilState = this._engine.getStencilBuffer();
  21353. var renderhighlights = false;
  21354. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21355. this._intermediateRendering = true;
  21356. for (var i = 0; i < this.highlightLayers.length; i++) {
  21357. var highlightLayer = this.highlightLayers[i];
  21358. if (highlightLayer.shouldRender() &&
  21359. (!highlightLayer.camera ||
  21360. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21361. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21362. renderhighlights = true;
  21363. var renderTarget = highlightLayer._mainTexture;
  21364. if (renderTarget._shouldRender()) {
  21365. this._renderId++;
  21366. renderTarget.render(false, false);
  21367. needsRestoreFrameBuffer = true;
  21368. }
  21369. }
  21370. }
  21371. this._intermediateRendering = false;
  21372. this._renderId++;
  21373. }
  21374. if (needsRestoreFrameBuffer) {
  21375. engine.restoreDefaultFramebuffer();
  21376. }
  21377. this._renderTargetsDuration.endMonitoring(false);
  21378. // Prepare Frame
  21379. this.postProcessManager._prepareFrame();
  21380. this._renderDuration.beginMonitoring();
  21381. // Backgrounds
  21382. var layerIndex;
  21383. var layer;
  21384. if (this.layers.length) {
  21385. engine.setDepthBuffer(false);
  21386. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21387. layer = this.layers[layerIndex];
  21388. if (layer.isBackground) {
  21389. layer.render();
  21390. }
  21391. }
  21392. engine.setDepthBuffer(true);
  21393. }
  21394. // Render
  21395. BABYLON.Tools.StartPerformanceCounter("Main render");
  21396. // Activate HighlightLayer stencil
  21397. if (renderhighlights) {
  21398. this._engine.setStencilBuffer(true);
  21399. }
  21400. this._renderingManager.render(null, null, true, true);
  21401. // Restore HighlightLayer stencil
  21402. if (renderhighlights) {
  21403. this._engine.setStencilBuffer(stencilState);
  21404. }
  21405. BABYLON.Tools.EndPerformanceCounter("Main render");
  21406. // Bounding boxes
  21407. this._boundingBoxRenderer.render();
  21408. // Edges
  21409. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21410. this._edgesRenderers.data[edgesRendererIndex].render();
  21411. }
  21412. // Lens flares
  21413. if (this.lensFlaresEnabled) {
  21414. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21415. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21416. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21417. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21418. lensFlareSystem.render();
  21419. }
  21420. }
  21421. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21422. }
  21423. // Foregrounds
  21424. if (this.layers.length) {
  21425. engine.setDepthBuffer(false);
  21426. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21427. layer = this.layers[layerIndex];
  21428. if (!layer.isBackground) {
  21429. layer.render();
  21430. }
  21431. }
  21432. engine.setDepthBuffer(true);
  21433. }
  21434. // Highlight Layer
  21435. if (renderhighlights) {
  21436. engine.setDepthBuffer(false);
  21437. for (var i = 0; i < this.highlightLayers.length; i++) {
  21438. if (this.highlightLayers[i].shouldRender()) {
  21439. this.highlightLayers[i].render();
  21440. }
  21441. }
  21442. engine.setDepthBuffer(true);
  21443. }
  21444. this._renderDuration.endMonitoring(false);
  21445. // Finalize frame
  21446. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21447. // Update camera
  21448. this.activeCamera._updateFromScene();
  21449. // Reset some special arrays
  21450. this._renderTargets.reset();
  21451. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21452. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21453. };
  21454. Scene.prototype._processSubCameras = function (camera) {
  21455. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21456. this._renderForCamera(camera);
  21457. return;
  21458. }
  21459. // rig cameras
  21460. for (var index = 0; index < camera._rigCameras.length; index++) {
  21461. this._renderForCamera(camera._rigCameras[index]);
  21462. }
  21463. this.activeCamera = camera;
  21464. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21465. // Update camera
  21466. this.activeCamera._updateFromScene();
  21467. };
  21468. Scene.prototype._checkIntersections = function () {
  21469. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  21470. var sourceMesh = this._meshesForIntersections.data[index];
  21471. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  21472. var action = sourceMesh.actionManager.actions[actionIndex];
  21473. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21474. var parameters = action.getTriggerParameter();
  21475. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  21476. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  21477. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  21478. if (areIntersecting && currentIntersectionInProgress === -1) {
  21479. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  21480. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21481. sourceMesh._intersectionsInProgress.push(otherMesh);
  21482. }
  21483. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21484. sourceMesh._intersectionsInProgress.push(otherMesh);
  21485. }
  21486. }
  21487. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  21488. //They intersected, and now they don't.
  21489. //is this trigger an exit trigger? execute an event.
  21490. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21491. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21492. }
  21493. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  21494. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21495. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  21496. }
  21497. }
  21498. }
  21499. }
  21500. }
  21501. };
  21502. Scene.prototype.render = function () {
  21503. this._lastFrameDuration.beginMonitoring();
  21504. this._particlesDuration.fetchNewFrame();
  21505. this._spritesDuration.fetchNewFrame();
  21506. this._activeParticles.fetchNewFrame();
  21507. this._renderDuration.fetchNewFrame();
  21508. this._renderTargetsDuration.fetchNewFrame();
  21509. this._evaluateActiveMeshesDuration.fetchNewFrame();
  21510. this._totalVertices.fetchNewFrame();
  21511. this._activeIndices.fetchNewFrame();
  21512. this._activeBones.fetchNewFrame();
  21513. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  21514. this._meshesForIntersections.reset();
  21515. this.resetCachedMaterial();
  21516. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  21517. // Actions
  21518. if (this.actionManager) {
  21519. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  21520. }
  21521. //Simplification Queue
  21522. if (this.simplificationQueue && !this.simplificationQueue.running) {
  21523. this.simplificationQueue.executeNext();
  21524. }
  21525. // Animations
  21526. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  21527. this._animationRatio = deltaTime * (60.0 / 1000.0);
  21528. this._animate();
  21529. // Physics
  21530. if (this._physicsEngine) {
  21531. BABYLON.Tools.StartPerformanceCounter("Physics");
  21532. this._physicsEngine._step(deltaTime / 1000.0);
  21533. BABYLON.Tools.EndPerformanceCounter("Physics");
  21534. }
  21535. // Before render
  21536. this.onBeforeRenderObservable.notifyObservers(this);
  21537. // Customs render targets
  21538. this._renderTargetsDuration.beginMonitoring();
  21539. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21540. var engine = this.getEngine();
  21541. var currentActiveCamera = this.activeCamera;
  21542. if (this.renderTargetsEnabled) {
  21543. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21544. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  21545. var renderTarget = this.customRenderTargets[customIndex];
  21546. if (renderTarget._shouldRender()) {
  21547. this._renderId++;
  21548. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  21549. if (!this.activeCamera)
  21550. throw new Error("Active camera not set");
  21551. // Viewport
  21552. engine.setViewport(this.activeCamera.viewport);
  21553. // Camera
  21554. this.updateTransformMatrix();
  21555. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  21556. }
  21557. }
  21558. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21559. this._renderId++;
  21560. }
  21561. if (this.customRenderTargets.length > 0) {
  21562. engine.restoreDefaultFramebuffer();
  21563. }
  21564. this._renderTargetsDuration.endMonitoring();
  21565. this.activeCamera = currentActiveCamera;
  21566. // Procedural textures
  21567. if (this.proceduralTexturesEnabled) {
  21568. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21569. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  21570. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  21571. if (proceduralTexture._shouldRender()) {
  21572. proceduralTexture.render();
  21573. }
  21574. }
  21575. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21576. }
  21577. // Clear
  21578. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  21579. // Shadows
  21580. if (this.shadowsEnabled) {
  21581. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  21582. var light = this.lights[lightIndex];
  21583. var shadowGenerator = light.getShadowGenerator();
  21584. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  21585. this._renderTargets.push(shadowGenerator.getShadowMap());
  21586. }
  21587. }
  21588. }
  21589. // Depth renderer
  21590. if (this._depthRenderer) {
  21591. this._renderTargets.push(this._depthRenderer.getDepthMap());
  21592. }
  21593. // RenderPipeline
  21594. this.postProcessRenderPipelineManager.update();
  21595. // Multi-cameras?
  21596. if (this.activeCameras.length > 0) {
  21597. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  21598. if (cameraIndex > 0) {
  21599. this._engine.clear(null, false, true, true);
  21600. }
  21601. this._processSubCameras(this.activeCameras[cameraIndex]);
  21602. }
  21603. }
  21604. else {
  21605. if (!this.activeCamera) {
  21606. throw new Error("No camera defined");
  21607. }
  21608. this._processSubCameras(this.activeCamera);
  21609. }
  21610. // Intersection checks
  21611. this._checkIntersections();
  21612. // Update the audio listener attached to the camera
  21613. if (BABYLON.AudioEngine) {
  21614. this._updateAudioParameters();
  21615. }
  21616. // After render
  21617. if (this.afterRender) {
  21618. this.afterRender();
  21619. }
  21620. this.onAfterRenderObservable.notifyObservers(this);
  21621. // Cleaning
  21622. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21623. this._toBeDisposed.data[index].dispose();
  21624. this._toBeDisposed[index] = null;
  21625. }
  21626. this._toBeDisposed.reset();
  21627. if (this.dumpNextRenderTargets) {
  21628. this.dumpNextRenderTargets = false;
  21629. }
  21630. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  21631. this._lastFrameDuration.endMonitoring();
  21632. this._totalMeshesCounter.addCount(this.meshes.length, true);
  21633. this._totalLightsCounter.addCount(this.lights.length, true);
  21634. this._totalMaterialsCounter.addCount(this.materials.length, true);
  21635. this._totalTexturesCounter.addCount(this.textures.length, true);
  21636. this._activeBones.addCount(0, true);
  21637. this._activeIndices.addCount(0, true);
  21638. this._activeParticles.addCount(0, true);
  21639. };
  21640. Scene.prototype._updateAudioParameters = function () {
  21641. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21642. return;
  21643. }
  21644. var listeningCamera;
  21645. var audioEngine = BABYLON.Engine.audioEngine;
  21646. if (this.activeCameras.length > 0) {
  21647. listeningCamera = this.activeCameras[0];
  21648. }
  21649. else {
  21650. listeningCamera = this.activeCamera;
  21651. }
  21652. if (listeningCamera && audioEngine.canUseWebAudio) {
  21653. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21654. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21655. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21656. cameraDirection.normalize();
  21657. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21658. var i;
  21659. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21660. var sound = this.mainSoundTrack.soundCollection[i];
  21661. if (sound.useCustomAttenuation) {
  21662. sound.updateDistanceFromListener();
  21663. }
  21664. }
  21665. for (i = 0; i < this.soundTracks.length; i++) {
  21666. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21667. sound = this.soundTracks[i].soundCollection[j];
  21668. if (sound.useCustomAttenuation) {
  21669. sound.updateDistanceFromListener();
  21670. }
  21671. }
  21672. }
  21673. }
  21674. };
  21675. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21676. // Audio
  21677. get: function () {
  21678. return this._audioEnabled;
  21679. },
  21680. set: function (value) {
  21681. this._audioEnabled = value;
  21682. if (BABYLON.AudioEngine) {
  21683. if (this._audioEnabled) {
  21684. this._enableAudio();
  21685. }
  21686. else {
  21687. this._disableAudio();
  21688. }
  21689. }
  21690. },
  21691. enumerable: true,
  21692. configurable: true
  21693. });
  21694. Scene.prototype._disableAudio = function () {
  21695. var i;
  21696. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21697. this.mainSoundTrack.soundCollection[i].pause();
  21698. }
  21699. for (i = 0; i < this.soundTracks.length; i++) {
  21700. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21701. this.soundTracks[i].soundCollection[j].pause();
  21702. }
  21703. }
  21704. };
  21705. Scene.prototype._enableAudio = function () {
  21706. var i;
  21707. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21708. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21709. this.mainSoundTrack.soundCollection[i].play();
  21710. }
  21711. }
  21712. for (i = 0; i < this.soundTracks.length; i++) {
  21713. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21714. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21715. this.soundTracks[i].soundCollection[j].play();
  21716. }
  21717. }
  21718. }
  21719. };
  21720. Object.defineProperty(Scene.prototype, "headphone", {
  21721. get: function () {
  21722. return this._headphone;
  21723. },
  21724. set: function (value) {
  21725. this._headphone = value;
  21726. if (BABYLON.AudioEngine) {
  21727. if (this._headphone) {
  21728. this._switchAudioModeForHeadphones();
  21729. }
  21730. else {
  21731. this._switchAudioModeForNormalSpeakers();
  21732. }
  21733. }
  21734. },
  21735. enumerable: true,
  21736. configurable: true
  21737. });
  21738. Scene.prototype._switchAudioModeForHeadphones = function () {
  21739. this.mainSoundTrack.switchPanningModelToHRTF();
  21740. for (var i = 0; i < this.soundTracks.length; i++) {
  21741. this.soundTracks[i].switchPanningModelToHRTF();
  21742. }
  21743. };
  21744. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21745. this.mainSoundTrack.switchPanningModelToEqualPower();
  21746. for (var i = 0; i < this.soundTracks.length; i++) {
  21747. this.soundTracks[i].switchPanningModelToEqualPower();
  21748. }
  21749. };
  21750. Scene.prototype.enableDepthRenderer = function () {
  21751. if (this._depthRenderer) {
  21752. return this._depthRenderer;
  21753. }
  21754. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21755. return this._depthRenderer;
  21756. };
  21757. Scene.prototype.disableDepthRenderer = function () {
  21758. if (!this._depthRenderer) {
  21759. return;
  21760. }
  21761. this._depthRenderer.dispose();
  21762. this._depthRenderer = null;
  21763. };
  21764. Scene.prototype.freezeMaterials = function () {
  21765. for (var i = 0; i < this.materials.length; i++) {
  21766. this.materials[i].freeze();
  21767. }
  21768. };
  21769. Scene.prototype.unfreezeMaterials = function () {
  21770. for (var i = 0; i < this.materials.length; i++) {
  21771. this.materials[i].unfreeze();
  21772. }
  21773. };
  21774. Scene.prototype.dispose = function () {
  21775. this.beforeRender = null;
  21776. this.afterRender = null;
  21777. this.skeletons = [];
  21778. this._boundingBoxRenderer.dispose();
  21779. if (this._depthRenderer) {
  21780. this._depthRenderer.dispose();
  21781. }
  21782. // Smart arrays
  21783. if (this.activeCamera) {
  21784. this.activeCamera._activeMeshes.dispose();
  21785. this.activeCamera = null;
  21786. }
  21787. this._activeMeshes.dispose();
  21788. this._renderingManager.dispose();
  21789. this._processedMaterials.dispose();
  21790. this._activeParticleSystems.dispose();
  21791. this._activeSkeletons.dispose();
  21792. this._softwareSkinnedMeshes.dispose();
  21793. this._boundingBoxRenderer.dispose();
  21794. this._edgesRenderers.dispose();
  21795. this._meshesForIntersections.dispose();
  21796. this._toBeDisposed.dispose();
  21797. // Debug layer
  21798. if (this._debugLayer) {
  21799. this._debugLayer.hide();
  21800. }
  21801. // Events
  21802. this.onDisposeObservable.notifyObservers(this);
  21803. this.onDisposeObservable.clear();
  21804. this.onBeforeRenderObservable.clear();
  21805. this.onAfterRenderObservable.clear();
  21806. this.detachControl();
  21807. // Release sounds & sounds tracks
  21808. if (BABYLON.AudioEngine) {
  21809. this.disposeSounds();
  21810. }
  21811. // Detach cameras
  21812. var canvas = this._engine.getRenderingCanvas();
  21813. var index;
  21814. for (index = 0; index < this.cameras.length; index++) {
  21815. this.cameras[index].detachControl(canvas);
  21816. }
  21817. // Release lights
  21818. while (this.lights.length) {
  21819. this.lights[0].dispose();
  21820. }
  21821. // Release meshes
  21822. while (this.meshes.length) {
  21823. this.meshes[0].dispose(true);
  21824. }
  21825. // Release cameras
  21826. while (this.cameras.length) {
  21827. this.cameras[0].dispose();
  21828. }
  21829. // Release materials
  21830. while (this.materials.length) {
  21831. this.materials[0].dispose();
  21832. }
  21833. // Release particles
  21834. while (this.particleSystems.length) {
  21835. this.particleSystems[0].dispose();
  21836. }
  21837. // Release sprites
  21838. while (this.spriteManagers.length) {
  21839. this.spriteManagers[0].dispose();
  21840. }
  21841. // Release layers
  21842. while (this.layers.length) {
  21843. this.layers[0].dispose();
  21844. }
  21845. while (this.highlightLayers.length) {
  21846. this.highlightLayers[0].dispose();
  21847. }
  21848. // Release textures
  21849. while (this.textures.length) {
  21850. this.textures[0].dispose();
  21851. }
  21852. // Post-processes
  21853. this.postProcessManager.dispose();
  21854. // Physics
  21855. if (this._physicsEngine) {
  21856. this.disablePhysicsEngine();
  21857. }
  21858. // Remove from engine
  21859. index = this._engine.scenes.indexOf(this);
  21860. if (index > -1) {
  21861. this._engine.scenes.splice(index, 1);
  21862. }
  21863. this._engine.wipeCaches();
  21864. };
  21865. // Release sounds & sounds tracks
  21866. Scene.prototype.disposeSounds = function () {
  21867. this.mainSoundTrack.dispose();
  21868. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21869. this.soundTracks[scIndex].dispose();
  21870. }
  21871. };
  21872. // Octrees
  21873. Scene.prototype.getWorldExtends = function () {
  21874. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21875. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21876. for (var index = 0; index < this.meshes.length; index++) {
  21877. var mesh = this.meshes[index];
  21878. mesh.computeWorldMatrix(true);
  21879. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  21880. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  21881. BABYLON.Tools.CheckExtends(minBox, min, max);
  21882. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21883. }
  21884. return {
  21885. min: min,
  21886. max: max
  21887. };
  21888. };
  21889. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21890. if (maxCapacity === void 0) { maxCapacity = 64; }
  21891. if (maxDepth === void 0) { maxDepth = 2; }
  21892. if (!this._selectionOctree) {
  21893. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21894. }
  21895. var worldExtends = this.getWorldExtends();
  21896. // Update octree
  21897. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21898. return this._selectionOctree;
  21899. };
  21900. // Picking
  21901. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21902. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21903. var engine = this._engine;
  21904. if (!camera) {
  21905. if (!this.activeCamera)
  21906. throw new Error("Active camera not set");
  21907. camera = this.activeCamera;
  21908. }
  21909. var cameraViewport = camera.viewport;
  21910. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21911. // Moving coordinates to local viewport world
  21912. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21913. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21914. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21915. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  21916. };
  21917. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21918. var engine = this._engine;
  21919. if (!camera) {
  21920. if (!this.activeCamera)
  21921. throw new Error("Active camera not set");
  21922. camera = this.activeCamera;
  21923. }
  21924. var cameraViewport = camera.viewport;
  21925. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21926. var identity = BABYLON.Matrix.Identity();
  21927. // Moving coordinates to local viewport world
  21928. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21929. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21930. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21931. };
  21932. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21933. var pickingInfo = null;
  21934. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21935. var mesh = this.meshes[meshIndex];
  21936. if (predicate) {
  21937. if (!predicate(mesh)) {
  21938. continue;
  21939. }
  21940. }
  21941. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21942. continue;
  21943. }
  21944. var world = mesh.getWorldMatrix();
  21945. var ray = rayFunction(world);
  21946. var result = mesh.intersects(ray, fastCheck);
  21947. if (!result || !result.hit)
  21948. continue;
  21949. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21950. continue;
  21951. pickingInfo = result;
  21952. if (fastCheck) {
  21953. break;
  21954. }
  21955. }
  21956. return pickingInfo || new BABYLON.PickingInfo();
  21957. };
  21958. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21959. var pickingInfos = new Array();
  21960. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21961. var mesh = this.meshes[meshIndex];
  21962. if (predicate) {
  21963. if (!predicate(mesh)) {
  21964. continue;
  21965. }
  21966. }
  21967. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21968. continue;
  21969. }
  21970. var world = mesh.getWorldMatrix();
  21971. var ray = rayFunction(world);
  21972. var result = mesh.intersects(ray, false);
  21973. if (!result || !result.hit)
  21974. continue;
  21975. pickingInfos.push(result);
  21976. }
  21977. return pickingInfos;
  21978. };
  21979. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21980. var pickingInfo = null;
  21981. camera = camera || this.activeCamera;
  21982. if (this.spriteManagers.length > 0) {
  21983. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21984. var spriteManager = this.spriteManagers[spriteIndex];
  21985. if (!spriteManager.isPickable) {
  21986. continue;
  21987. }
  21988. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21989. if (!result || !result.hit)
  21990. continue;
  21991. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21992. continue;
  21993. pickingInfo = result;
  21994. if (fastCheck) {
  21995. break;
  21996. }
  21997. }
  21998. }
  21999. return pickingInfo || new BABYLON.PickingInfo();
  22000. };
  22001. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22002. /// <param name="x">X position on screen</param>
  22003. /// <param name="y">Y position on screen</param>
  22004. /// <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>
  22005. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22006. /// <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>
  22007. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22008. var _this = this;
  22009. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  22010. };
  22011. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22012. /// <param name="x">X position on screen</param>
  22013. /// <param name="y">Y position on screen</param>
  22014. /// <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>
  22015. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22016. /// <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>
  22017. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22018. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  22019. };
  22020. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22021. var _this = this;
  22022. return this._internalPick(function (world) {
  22023. if (!_this._pickWithRayInverseMatrix) {
  22024. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22025. }
  22026. world.invertToRef(_this._pickWithRayInverseMatrix);
  22027. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22028. }, predicate, fastCheck);
  22029. };
  22030. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22031. /// <param name="x">X position on screen</param>
  22032. /// <param name="y">Y position on screen</param>
  22033. /// <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>
  22034. /// <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>
  22035. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22036. var _this = this;
  22037. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  22038. };
  22039. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22040. /// <param name="ray">Ray to use</param>
  22041. /// <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>
  22042. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22043. var _this = this;
  22044. return this._internalMultiPick(function (world) {
  22045. if (!_this._pickWithRayInverseMatrix) {
  22046. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22047. }
  22048. world.invertToRef(_this._pickWithRayInverseMatrix);
  22049. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22050. }, predicate);
  22051. };
  22052. Scene.prototype.setPointerOverMesh = function (mesh) {
  22053. if (this._pointerOverMesh === mesh) {
  22054. return;
  22055. }
  22056. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22057. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22058. }
  22059. this._pointerOverMesh = mesh;
  22060. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22061. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22062. }
  22063. };
  22064. Scene.prototype.getPointerOverMesh = function () {
  22065. return this._pointerOverMesh;
  22066. };
  22067. Scene.prototype.setPointerOverSprite = function (sprite) {
  22068. if (this._pointerOverSprite === sprite) {
  22069. return;
  22070. }
  22071. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22072. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22073. }
  22074. this._pointerOverSprite = sprite;
  22075. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22076. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22077. }
  22078. };
  22079. Scene.prototype.getPointerOverSprite = function () {
  22080. return this._pointerOverSprite;
  22081. };
  22082. // Physics
  22083. Scene.prototype.getPhysicsEngine = function () {
  22084. return this._physicsEngine;
  22085. };
  22086. /**
  22087. * Enables physics to the current scene
  22088. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22089. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22090. * @return {boolean} was the physics engine initialized
  22091. */
  22092. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22093. if (this._physicsEngine) {
  22094. return true;
  22095. }
  22096. try {
  22097. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22098. return true;
  22099. }
  22100. catch (e) {
  22101. BABYLON.Tools.Error(e.message);
  22102. return false;
  22103. }
  22104. };
  22105. Scene.prototype.disablePhysicsEngine = function () {
  22106. if (!this._physicsEngine) {
  22107. return;
  22108. }
  22109. this._physicsEngine.dispose();
  22110. this._physicsEngine = undefined;
  22111. };
  22112. Scene.prototype.isPhysicsEnabled = function () {
  22113. return this._physicsEngine !== undefined;
  22114. };
  22115. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22116. var mesh = compound.parts[0].mesh;
  22117. mesh.physicsImpostor.dispose();
  22118. mesh.physicsImpostor = null;
  22119. };
  22120. // Misc.
  22121. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  22122. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22123. // Light
  22124. if (this.lights.length === 0) {
  22125. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22126. }
  22127. // Camera
  22128. if (!this.activeCamera) {
  22129. // Compute position
  22130. var worldExtends = this.getWorldExtends();
  22131. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  22132. var camera;
  22133. if (createArcRotateCamera) {
  22134. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  22135. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  22136. camera.setTarget(worldCenter);
  22137. }
  22138. else {
  22139. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  22140. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  22141. camera.setTarget(worldCenter);
  22142. }
  22143. this.activeCamera = camera;
  22144. }
  22145. };
  22146. // Tags
  22147. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22148. if (tagsQuery === undefined) {
  22149. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22150. return list;
  22151. }
  22152. var listByTags = [];
  22153. forEach = forEach || (function (item) { return; });
  22154. for (var i in list) {
  22155. var item = list[i];
  22156. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  22157. listByTags.push(item);
  22158. forEach(item);
  22159. }
  22160. }
  22161. return listByTags;
  22162. };
  22163. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  22164. return this._getByTags(this.meshes, tagsQuery, forEach);
  22165. };
  22166. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  22167. return this._getByTags(this.cameras, tagsQuery, forEach);
  22168. };
  22169. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  22170. return this._getByTags(this.lights, tagsQuery, forEach);
  22171. };
  22172. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  22173. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  22174. };
  22175. /**
  22176. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22177. * This allowed control for front to back rendering or reversly depending of the special needs.
  22178. *
  22179. * @param renderingGroupId The rendering group id corresponding to its index
  22180. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22181. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22182. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22183. */
  22184. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22185. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22186. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22187. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22188. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22189. };
  22190. /**
  22191. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22192. *
  22193. * @param renderingGroupId The rendering group id corresponding to its index
  22194. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22195. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22196. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22197. */
  22198. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22199. if (depth === void 0) { depth = true; }
  22200. if (stencil === void 0) { stencil = true; }
  22201. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  22202. };
  22203. return Scene;
  22204. }());
  22205. // Statics
  22206. Scene._FOGMODE_NONE = 0;
  22207. Scene._FOGMODE_EXP = 1;
  22208. Scene._FOGMODE_EXP2 = 2;
  22209. Scene._FOGMODE_LINEAR = 3;
  22210. Scene.MinDeltaTime = 1.0;
  22211. Scene.MaxDeltaTime = 1000.0;
  22212. Scene.DragMovementThreshold = 10; // in pixels
  22213. Scene.LongPressDelay = 500; // in milliseconds
  22214. Scene.DoubleClickDelay = 300; // in milliseconds
  22215. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  22216. BABYLON.Scene = Scene;
  22217. })(BABYLON || (BABYLON = {}));
  22218. //# sourceMappingURL=babylon.scene.js.map
  22219. var BABYLON;
  22220. (function (BABYLON) {
  22221. var Buffer = (function () {
  22222. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  22223. if (engine instanceof BABYLON.Mesh) {
  22224. this._engine = engine.getScene().getEngine();
  22225. }
  22226. else {
  22227. this._engine = engine;
  22228. }
  22229. this._updatable = updatable;
  22230. this._data = data;
  22231. this._strideSize = stride;
  22232. if (!postponeInternalCreation) {
  22233. this.create();
  22234. }
  22235. this._instanced = instanced;
  22236. }
  22237. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  22238. // a lot of these parameters are ignored as they are overriden by the buffer
  22239. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  22240. };
  22241. // Properties
  22242. Buffer.prototype.isUpdatable = function () {
  22243. return this._updatable;
  22244. };
  22245. Buffer.prototype.getData = function () {
  22246. return this._data;
  22247. };
  22248. Buffer.prototype.getBuffer = function () {
  22249. return this._buffer;
  22250. };
  22251. Buffer.prototype.getStrideSize = function () {
  22252. return this._strideSize;
  22253. };
  22254. Buffer.prototype.getIsInstanced = function () {
  22255. return this._instanced;
  22256. };
  22257. // Methods
  22258. Buffer.prototype.create = function (data) {
  22259. if (!data && this._buffer) {
  22260. return; // nothing to do
  22261. }
  22262. data = data || this._data;
  22263. if (!this._buffer) {
  22264. if (this._updatable) {
  22265. this._buffer = this._engine.createDynamicVertexBuffer(data);
  22266. this._data = data;
  22267. }
  22268. else {
  22269. this._buffer = this._engine.createVertexBuffer(data);
  22270. }
  22271. }
  22272. else if (this._updatable) {
  22273. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  22274. this._data = data;
  22275. }
  22276. };
  22277. Buffer.prototype.update = function (data) {
  22278. this.create(data);
  22279. };
  22280. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  22281. if (!this._buffer) {
  22282. return;
  22283. }
  22284. if (this._updatable) {
  22285. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  22286. this._data = null;
  22287. }
  22288. };
  22289. Buffer.prototype.dispose = function () {
  22290. if (!this._buffer) {
  22291. return;
  22292. }
  22293. if (this._engine._releaseBuffer(this._buffer)) {
  22294. this._buffer = null;
  22295. }
  22296. };
  22297. return Buffer;
  22298. }());
  22299. BABYLON.Buffer = Buffer;
  22300. })(BABYLON || (BABYLON = {}));
  22301. //# sourceMappingURL=babylon.buffer.js.map
  22302. var BABYLON;
  22303. (function (BABYLON) {
  22304. var VertexBuffer = (function () {
  22305. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  22306. if (!stride) {
  22307. // Deduce stride from kind
  22308. switch (kind) {
  22309. case VertexBuffer.PositionKind:
  22310. stride = 3;
  22311. break;
  22312. case VertexBuffer.NormalKind:
  22313. stride = 3;
  22314. break;
  22315. case VertexBuffer.UVKind:
  22316. case VertexBuffer.UV2Kind:
  22317. case VertexBuffer.UV3Kind:
  22318. case VertexBuffer.UV4Kind:
  22319. case VertexBuffer.UV5Kind:
  22320. case VertexBuffer.UV6Kind:
  22321. stride = 2;
  22322. break;
  22323. case VertexBuffer.TangentKind:
  22324. case VertexBuffer.ColorKind:
  22325. stride = 4;
  22326. break;
  22327. case VertexBuffer.MatricesIndicesKind:
  22328. case VertexBuffer.MatricesIndicesExtraKind:
  22329. stride = 4;
  22330. break;
  22331. case VertexBuffer.MatricesWeightsKind:
  22332. case VertexBuffer.MatricesWeightsExtraKind:
  22333. stride = 4;
  22334. break;
  22335. }
  22336. }
  22337. if (data instanceof BABYLON.Buffer) {
  22338. if (!stride) {
  22339. stride = data.getStrideSize();
  22340. }
  22341. this._buffer = data;
  22342. this._ownsBuffer = false;
  22343. }
  22344. else {
  22345. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  22346. this._ownsBuffer = true;
  22347. }
  22348. this._stride = stride;
  22349. this._offset = offset ? offset : 0;
  22350. this._size = size ? size : stride;
  22351. this._kind = kind;
  22352. }
  22353. /**
  22354. * Returns the kind of the VertexBuffer (string).
  22355. */
  22356. VertexBuffer.prototype.getKind = function () {
  22357. return this._kind;
  22358. };
  22359. // Properties
  22360. /**
  22361. * Boolean : is the VertexBuffer updatable ?
  22362. */
  22363. VertexBuffer.prototype.isUpdatable = function () {
  22364. return this._buffer.isUpdatable();
  22365. };
  22366. /**
  22367. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  22368. */
  22369. VertexBuffer.prototype.getData = function () {
  22370. return this._buffer.getData();
  22371. };
  22372. /**
  22373. * Returns the WebGLBuffer associated to the VertexBuffer.
  22374. */
  22375. VertexBuffer.prototype.getBuffer = function () {
  22376. return this._buffer.getBuffer();
  22377. };
  22378. /**
  22379. * Returns the stride of the VertexBuffer (integer).
  22380. */
  22381. VertexBuffer.prototype.getStrideSize = function () {
  22382. return this._stride;
  22383. };
  22384. /**
  22385. * Returns the offset (integer).
  22386. */
  22387. VertexBuffer.prototype.getOffset = function () {
  22388. return this._offset;
  22389. };
  22390. /**
  22391. * Returns the VertexBuffer total size (integer).
  22392. */
  22393. VertexBuffer.prototype.getSize = function () {
  22394. return this._size;
  22395. };
  22396. /**
  22397. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22398. */
  22399. VertexBuffer.prototype.getIsInstanced = function () {
  22400. return this._buffer.getIsInstanced();
  22401. };
  22402. // Methods
  22403. /**
  22404. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22405. * Returns the created WebGLBuffer.
  22406. */
  22407. VertexBuffer.prototype.create = function (data) {
  22408. return this._buffer.create(data);
  22409. };
  22410. /**
  22411. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22412. * Returns the updated WebGLBuffer.
  22413. */
  22414. VertexBuffer.prototype.update = function (data) {
  22415. return this._buffer.update(data);
  22416. };
  22417. /**
  22418. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22419. * Returns the directly updated WebGLBuffer.
  22420. */
  22421. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22422. return this._buffer.updateDirectly(data, offset);
  22423. };
  22424. /**
  22425. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22426. */
  22427. VertexBuffer.prototype.dispose = function () {
  22428. if (this._ownsBuffer) {
  22429. this._buffer.dispose();
  22430. }
  22431. };
  22432. Object.defineProperty(VertexBuffer, "PositionKind", {
  22433. get: function () {
  22434. return VertexBuffer._PositionKind;
  22435. },
  22436. enumerable: true,
  22437. configurable: true
  22438. });
  22439. Object.defineProperty(VertexBuffer, "NormalKind", {
  22440. get: function () {
  22441. return VertexBuffer._NormalKind;
  22442. },
  22443. enumerable: true,
  22444. configurable: true
  22445. });
  22446. Object.defineProperty(VertexBuffer, "TangentKind", {
  22447. get: function () {
  22448. return VertexBuffer._TangentKind;
  22449. },
  22450. enumerable: true,
  22451. configurable: true
  22452. });
  22453. Object.defineProperty(VertexBuffer, "UVKind", {
  22454. get: function () {
  22455. return VertexBuffer._UVKind;
  22456. },
  22457. enumerable: true,
  22458. configurable: true
  22459. });
  22460. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22461. get: function () {
  22462. return VertexBuffer._UV2Kind;
  22463. },
  22464. enumerable: true,
  22465. configurable: true
  22466. });
  22467. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22468. get: function () {
  22469. return VertexBuffer._UV3Kind;
  22470. },
  22471. enumerable: true,
  22472. configurable: true
  22473. });
  22474. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22475. get: function () {
  22476. return VertexBuffer._UV4Kind;
  22477. },
  22478. enumerable: true,
  22479. configurable: true
  22480. });
  22481. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22482. get: function () {
  22483. return VertexBuffer._UV5Kind;
  22484. },
  22485. enumerable: true,
  22486. configurable: true
  22487. });
  22488. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22489. get: function () {
  22490. return VertexBuffer._UV6Kind;
  22491. },
  22492. enumerable: true,
  22493. configurable: true
  22494. });
  22495. Object.defineProperty(VertexBuffer, "ColorKind", {
  22496. get: function () {
  22497. return VertexBuffer._ColorKind;
  22498. },
  22499. enumerable: true,
  22500. configurable: true
  22501. });
  22502. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22503. get: function () {
  22504. return VertexBuffer._MatricesIndicesKind;
  22505. },
  22506. enumerable: true,
  22507. configurable: true
  22508. });
  22509. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22510. get: function () {
  22511. return VertexBuffer._MatricesWeightsKind;
  22512. },
  22513. enumerable: true,
  22514. configurable: true
  22515. });
  22516. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22517. get: function () {
  22518. return VertexBuffer._MatricesIndicesExtraKind;
  22519. },
  22520. enumerable: true,
  22521. configurable: true
  22522. });
  22523. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22524. get: function () {
  22525. return VertexBuffer._MatricesWeightsExtraKind;
  22526. },
  22527. enumerable: true,
  22528. configurable: true
  22529. });
  22530. return VertexBuffer;
  22531. }());
  22532. // Enums
  22533. VertexBuffer._PositionKind = "position";
  22534. VertexBuffer._NormalKind = "normal";
  22535. VertexBuffer._TangentKind = "tangent";
  22536. VertexBuffer._UVKind = "uv";
  22537. VertexBuffer._UV2Kind = "uv2";
  22538. VertexBuffer._UV3Kind = "uv3";
  22539. VertexBuffer._UV4Kind = "uv4";
  22540. VertexBuffer._UV5Kind = "uv5";
  22541. VertexBuffer._UV6Kind = "uv6";
  22542. VertexBuffer._ColorKind = "color";
  22543. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22544. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22545. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22546. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22547. BABYLON.VertexBuffer = VertexBuffer;
  22548. })(BABYLON || (BABYLON = {}));
  22549. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22550. var BABYLON;
  22551. (function (BABYLON) {
  22552. /**
  22553. * Creates an instance based on a source mesh.
  22554. */
  22555. var InstancedMesh = (function (_super) {
  22556. __extends(InstancedMesh, _super);
  22557. function InstancedMesh(name, source) {
  22558. var _this = _super.call(this, name, source.getScene()) || this;
  22559. source.instances.push(_this);
  22560. _this._sourceMesh = source;
  22561. _this.position.copyFrom(source.position);
  22562. _this.rotation.copyFrom(source.rotation);
  22563. _this.scaling.copyFrom(source.scaling);
  22564. if (source.rotationQuaternion) {
  22565. _this.rotationQuaternion = source.rotationQuaternion.clone();
  22566. }
  22567. _this.infiniteDistance = source.infiniteDistance;
  22568. _this.setPivotMatrix(source.getPivotMatrix());
  22569. _this.refreshBoundingInfo();
  22570. _this._syncSubMeshes();
  22571. return _this;
  22572. }
  22573. /**
  22574. * Returns the string "InstancedMesh".
  22575. */
  22576. InstancedMesh.prototype.getClassName = function () {
  22577. return "InstancedMesh";
  22578. };
  22579. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  22580. // Methods
  22581. get: function () {
  22582. return this._sourceMesh.receiveShadows;
  22583. },
  22584. enumerable: true,
  22585. configurable: true
  22586. });
  22587. Object.defineProperty(InstancedMesh.prototype, "material", {
  22588. get: function () {
  22589. return this._sourceMesh.material;
  22590. },
  22591. enumerable: true,
  22592. configurable: true
  22593. });
  22594. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  22595. get: function () {
  22596. return this._sourceMesh.visibility;
  22597. },
  22598. enumerable: true,
  22599. configurable: true
  22600. });
  22601. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  22602. get: function () {
  22603. return this._sourceMesh.skeleton;
  22604. },
  22605. enumerable: true,
  22606. configurable: true
  22607. });
  22608. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  22609. get: function () {
  22610. return this._sourceMesh.renderingGroupId;
  22611. },
  22612. enumerable: true,
  22613. configurable: true
  22614. });
  22615. /**
  22616. * Returns the total number of vertices (integer).
  22617. */
  22618. InstancedMesh.prototype.getTotalVertices = function () {
  22619. return this._sourceMesh.getTotalVertices();
  22620. };
  22621. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  22622. get: function () {
  22623. return this._sourceMesh;
  22624. },
  22625. enumerable: true,
  22626. configurable: true
  22627. });
  22628. /**
  22629. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  22630. */
  22631. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22632. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  22633. };
  22634. /**
  22635. * Boolean : True if the mesh owns the requested kind of data.
  22636. */
  22637. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  22638. return this._sourceMesh.isVerticesDataPresent(kind);
  22639. };
  22640. /**
  22641. * Returns an array of indices (IndicesArray).
  22642. */
  22643. InstancedMesh.prototype.getIndices = function () {
  22644. return this._sourceMesh.getIndices();
  22645. };
  22646. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  22647. get: function () {
  22648. return this._sourceMesh._positions;
  22649. },
  22650. enumerable: true,
  22651. configurable: true
  22652. });
  22653. /**
  22654. * Sets a new updated BoundingInfo to the mesh.
  22655. * Returns the mesh.
  22656. */
  22657. InstancedMesh.prototype.refreshBoundingInfo = function () {
  22658. var meshBB = this._sourceMesh.getBoundingInfo();
  22659. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  22660. this._updateBoundingInfo();
  22661. return this;
  22662. };
  22663. InstancedMesh.prototype._preActivate = function () {
  22664. if (this._currentLOD) {
  22665. this._currentLOD._preActivate();
  22666. }
  22667. return this;
  22668. };
  22669. InstancedMesh.prototype._activate = function (renderId) {
  22670. if (this._currentLOD) {
  22671. this._currentLOD._registerInstanceForRenderId(this, renderId);
  22672. }
  22673. return this;
  22674. };
  22675. /**
  22676. * Returns the current associated LOD AbstractMesh.
  22677. */
  22678. InstancedMesh.prototype.getLOD = function (camera) {
  22679. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  22680. if (this._currentLOD === this.sourceMesh) {
  22681. return this;
  22682. }
  22683. return this._currentLOD;
  22684. };
  22685. InstancedMesh.prototype._syncSubMeshes = function () {
  22686. this.releaseSubMeshes();
  22687. if (this._sourceMesh.subMeshes) {
  22688. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  22689. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  22690. }
  22691. }
  22692. return this;
  22693. };
  22694. InstancedMesh.prototype._generatePointsArray = function () {
  22695. return this._sourceMesh._generatePointsArray();
  22696. };
  22697. /**
  22698. * Creates a new InstancedMesh from the current mesh.
  22699. * - name (string) : the cloned mesh name
  22700. * - newParent (optional Node) : the optional Node to parent the clone to.
  22701. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  22702. *
  22703. * Returns the clone.
  22704. */
  22705. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22706. var result = this._sourceMesh.createInstance(name);
  22707. // Deep copy
  22708. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  22709. // Bounding info
  22710. this.refreshBoundingInfo();
  22711. // Parent
  22712. if (newParent) {
  22713. result.parent = newParent;
  22714. }
  22715. if (!doNotCloneChildren) {
  22716. // Children
  22717. for (var index = 0; index < this.getScene().meshes.length; index++) {
  22718. var mesh = this.getScene().meshes[index];
  22719. if (mesh.parent === this) {
  22720. mesh.clone(mesh.name, result);
  22721. }
  22722. }
  22723. }
  22724. result.computeWorldMatrix(true);
  22725. return result;
  22726. };
  22727. /**
  22728. * Disposes the InstancedMesh.
  22729. * Returns nothing.
  22730. */
  22731. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  22732. // Remove from mesh
  22733. var index = this._sourceMesh.instances.indexOf(this);
  22734. this._sourceMesh.instances.splice(index, 1);
  22735. _super.prototype.dispose.call(this, doNotRecurse);
  22736. };
  22737. return InstancedMesh;
  22738. }(BABYLON.AbstractMesh));
  22739. BABYLON.InstancedMesh = InstancedMesh;
  22740. })(BABYLON || (BABYLON = {}));
  22741. //# sourceMappingURL=babylon.instancedMesh.js.map
  22742. var BABYLON;
  22743. (function (BABYLON) {
  22744. var _InstancesBatch = (function () {
  22745. function _InstancesBatch() {
  22746. this.mustReturn = false;
  22747. this.visibleInstances = new Array();
  22748. this.renderSelf = new Array();
  22749. }
  22750. return _InstancesBatch;
  22751. }());
  22752. BABYLON._InstancesBatch = _InstancesBatch;
  22753. var Mesh = (function (_super) {
  22754. __extends(Mesh, _super);
  22755. /**
  22756. * @constructor
  22757. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22758. * @param {Scene} scene The scene to add this mesh to.
  22759. * @param {Node} parent The parent of this mesh, if it has one
  22760. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22761. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22762. * When false, achieved by calling a clone(), also passing False.
  22763. * This will make creation of children, recursive.
  22764. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22765. */
  22766. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22767. if (parent === void 0) { parent = null; }
  22768. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22769. var _this = _super.call(this, name, scene) || this;
  22770. // Events
  22771. /**
  22772. * An event triggered before rendering the mesh
  22773. * @type {BABYLON.Observable}
  22774. */
  22775. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22776. /**
  22777. * An event triggered after rendering the mesh
  22778. * @type {BABYLON.Observable}
  22779. */
  22780. _this.onAfterRenderObservable = new BABYLON.Observable();
  22781. /**
  22782. * An event triggered before drawing the mesh
  22783. * @type {BABYLON.Observable}
  22784. */
  22785. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22786. // Members
  22787. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22788. _this.instances = new Array();
  22789. _this._LODLevels = new Array();
  22790. _this._visibleInstances = {};
  22791. _this._renderIdForInstances = new Array();
  22792. _this._batchCache = new _InstancesBatch();
  22793. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22794. _this._sideOrientation = Mesh._DEFAULTSIDE;
  22795. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22796. // Will be used to save a source mesh reference, If any
  22797. _this._source = null;
  22798. if (source) {
  22799. // Source mesh
  22800. _this._source = source;
  22801. // Geometry
  22802. if (source._geometry) {
  22803. source._geometry.applyToMesh(_this);
  22804. }
  22805. // Deep copy
  22806. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  22807. // Parent
  22808. _this.parent = source.parent;
  22809. // Pivot
  22810. _this.setPivotMatrix(source.getPivotMatrix());
  22811. _this.id = name + "." + source.id;
  22812. // Material
  22813. _this.material = source.material;
  22814. var index;
  22815. if (!doNotCloneChildren) {
  22816. // Children
  22817. for (index = 0; index < scene.meshes.length; index++) {
  22818. var mesh = scene.meshes[index];
  22819. if (mesh.parent === source) {
  22820. // doNotCloneChildren is always going to be False
  22821. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22822. }
  22823. }
  22824. }
  22825. // Physics clone
  22826. var physicsEngine = _this.getScene().getPhysicsEngine();
  22827. if (clonePhysicsImpostor && physicsEngine) {
  22828. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22829. if (impostor) {
  22830. _this.physicsImpostor = impostor.clone(_this);
  22831. }
  22832. }
  22833. // Particles
  22834. for (index = 0; index < scene.particleSystems.length; index++) {
  22835. var system = scene.particleSystems[index];
  22836. if (system.emitter === source) {
  22837. system.clone(system.name, _this);
  22838. }
  22839. }
  22840. _this.computeWorldMatrix(true);
  22841. }
  22842. // Parent
  22843. if (parent !== null) {
  22844. _this.parent = parent;
  22845. }
  22846. return _this;
  22847. }
  22848. Object.defineProperty(Mesh, "FRONTSIDE", {
  22849. /**
  22850. * Mesh side orientation : usually the external or front surface
  22851. */
  22852. get: function () {
  22853. return Mesh._FRONTSIDE;
  22854. },
  22855. enumerable: true,
  22856. configurable: true
  22857. });
  22858. Object.defineProperty(Mesh, "BACKSIDE", {
  22859. /**
  22860. * Mesh side orientation : usually the internal or back surface
  22861. */
  22862. get: function () {
  22863. return Mesh._BACKSIDE;
  22864. },
  22865. enumerable: true,
  22866. configurable: true
  22867. });
  22868. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22869. /**
  22870. * Mesh side orientation : both internal and external or front and back surfaces
  22871. */
  22872. get: function () {
  22873. return Mesh._DOUBLESIDE;
  22874. },
  22875. enumerable: true,
  22876. configurable: true
  22877. });
  22878. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22879. /**
  22880. * Mesh side orientation : by default, `FRONTSIDE`
  22881. */
  22882. get: function () {
  22883. return Mesh._DEFAULTSIDE;
  22884. },
  22885. enumerable: true,
  22886. configurable: true
  22887. });
  22888. Object.defineProperty(Mesh, "NO_CAP", {
  22889. /**
  22890. * Mesh cap setting : no cap
  22891. */
  22892. get: function () {
  22893. return Mesh._NO_CAP;
  22894. },
  22895. enumerable: true,
  22896. configurable: true
  22897. });
  22898. Object.defineProperty(Mesh, "CAP_START", {
  22899. /**
  22900. * Mesh cap setting : one cap at the beginning of the mesh
  22901. */
  22902. get: function () {
  22903. return Mesh._CAP_START;
  22904. },
  22905. enumerable: true,
  22906. configurable: true
  22907. });
  22908. Object.defineProperty(Mesh, "CAP_END", {
  22909. /**
  22910. * Mesh cap setting : one cap at the end of the mesh
  22911. */
  22912. get: function () {
  22913. return Mesh._CAP_END;
  22914. },
  22915. enumerable: true,
  22916. configurable: true
  22917. });
  22918. Object.defineProperty(Mesh, "CAP_ALL", {
  22919. /**
  22920. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22921. */
  22922. get: function () {
  22923. return Mesh._CAP_ALL;
  22924. },
  22925. enumerable: true,
  22926. configurable: true
  22927. });
  22928. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22929. set: function (callback) {
  22930. if (this._onBeforeDrawObserver) {
  22931. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22932. }
  22933. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22934. },
  22935. enumerable: true,
  22936. configurable: true
  22937. });
  22938. Object.defineProperty(Mesh.prototype, "source", {
  22939. get: function () {
  22940. return this._source;
  22941. },
  22942. enumerable: true,
  22943. configurable: true
  22944. });
  22945. // Methods
  22946. /**
  22947. * Returns the string "Mesh".
  22948. */
  22949. Mesh.prototype.getClassName = function () {
  22950. return "Mesh";
  22951. };
  22952. /**
  22953. * Returns a string.
  22954. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22955. */
  22956. Mesh.prototype.toString = function (fullDetails) {
  22957. var ret = _super.prototype.toString.call(this, fullDetails);
  22958. ret += ", n vertices: " + this.getTotalVertices();
  22959. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22960. if (this.animations) {
  22961. for (var i = 0; i < this.animations.length; i++) {
  22962. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22963. }
  22964. }
  22965. if (fullDetails) {
  22966. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  22967. }
  22968. return ret;
  22969. };
  22970. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22971. /**
  22972. * True if the mesh has some Levels Of Details (LOD).
  22973. * Returns a boolean.
  22974. */
  22975. get: function () {
  22976. return this._LODLevels.length > 0;
  22977. },
  22978. enumerable: true,
  22979. configurable: true
  22980. });
  22981. Mesh.prototype._sortLODLevels = function () {
  22982. this._LODLevels.sort(function (a, b) {
  22983. if (a.distance < b.distance) {
  22984. return 1;
  22985. }
  22986. if (a.distance > b.distance) {
  22987. return -1;
  22988. }
  22989. return 0;
  22990. });
  22991. };
  22992. /**
  22993. * Add a mesh as LOD level triggered at the given distance.
  22994. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22995. * @param {number} distance The distance from the center of the object to show this level
  22996. * @param {Mesh} mesh The mesh to be added as LOD level
  22997. * @return {Mesh} This mesh (for chaining)
  22998. */
  22999. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23000. if (mesh && mesh._masterMesh) {
  23001. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23002. return this;
  23003. }
  23004. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23005. this._LODLevels.push(level);
  23006. if (mesh) {
  23007. mesh._masterMesh = this;
  23008. }
  23009. this._sortLODLevels();
  23010. return this;
  23011. };
  23012. /**
  23013. * Returns the LOD level mesh at the passed distance or null if not found.
  23014. * It is related to the method `addLODLevel(distance, mesh)`.
  23015. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23016. * Returns an object Mesh or `null`.
  23017. */
  23018. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23019. for (var index = 0; index < this._LODLevels.length; index++) {
  23020. var level = this._LODLevels[index];
  23021. if (level.distance === distance) {
  23022. return level.mesh;
  23023. }
  23024. }
  23025. return null;
  23026. };
  23027. /**
  23028. * Remove a mesh from the LOD array
  23029. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23030. * @param {Mesh} mesh The mesh to be removed.
  23031. * @return {Mesh} This mesh (for chaining)
  23032. */
  23033. Mesh.prototype.removeLODLevel = function (mesh) {
  23034. for (var index = 0; index < this._LODLevels.length; index++) {
  23035. if (this._LODLevels[index].mesh === mesh) {
  23036. this._LODLevels.splice(index, 1);
  23037. if (mesh) {
  23038. mesh._masterMesh = null;
  23039. }
  23040. }
  23041. }
  23042. this._sortLODLevels();
  23043. return this;
  23044. };
  23045. /**
  23046. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23047. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23048. */
  23049. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23050. if (!this._LODLevels || this._LODLevels.length === 0) {
  23051. return this;
  23052. }
  23053. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  23054. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23055. if (this.onLODLevelSelection) {
  23056. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23057. }
  23058. return this;
  23059. }
  23060. for (var index = 0; index < this._LODLevels.length; index++) {
  23061. var level = this._LODLevels[index];
  23062. if (level.distance < distanceToCamera) {
  23063. if (level.mesh) {
  23064. level.mesh._preActivate();
  23065. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23066. }
  23067. if (this.onLODLevelSelection) {
  23068. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23069. }
  23070. return level.mesh;
  23071. }
  23072. }
  23073. if (this.onLODLevelSelection) {
  23074. this.onLODLevelSelection(distanceToCamera, this, this);
  23075. }
  23076. return this;
  23077. };
  23078. Object.defineProperty(Mesh.prototype, "geometry", {
  23079. /**
  23080. * Returns the mesh internal Geometry object.
  23081. */
  23082. get: function () {
  23083. return this._geometry;
  23084. },
  23085. enumerable: true,
  23086. configurable: true
  23087. });
  23088. /**
  23089. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23090. */
  23091. Mesh.prototype.getTotalVertices = function () {
  23092. if (!this._geometry) {
  23093. return 0;
  23094. }
  23095. return this._geometry.getTotalVertices();
  23096. };
  23097. /**
  23098. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23099. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  23100. * Returns null if the mesh has no geometry or no vertex buffer.
  23101. * Possible `kind` values :
  23102. * - BABYLON.VertexBuffer.PositionKind
  23103. * - BABYLON.VertexBuffer.UVKind
  23104. * - BABYLON.VertexBuffer.UV2Kind
  23105. * - BABYLON.VertexBuffer.UV3Kind
  23106. * - BABYLON.VertexBuffer.UV4Kind
  23107. * - BABYLON.VertexBuffer.UV5Kind
  23108. * - BABYLON.VertexBuffer.UV6Kind
  23109. * - BABYLON.VertexBuffer.ColorKind
  23110. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23111. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23112. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23113. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23114. */
  23115. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  23116. if (!this._geometry) {
  23117. return null;
  23118. }
  23119. return this._geometry.getVerticesData(kind, copyWhenShared);
  23120. };
  23121. /**
  23122. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23123. * Returns `undefined` if the mesh has no geometry.
  23124. * Possible `kind` values :
  23125. * - BABYLON.VertexBuffer.PositionKind
  23126. * - BABYLON.VertexBuffer.UVKind
  23127. * - BABYLON.VertexBuffer.UV2Kind
  23128. * - BABYLON.VertexBuffer.UV3Kind
  23129. * - BABYLON.VertexBuffer.UV4Kind
  23130. * - BABYLON.VertexBuffer.UV5Kind
  23131. * - BABYLON.VertexBuffer.UV6Kind
  23132. * - BABYLON.VertexBuffer.ColorKind
  23133. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23134. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23135. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23136. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23137. */
  23138. Mesh.prototype.getVertexBuffer = function (kind) {
  23139. if (!this._geometry) {
  23140. return undefined;
  23141. }
  23142. return this._geometry.getVertexBuffer(kind);
  23143. };
  23144. /**
  23145. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23146. * Possible `kind` values :
  23147. * - BABYLON.VertexBuffer.PositionKind
  23148. * - BABYLON.VertexBuffer.UVKind
  23149. * - BABYLON.VertexBuffer.UV2Kind
  23150. * - BABYLON.VertexBuffer.UV3Kind
  23151. * - BABYLON.VertexBuffer.UV4Kind
  23152. * - BABYLON.VertexBuffer.UV5Kind
  23153. * - BABYLON.VertexBuffer.UV6Kind
  23154. * - BABYLON.VertexBuffer.ColorKind
  23155. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23156. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23157. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23158. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23159. */
  23160. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23161. if (!this._geometry) {
  23162. if (this._delayInfo) {
  23163. return this._delayInfo.indexOf(kind) !== -1;
  23164. }
  23165. return false;
  23166. }
  23167. return this._geometry.isVerticesDataPresent(kind);
  23168. };
  23169. /**
  23170. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23171. * Possible `kind` values :
  23172. * - BABYLON.VertexBuffer.PositionKind
  23173. * - BABYLON.VertexBuffer.UVKind
  23174. * - BABYLON.VertexBuffer.UV2Kind
  23175. * - BABYLON.VertexBuffer.UV3Kind
  23176. * - BABYLON.VertexBuffer.UV4Kind
  23177. * - BABYLON.VertexBuffer.UV5Kind
  23178. * - BABYLON.VertexBuffer.UV6Kind
  23179. * - BABYLON.VertexBuffer.ColorKind
  23180. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23181. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23182. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23183. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23184. */
  23185. Mesh.prototype.getVerticesDataKinds = function () {
  23186. if (!this._geometry) {
  23187. var result = [];
  23188. if (this._delayInfo) {
  23189. this._delayInfo.forEach(function (kind, index, array) {
  23190. result.push(kind);
  23191. });
  23192. }
  23193. return result;
  23194. }
  23195. return this._geometry.getVerticesDataKinds();
  23196. };
  23197. /**
  23198. * Returns a positive integer : the total number of indices in this mesh geometry.
  23199. * Returns zero if the mesh has no geometry.
  23200. */
  23201. Mesh.prototype.getTotalIndices = function () {
  23202. if (!this._geometry) {
  23203. return 0;
  23204. }
  23205. return this._geometry.getTotalIndices();
  23206. };
  23207. /**
  23208. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23209. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  23210. * Returns an empty array if the mesh has no geometry.
  23211. */
  23212. Mesh.prototype.getIndices = function (copyWhenShared) {
  23213. if (!this._geometry) {
  23214. return [];
  23215. }
  23216. return this._geometry.getIndices(copyWhenShared);
  23217. };
  23218. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23219. get: function () {
  23220. return this._masterMesh !== null && this._masterMesh !== undefined;
  23221. },
  23222. enumerable: true,
  23223. configurable: true
  23224. });
  23225. /**
  23226. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23227. */
  23228. Mesh.prototype.isReady = function () {
  23229. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23230. return false;
  23231. }
  23232. return _super.prototype.isReady.call(this);
  23233. };
  23234. /**
  23235. * Boolean : true if the mesh has been disposed.
  23236. */
  23237. Mesh.prototype.isDisposed = function () {
  23238. return this._isDisposed;
  23239. };
  23240. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  23241. get: function () {
  23242. return this._sideOrientation;
  23243. },
  23244. /**
  23245. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  23246. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  23247. */
  23248. set: function (sideO) {
  23249. this._sideOrientation = sideO;
  23250. },
  23251. enumerable: true,
  23252. configurable: true
  23253. });
  23254. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23255. /**
  23256. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23257. * This property is pertinent only for updatable parametric shapes.
  23258. */
  23259. get: function () {
  23260. return this._areNormalsFrozen;
  23261. },
  23262. enumerable: true,
  23263. configurable: true
  23264. });
  23265. /**
  23266. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23267. * It has no effect at all on other shapes.
  23268. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23269. * Returns the Mesh.
  23270. */
  23271. Mesh.prototype.freezeNormals = function () {
  23272. this._areNormalsFrozen = true;
  23273. return this;
  23274. };
  23275. /**
  23276. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23277. * It has no effect at all on other shapes.
  23278. * It reactivates the mesh normals computation if it was previously frozen.
  23279. * Returns the Mesh.
  23280. */
  23281. Mesh.prototype.unfreezeNormals = function () {
  23282. this._areNormalsFrozen = false;
  23283. return this;
  23284. };
  23285. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23286. /**
  23287. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23288. */
  23289. set: function (count) {
  23290. this._overridenInstanceCount = count;
  23291. },
  23292. enumerable: true,
  23293. configurable: true
  23294. });
  23295. // Methods
  23296. Mesh.prototype._preActivate = function () {
  23297. var sceneRenderId = this.getScene().getRenderId();
  23298. if (this._preActivateId === sceneRenderId) {
  23299. return this;
  23300. }
  23301. this._preActivateId = sceneRenderId;
  23302. this._visibleInstances = null;
  23303. return this;
  23304. };
  23305. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23306. if (this._visibleInstances) {
  23307. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23308. }
  23309. return this;
  23310. };
  23311. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23312. if (!this._visibleInstances) {
  23313. this._visibleInstances = {};
  23314. this._visibleInstances.defaultRenderId = renderId;
  23315. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23316. }
  23317. if (!this._visibleInstances[renderId]) {
  23318. this._visibleInstances[renderId] = new Array();
  23319. }
  23320. this._visibleInstances[renderId].push(instance);
  23321. return this;
  23322. };
  23323. /**
  23324. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23325. * This means the mesh underlying bounding box and sphere are recomputed.
  23326. * Returns the Mesh.
  23327. */
  23328. Mesh.prototype.refreshBoundingInfo = function () {
  23329. if (this._boundingInfo.isLocked) {
  23330. return;
  23331. }
  23332. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23333. if (data) {
  23334. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23335. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23336. }
  23337. if (this.subMeshes) {
  23338. for (var index = 0; index < this.subMeshes.length; index++) {
  23339. this.subMeshes[index].refreshBoundingInfo();
  23340. }
  23341. }
  23342. this._updateBoundingInfo();
  23343. return this;
  23344. };
  23345. Mesh.prototype._createGlobalSubMesh = function () {
  23346. var totalVertices = this.getTotalVertices();
  23347. if (!totalVertices || !this.getIndices()) {
  23348. return null;
  23349. }
  23350. this.releaseSubMeshes();
  23351. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23352. };
  23353. Mesh.prototype.subdivide = function (count) {
  23354. if (count < 1) {
  23355. return;
  23356. }
  23357. var totalIndices = this.getTotalIndices();
  23358. var subdivisionSize = (totalIndices / count) | 0;
  23359. var offset = 0;
  23360. // Ensure that subdivisionSize is a multiple of 3
  23361. while (subdivisionSize % 3 !== 0) {
  23362. subdivisionSize++;
  23363. }
  23364. this.releaseSubMeshes();
  23365. for (var index = 0; index < count; index++) {
  23366. if (offset >= totalIndices) {
  23367. break;
  23368. }
  23369. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23370. offset += subdivisionSize;
  23371. }
  23372. this.synchronizeInstances();
  23373. };
  23374. /**
  23375. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23376. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23377. * The `data` are either a numeric array either a Float32Array.
  23378. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23379. * 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).
  23380. * Note that a new underlying VertexBuffer object is created each call.
  23381. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23382. *
  23383. * Possible `kind` values :
  23384. * - BABYLON.VertexBuffer.PositionKind
  23385. * - BABYLON.VertexBuffer.UVKind
  23386. * - BABYLON.VertexBuffer.UV2Kind
  23387. * - BABYLON.VertexBuffer.UV3Kind
  23388. * - BABYLON.VertexBuffer.UV4Kind
  23389. * - BABYLON.VertexBuffer.UV5Kind
  23390. * - BABYLON.VertexBuffer.UV6Kind
  23391. * - BABYLON.VertexBuffer.ColorKind
  23392. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23393. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23394. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23395. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23396. *
  23397. * Returns the Mesh.
  23398. */
  23399. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23400. if (!this._geometry) {
  23401. var vertexData = new BABYLON.VertexData();
  23402. vertexData.set(data, kind);
  23403. var scene = this.getScene();
  23404. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23405. }
  23406. else {
  23407. this._geometry.setVerticesData(kind, data, updatable, stride);
  23408. }
  23409. return this;
  23410. };
  23411. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23412. if (updatable === void 0) { updatable = true; }
  23413. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  23414. return;
  23415. }
  23416. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23417. };
  23418. /**
  23419. * Sets the mesh VertexBuffer.
  23420. * Returns the Mesh.
  23421. */
  23422. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23423. if (!this._geometry) {
  23424. var scene = this.getScene();
  23425. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  23426. }
  23427. this._geometry.setVerticesBuffer(buffer);
  23428. return this;
  23429. };
  23430. /**
  23431. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23432. * If the mesh has no geometry, it is simply returned as it is.
  23433. * The `data` are either a numeric array either a Float32Array.
  23434. * No new underlying VertexBuffer object is created.
  23435. * 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.
  23436. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23437. *
  23438. * Possible `kind` values :
  23439. * - BABYLON.VertexBuffer.PositionKind
  23440. * - BABYLON.VertexBuffer.UVKind
  23441. * - BABYLON.VertexBuffer.UV2Kind
  23442. * - BABYLON.VertexBuffer.UV3Kind
  23443. * - BABYLON.VertexBuffer.UV4Kind
  23444. * - BABYLON.VertexBuffer.UV5Kind
  23445. * - BABYLON.VertexBuffer.UV6Kind
  23446. * - BABYLON.VertexBuffer.ColorKind
  23447. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23448. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23449. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23450. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23451. *
  23452. * Returns the Mesh.
  23453. */
  23454. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23455. if (!this._geometry) {
  23456. return;
  23457. }
  23458. if (!makeItUnique) {
  23459. this._geometry.updateVerticesData(kind, data, updateExtends);
  23460. }
  23461. else {
  23462. this.makeGeometryUnique();
  23463. this.updateVerticesData(kind, data, updateExtends, false);
  23464. }
  23465. return this;
  23466. };
  23467. /**
  23468. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23469. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23470. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23471. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23472. * Returns the Mesh.
  23473. */
  23474. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23475. if (computeNormals === void 0) { computeNormals = true; }
  23476. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23477. positionFunction(positions);
  23478. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23479. if (computeNormals) {
  23480. var indices = this.getIndices();
  23481. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23482. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23483. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23484. }
  23485. return this;
  23486. };
  23487. /**
  23488. * Creates a un-shared specific occurence of the geometry for the mesh.
  23489. * Returns the Mesh.
  23490. */
  23491. Mesh.prototype.makeGeometryUnique = function () {
  23492. if (!this._geometry) {
  23493. return;
  23494. }
  23495. var oldGeometry = this._geometry;
  23496. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23497. oldGeometry.releaseForMesh(this, true);
  23498. geometry.applyToMesh(this);
  23499. return this;
  23500. };
  23501. /**
  23502. * Sets the mesh indices.
  23503. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23504. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23505. * This method creates a new index buffer each call.
  23506. * Returns the Mesh.
  23507. */
  23508. Mesh.prototype.setIndices = function (indices, totalVertices) {
  23509. if (!this._geometry) {
  23510. var vertexData = new BABYLON.VertexData();
  23511. vertexData.indices = indices;
  23512. var scene = this.getScene();
  23513. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  23514. }
  23515. else {
  23516. this._geometry.setIndices(indices, totalVertices);
  23517. }
  23518. return this;
  23519. };
  23520. /**
  23521. * Invert the geometry to move from a right handed system to a left handed one.
  23522. * Returns the Mesh.
  23523. */
  23524. Mesh.prototype.toLeftHanded = function () {
  23525. if (!this._geometry) {
  23526. return;
  23527. }
  23528. this._geometry.toLeftHanded();
  23529. return this;
  23530. };
  23531. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23532. var engine = this.getScene().getEngine();
  23533. // Wireframe
  23534. var indexToBind;
  23535. if (this._unIndexed) {
  23536. indexToBind = null;
  23537. }
  23538. else {
  23539. switch (fillMode) {
  23540. case BABYLON.Material.PointFillMode:
  23541. indexToBind = null;
  23542. break;
  23543. case BABYLON.Material.WireFrameFillMode:
  23544. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23545. break;
  23546. default:
  23547. case BABYLON.Material.TriangleFillMode:
  23548. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23549. break;
  23550. }
  23551. }
  23552. // VBOs
  23553. this._geometry._bind(effect, indexToBind);
  23554. return this;
  23555. };
  23556. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23557. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23558. return this;
  23559. }
  23560. this.onBeforeDrawObservable.notifyObservers(this);
  23561. var engine = this.getScene().getEngine();
  23562. // Draw order
  23563. switch (fillMode) {
  23564. case BABYLON.Material.PointFillMode:
  23565. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23566. break;
  23567. case BABYLON.Material.WireFrameFillMode:
  23568. if (this._unIndexed) {
  23569. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23570. }
  23571. else {
  23572. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  23573. }
  23574. break;
  23575. default:
  23576. if (this._unIndexed) {
  23577. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23578. }
  23579. else {
  23580. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23581. }
  23582. }
  23583. return this;
  23584. };
  23585. /**
  23586. * Registers for this mesh a javascript function called just before the rendering process.
  23587. * This function is passed the current mesh.
  23588. * Return the Mesh.
  23589. */
  23590. Mesh.prototype.registerBeforeRender = function (func) {
  23591. this.onBeforeRenderObservable.add(func);
  23592. return this;
  23593. };
  23594. /**
  23595. * Disposes a previously registered javascript function called before the rendering.
  23596. * This function is passed the current mesh.
  23597. * Returns the Mesh.
  23598. */
  23599. Mesh.prototype.unregisterBeforeRender = function (func) {
  23600. this.onBeforeRenderObservable.removeCallback(func);
  23601. return this;
  23602. };
  23603. /**
  23604. * Registers for this mesh a javascript function called just after the rendering is complete.
  23605. * This function is passed the current mesh.
  23606. * Returns the Mesh.
  23607. */
  23608. Mesh.prototype.registerAfterRender = function (func) {
  23609. this.onAfterRenderObservable.add(func);
  23610. return this;
  23611. };
  23612. /**
  23613. * Disposes a previously registered javascript function called after the rendering.
  23614. * This function is passed the current mesh.
  23615. * Return the Mesh.
  23616. */
  23617. Mesh.prototype.unregisterAfterRender = function (func) {
  23618. this.onAfterRenderObservable.removeCallback(func);
  23619. return this;
  23620. };
  23621. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23622. var scene = this.getScene();
  23623. this._batchCache.mustReturn = false;
  23624. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23625. this._batchCache.visibleInstances[subMeshId] = null;
  23626. if (this._visibleInstances) {
  23627. var currentRenderId = scene.getRenderId();
  23628. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23629. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23630. var selfRenderId = this._renderId;
  23631. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23632. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23633. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23634. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23635. }
  23636. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  23637. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23638. this._batchCache.mustReturn = true;
  23639. return this._batchCache;
  23640. }
  23641. if (currentRenderId !== selfRenderId) {
  23642. this._batchCache.renderSelf[subMeshId] = false;
  23643. }
  23644. }
  23645. this._renderIdForInstances[subMeshId] = currentRenderId;
  23646. }
  23647. return this._batchCache;
  23648. };
  23649. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23650. var visibleInstances = batch.visibleInstances[subMesh._id];
  23651. var matricesCount = visibleInstances.length + 1;
  23652. var bufferSize = matricesCount * 16 * 4;
  23653. var currentInstancesBufferSize = this._instancesBufferSize;
  23654. var instancesBuffer = this._instancesBuffer;
  23655. while (this._instancesBufferSize < bufferSize) {
  23656. this._instancesBufferSize *= 2;
  23657. }
  23658. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23659. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23660. }
  23661. var offset = 0;
  23662. var instancesCount = 0;
  23663. var world = this.getWorldMatrix();
  23664. if (batch.renderSelf[subMesh._id]) {
  23665. world.copyToArray(this._instancesData, offset);
  23666. offset += 16;
  23667. instancesCount++;
  23668. }
  23669. if (visibleInstances) {
  23670. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23671. var instance = visibleInstances[instanceIndex];
  23672. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23673. offset += 16;
  23674. instancesCount++;
  23675. }
  23676. }
  23677. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23678. if (instancesBuffer) {
  23679. instancesBuffer.dispose();
  23680. }
  23681. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23682. this._instancesBuffer = instancesBuffer;
  23683. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23684. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23685. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23686. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23687. }
  23688. else {
  23689. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23690. }
  23691. this.geometry._bind(effect);
  23692. this._draw(subMesh, fillMode, instancesCount);
  23693. engine.unbindInstanceAttributes();
  23694. return this;
  23695. };
  23696. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23697. var scene = this.getScene();
  23698. var engine = scene.getEngine();
  23699. if (hardwareInstancedRendering) {
  23700. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23701. }
  23702. else {
  23703. if (batch.renderSelf[subMesh._id]) {
  23704. // Draw
  23705. if (onBeforeDraw) {
  23706. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23707. }
  23708. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23709. }
  23710. if (batch.visibleInstances[subMesh._id]) {
  23711. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23712. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23713. // World
  23714. var world = instance.getWorldMatrix();
  23715. if (onBeforeDraw) {
  23716. onBeforeDraw(true, world, effectiveMaterial);
  23717. }
  23718. // Draw
  23719. this._draw(subMesh, fillMode);
  23720. }
  23721. }
  23722. }
  23723. return this;
  23724. };
  23725. /**
  23726. * Triggers the draw call for the mesh.
  23727. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23728. * Returns the Mesh.
  23729. */
  23730. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23731. var scene = this.getScene();
  23732. // Managing instances
  23733. var batch = this._getInstancesRenderList(subMesh._id);
  23734. if (batch.mustReturn) {
  23735. return this;
  23736. }
  23737. // Checking geometry state
  23738. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23739. return this;
  23740. }
  23741. var callbackIndex;
  23742. this.onBeforeRenderObservable.notifyObservers(this);
  23743. var engine = scene.getEngine();
  23744. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23745. // Material
  23746. var effectiveMaterial = subMesh.getMaterial();
  23747. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23748. return this;
  23749. }
  23750. // Outline - step 1
  23751. var savedDepthWrite = engine.getDepthWrite();
  23752. if (this.renderOutline) {
  23753. engine.setDepthWrite(false);
  23754. scene.getOutlineRenderer().render(subMesh, batch);
  23755. engine.setDepthWrite(savedDepthWrite);
  23756. }
  23757. effectiveMaterial._preBind();
  23758. var effect = effectiveMaterial.getEffect();
  23759. // Bind
  23760. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  23761. this._bind(subMesh, effect, fillMode);
  23762. var world = this.getWorldMatrix();
  23763. effectiveMaterial.bind(world, this);
  23764. // Alpha mode
  23765. if (enableAlphaMode) {
  23766. engine.setAlphaMode(effectiveMaterial.alphaMode);
  23767. }
  23768. // Draw
  23769. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  23770. // Unbind
  23771. effectiveMaterial.unbind();
  23772. // Outline - step 2
  23773. if (this.renderOutline && savedDepthWrite) {
  23774. engine.setDepthWrite(true);
  23775. engine.setColorWrite(false);
  23776. scene.getOutlineRenderer().render(subMesh, batch);
  23777. engine.setColorWrite(true);
  23778. }
  23779. // Overlay
  23780. if (this.renderOverlay) {
  23781. var currentMode = engine.getAlphaMode();
  23782. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23783. scene.getOutlineRenderer().render(subMesh, batch, true);
  23784. engine.setAlphaMode(currentMode);
  23785. }
  23786. this.onAfterRenderObservable.notifyObservers(this);
  23787. return this;
  23788. };
  23789. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23790. if (isInstance) {
  23791. effectiveMaterial.bindOnlyWorldMatrix(world);
  23792. }
  23793. return this;
  23794. };
  23795. /**
  23796. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23797. */
  23798. Mesh.prototype.getEmittedParticleSystems = function () {
  23799. var results = new Array();
  23800. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23801. var particleSystem = this.getScene().particleSystems[index];
  23802. if (particleSystem.emitter === this) {
  23803. results.push(particleSystem);
  23804. }
  23805. }
  23806. return results;
  23807. };
  23808. /**
  23809. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23810. */
  23811. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23812. var results = new Array();
  23813. var descendants = this.getDescendants();
  23814. descendants.push(this);
  23815. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23816. var particleSystem = this.getScene().particleSystems[index];
  23817. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  23818. results.push(particleSystem);
  23819. }
  23820. }
  23821. return results;
  23822. };
  23823. Mesh.prototype._checkDelayState = function () {
  23824. var scene = this.getScene();
  23825. if (this._geometry) {
  23826. this._geometry.load(scene);
  23827. }
  23828. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23829. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23830. this._queueLoad(this, scene);
  23831. }
  23832. return this;
  23833. };
  23834. Mesh.prototype._queueLoad = function (mesh, scene) {
  23835. var _this = this;
  23836. scene._addPendingData(mesh);
  23837. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23838. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23839. if (data instanceof ArrayBuffer) {
  23840. _this._delayLoadingFunction(data, _this);
  23841. }
  23842. else {
  23843. _this._delayLoadingFunction(JSON.parse(data), _this);
  23844. }
  23845. _this.instances.forEach(function (instance) {
  23846. instance._syncSubMeshes();
  23847. });
  23848. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23849. scene._removePendingData(_this);
  23850. }, function () { }, scene.database, getBinaryData);
  23851. return this;
  23852. };
  23853. /**
  23854. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23855. */
  23856. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23857. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23858. return false;
  23859. }
  23860. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23861. return false;
  23862. }
  23863. this._checkDelayState();
  23864. return true;
  23865. };
  23866. /**
  23867. * Sets the mesh material by the material or multiMaterial `id` property.
  23868. * The material `id` is a string identifying the material or the multiMaterial.
  23869. * This method returns the Mesh.
  23870. */
  23871. Mesh.prototype.setMaterialByID = function (id) {
  23872. var materials = this.getScene().materials;
  23873. var index;
  23874. for (index = 0; index < materials.length; index++) {
  23875. if (materials[index].id === id) {
  23876. this.material = materials[index];
  23877. return this;
  23878. }
  23879. }
  23880. // Multi
  23881. var multiMaterials = this.getScene().multiMaterials;
  23882. for (index = 0; index < multiMaterials.length; index++) {
  23883. if (multiMaterials[index].id === id) {
  23884. this.material = multiMaterials[index];
  23885. return this;
  23886. }
  23887. }
  23888. return this;
  23889. };
  23890. /**
  23891. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23892. */
  23893. Mesh.prototype.getAnimatables = function () {
  23894. var results = [];
  23895. if (this.material) {
  23896. results.push(this.material);
  23897. }
  23898. if (this.skeleton) {
  23899. results.push(this.skeleton);
  23900. }
  23901. return results;
  23902. };
  23903. /**
  23904. * Modifies the mesh geometry according to the passed transformation matrix.
  23905. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23906. * The mesh normals are modified accordingly the same transformation.
  23907. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23908. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23909. * Returns the Mesh.
  23910. */
  23911. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23912. // Position
  23913. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23914. return this;
  23915. }
  23916. var submeshes = this.subMeshes.splice(0);
  23917. this._resetPointsArrayCache();
  23918. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23919. var temp = [];
  23920. var index;
  23921. for (index = 0; index < data.length; index += 3) {
  23922. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23923. }
  23924. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23925. // Normals
  23926. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23927. return this;
  23928. }
  23929. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23930. temp = [];
  23931. for (index = 0; index < data.length; index += 3) {
  23932. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23933. }
  23934. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23935. // flip faces?
  23936. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23937. this.flipFaces();
  23938. }
  23939. // Restore submeshes
  23940. this.releaseSubMeshes();
  23941. this.subMeshes = submeshes;
  23942. return this;
  23943. };
  23944. /**
  23945. * Modifies the mesh geometry according to its own current World Matrix.
  23946. * The mesh World Matrix is then reset.
  23947. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23948. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23949. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23950. * Returns the Mesh.
  23951. */
  23952. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23953. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23954. this.scaling.copyFromFloats(1, 1, 1);
  23955. this.position.copyFromFloats(0, 0, 0);
  23956. this.rotation.copyFromFloats(0, 0, 0);
  23957. //only if quaternion is already set
  23958. if (this.rotationQuaternion) {
  23959. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23960. }
  23961. this._worldMatrix = BABYLON.Matrix.Identity();
  23962. return this;
  23963. };
  23964. // Cache
  23965. Mesh.prototype._resetPointsArrayCache = function () {
  23966. this._positions = null;
  23967. return this;
  23968. };
  23969. Mesh.prototype._generatePointsArray = function () {
  23970. if (this._positions)
  23971. return true;
  23972. this._positions = [];
  23973. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23974. if (!data) {
  23975. return false;
  23976. }
  23977. for (var index = 0; index < data.length; index += 3) {
  23978. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  23979. }
  23980. return true;
  23981. };
  23982. /**
  23983. * Returns a new Mesh object generated from the current mesh properties.
  23984. * This method must not get confused with createInstance().
  23985. * The parameter `name` is a string, the name given to the new mesh.
  23986. * The optional parameter `newParent` can be any Node object (default `null`).
  23987. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23988. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  23989. */
  23990. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23991. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23992. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23993. };
  23994. /**
  23995. * Disposes the mesh.
  23996. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23997. */
  23998. Mesh.prototype.dispose = function (doNotRecurse) {
  23999. var _this = this;
  24000. if (this._geometry) {
  24001. this._geometry.releaseForMesh(this, true);
  24002. }
  24003. // Sources
  24004. var meshes = this.getScene().meshes;
  24005. meshes.forEach(function (mesh) {
  24006. if (mesh._source && mesh._source === _this) {
  24007. mesh._source = null;
  24008. }
  24009. });
  24010. this._source = null;
  24011. // Instances
  24012. if (this._instancesBuffer) {
  24013. this._instancesBuffer.dispose();
  24014. this._instancesBuffer = null;
  24015. }
  24016. while (this.instances.length) {
  24017. this.instances[0].dispose();
  24018. }
  24019. // Highlight layers.
  24020. var highlightLayers = this.getScene().highlightLayers;
  24021. for (var i = 0; i < highlightLayers.length; i++) {
  24022. var highlightLayer = highlightLayers[i];
  24023. if (highlightLayer) {
  24024. highlightLayer.removeMesh(this);
  24025. highlightLayer.removeExcludedMesh(this);
  24026. }
  24027. }
  24028. _super.prototype.dispose.call(this, doNotRecurse);
  24029. };
  24030. /**
  24031. * Modifies the mesh geometry according to a displacement map.
  24032. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  24033. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24034. * This method returns nothing.
  24035. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24036. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24037. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  24038. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24039. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24040. *
  24041. * Returns the Mesh.
  24042. */
  24043. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24044. var _this = this;
  24045. var scene = this.getScene();
  24046. var onload = function (img) {
  24047. // Getting height map data
  24048. var canvas = document.createElement("canvas");
  24049. var context = canvas.getContext("2d");
  24050. var heightMapWidth = img.width;
  24051. var heightMapHeight = img.height;
  24052. canvas.width = heightMapWidth;
  24053. canvas.height = heightMapHeight;
  24054. context.drawImage(img, 0, 0);
  24055. // Create VertexData from map data
  24056. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24057. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24058. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24059. //execute success callback, if set
  24060. if (onSuccess) {
  24061. onSuccess(_this);
  24062. }
  24063. };
  24064. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24065. return this;
  24066. };
  24067. /**
  24068. * Modifies the mesh geometry according to a displacementMap buffer.
  24069. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  24070. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24071. * This method returns nothing.
  24072. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  24073. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24074. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24075. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24076. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24077. *
  24078. * Returns the Mesh.
  24079. */
  24080. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24081. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24082. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24083. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24084. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24085. return this;
  24086. }
  24087. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24088. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24089. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24090. var position = BABYLON.Vector3.Zero();
  24091. var normal = BABYLON.Vector3.Zero();
  24092. var uv = BABYLON.Vector2.Zero();
  24093. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24094. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24095. for (var index = 0; index < positions.length; index += 3) {
  24096. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24097. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24098. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24099. // Compute height
  24100. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24101. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24102. var pos = (u + v * heightMapWidth) * 4;
  24103. var r = buffer[pos] / 255.0;
  24104. var g = buffer[pos + 1] / 255.0;
  24105. var b = buffer[pos + 2] / 255.0;
  24106. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24107. normal.normalize();
  24108. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24109. position = position.add(normal);
  24110. position.toArray(positions, index);
  24111. }
  24112. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24113. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24114. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24115. return this;
  24116. };
  24117. /**
  24118. * Modify the mesh to get a flat shading rendering.
  24119. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24120. * This method returns the Mesh.
  24121. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24122. */
  24123. Mesh.prototype.convertToFlatShadedMesh = function () {
  24124. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24125. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24126. var kinds = this.getVerticesDataKinds();
  24127. var vbs = [];
  24128. var data = [];
  24129. var newdata = [];
  24130. var updatableNormals = false;
  24131. var kindIndex;
  24132. var kind;
  24133. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24134. kind = kinds[kindIndex];
  24135. var vertexBuffer = this.getVertexBuffer(kind);
  24136. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24137. updatableNormals = vertexBuffer.isUpdatable();
  24138. kinds.splice(kindIndex, 1);
  24139. kindIndex--;
  24140. continue;
  24141. }
  24142. vbs[kind] = vertexBuffer;
  24143. data[kind] = vbs[kind].getData();
  24144. newdata[kind] = [];
  24145. }
  24146. // Save previous submeshes
  24147. var previousSubmeshes = this.subMeshes.slice(0);
  24148. var indices = this.getIndices();
  24149. var totalIndices = this.getTotalIndices();
  24150. // Generating unique vertices per face
  24151. var index;
  24152. for (index = 0; index < totalIndices; index++) {
  24153. var vertexIndex = indices[index];
  24154. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24155. kind = kinds[kindIndex];
  24156. var stride = vbs[kind].getStrideSize();
  24157. for (var offset = 0; offset < stride; offset++) {
  24158. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24159. }
  24160. }
  24161. }
  24162. // Updating faces & normal
  24163. var normals = [];
  24164. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24165. for (index = 0; index < totalIndices; index += 3) {
  24166. indices[index] = index;
  24167. indices[index + 1] = index + 1;
  24168. indices[index + 2] = index + 2;
  24169. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24170. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24171. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24172. var p1p2 = p1.subtract(p2);
  24173. var p3p2 = p3.subtract(p2);
  24174. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24175. // Store same normals for every vertex
  24176. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24177. normals.push(normal.x);
  24178. normals.push(normal.y);
  24179. normals.push(normal.z);
  24180. }
  24181. }
  24182. this.setIndices(indices);
  24183. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24184. // Updating vertex buffers
  24185. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24186. kind = kinds[kindIndex];
  24187. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24188. }
  24189. // Updating submeshes
  24190. this.releaseSubMeshes();
  24191. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24192. var previousOne = previousSubmeshes[submeshIndex];
  24193. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24194. }
  24195. this.synchronizeInstances();
  24196. return this;
  24197. };
  24198. /**
  24199. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24200. * In other words, more vertices, no more indices and a single bigger VBO.
  24201. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24202. * Returns the Mesh.
  24203. */
  24204. Mesh.prototype.convertToUnIndexedMesh = function () {
  24205. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24206. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24207. var kinds = this.getVerticesDataKinds();
  24208. var vbs = [];
  24209. var data = [];
  24210. var newdata = [];
  24211. var updatableNormals = false;
  24212. var kindIndex;
  24213. var kind;
  24214. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24215. kind = kinds[kindIndex];
  24216. var vertexBuffer = this.getVertexBuffer(kind);
  24217. vbs[kind] = vertexBuffer;
  24218. data[kind] = vbs[kind].getData();
  24219. newdata[kind] = [];
  24220. }
  24221. // Save previous submeshes
  24222. var previousSubmeshes = this.subMeshes.slice(0);
  24223. var indices = this.getIndices();
  24224. var totalIndices = this.getTotalIndices();
  24225. // Generating unique vertices per face
  24226. var index;
  24227. for (index = 0; index < totalIndices; index++) {
  24228. var vertexIndex = indices[index];
  24229. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24230. kind = kinds[kindIndex];
  24231. var stride = vbs[kind].getStrideSize();
  24232. for (var offset = 0; offset < stride; offset++) {
  24233. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24234. }
  24235. }
  24236. }
  24237. // Updating indices
  24238. for (index = 0; index < totalIndices; index += 3) {
  24239. indices[index] = index;
  24240. indices[index + 1] = index + 1;
  24241. indices[index + 2] = index + 2;
  24242. }
  24243. this.setIndices(indices);
  24244. // Updating vertex buffers
  24245. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24246. kind = kinds[kindIndex];
  24247. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24248. }
  24249. // Updating submeshes
  24250. this.releaseSubMeshes();
  24251. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24252. var previousOne = previousSubmeshes[submeshIndex];
  24253. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24254. }
  24255. this._unIndexed = true;
  24256. this.synchronizeInstances();
  24257. return this;
  24258. };
  24259. /**
  24260. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24261. * This method returns the Mesh.
  24262. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24263. */
  24264. Mesh.prototype.flipFaces = function (flipNormals) {
  24265. if (flipNormals === void 0) { flipNormals = false; }
  24266. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24267. var i;
  24268. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24269. for (i = 0; i < vertex_data.normals.length; i++) {
  24270. vertex_data.normals[i] *= -1;
  24271. }
  24272. }
  24273. var temp;
  24274. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24275. // reassign indices
  24276. temp = vertex_data.indices[i + 1];
  24277. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24278. vertex_data.indices[i + 2] = temp;
  24279. }
  24280. vertex_data.applyToMesh(this);
  24281. return this;
  24282. };
  24283. // Instances
  24284. /**
  24285. * Creates a new InstancedMesh object from the mesh model.
  24286. * An instance shares the same properties and the same material than its model.
  24287. * Only these properties of each instance can then be set individually :
  24288. * - position
  24289. * - rotation
  24290. * - rotationQuaternion
  24291. * - setPivotMatrix
  24292. * - scaling
  24293. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24294. * Warning : this method is not supported for Line mesh and LineSystem
  24295. */
  24296. Mesh.prototype.createInstance = function (name) {
  24297. return new BABYLON.InstancedMesh(name, this);
  24298. };
  24299. /**
  24300. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24301. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24302. * This method returns the Mesh.
  24303. */
  24304. Mesh.prototype.synchronizeInstances = function () {
  24305. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24306. var instance = this.instances[instanceIndex];
  24307. instance._syncSubMeshes();
  24308. }
  24309. return this;
  24310. };
  24311. /**
  24312. * Simplify the mesh according to the given array of settings.
  24313. * Function will return immediately and will simplify async. It returns the Mesh.
  24314. * @param settings a collection of simplification settings.
  24315. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24316. * @param type the type of simplification to run.
  24317. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24318. */
  24319. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24320. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24321. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24322. this.getScene().simplificationQueue.addTask({
  24323. settings: settings,
  24324. parallelProcessing: parallelProcessing,
  24325. mesh: this,
  24326. simplificationType: simplificationType,
  24327. successCallback: successCallback
  24328. });
  24329. return this;
  24330. };
  24331. /**
  24332. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24333. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24334. * This should be used together with the simplification to avoid disappearing triangles.
  24335. * Returns the Mesh.
  24336. * @param successCallback an optional success callback to be called after the optimization finished.
  24337. */
  24338. Mesh.prototype.optimizeIndices = function (successCallback) {
  24339. var _this = this;
  24340. var indices = this.getIndices();
  24341. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24342. var vectorPositions = [];
  24343. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24344. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24345. }
  24346. var dupes = [];
  24347. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24348. var realPos = vectorPositions.length - 1 - iteration;
  24349. var testedPosition = vectorPositions[realPos];
  24350. for (var j = 0; j < realPos; ++j) {
  24351. var againstPosition = vectorPositions[j];
  24352. if (testedPosition.equals(againstPosition)) {
  24353. dupes[realPos] = j;
  24354. break;
  24355. }
  24356. }
  24357. }, function () {
  24358. for (var i = 0; i < indices.length; ++i) {
  24359. indices[i] = dupes[indices[i]] || indices[i];
  24360. }
  24361. //indices are now reordered
  24362. var originalSubMeshes = _this.subMeshes.slice(0);
  24363. _this.setIndices(indices);
  24364. _this.subMeshes = originalSubMeshes;
  24365. if (successCallback) {
  24366. successCallback(_this);
  24367. }
  24368. });
  24369. return this;
  24370. };
  24371. Mesh.prototype.serialize = function (serializationObject) {
  24372. serializationObject.name = this.name;
  24373. serializationObject.id = this.id;
  24374. serializationObject.type = this.getClassName();
  24375. if (BABYLON.Tags.HasTags(this)) {
  24376. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24377. }
  24378. serializationObject.position = this.position.asArray();
  24379. if (this.rotationQuaternion) {
  24380. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24381. }
  24382. else if (this.rotation) {
  24383. serializationObject.rotation = this.rotation.asArray();
  24384. }
  24385. serializationObject.scaling = this.scaling.asArray();
  24386. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24387. serializationObject.isEnabled = this.isEnabled();
  24388. serializationObject.isVisible = this.isVisible;
  24389. serializationObject.infiniteDistance = this.infiniteDistance;
  24390. serializationObject.pickable = this.isPickable;
  24391. serializationObject.receiveShadows = this.receiveShadows;
  24392. serializationObject.billboardMode = this.billboardMode;
  24393. serializationObject.visibility = this.visibility;
  24394. serializationObject.checkCollisions = this.checkCollisions;
  24395. serializationObject.isBlocker = this.isBlocker;
  24396. // Parent
  24397. if (this.parent) {
  24398. serializationObject.parentId = this.parent.id;
  24399. }
  24400. // Geometry
  24401. var geometry = this._geometry;
  24402. if (geometry) {
  24403. var geometryId = geometry.id;
  24404. serializationObject.geometryId = geometryId;
  24405. // SubMeshes
  24406. serializationObject.subMeshes = [];
  24407. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24408. var subMesh = this.subMeshes[subIndex];
  24409. serializationObject.subMeshes.push({
  24410. materialIndex: subMesh.materialIndex,
  24411. verticesStart: subMesh.verticesStart,
  24412. verticesCount: subMesh.verticesCount,
  24413. indexStart: subMesh.indexStart,
  24414. indexCount: subMesh.indexCount
  24415. });
  24416. }
  24417. }
  24418. // Material
  24419. if (this.material) {
  24420. serializationObject.materialId = this.material.id;
  24421. }
  24422. else {
  24423. this.material = null;
  24424. }
  24425. // Skeleton
  24426. if (this.skeleton) {
  24427. serializationObject.skeletonId = this.skeleton.id;
  24428. }
  24429. // Physics
  24430. //TODO implement correct serialization for physics impostors.
  24431. if (this.getPhysicsImpostor()) {
  24432. var impostor = this.getPhysicsImpostor();
  24433. serializationObject.physicsMass = impostor.getParam("mass");
  24434. serializationObject.physicsFriction = impostor.getParam("friction");
  24435. serializationObject.physicsRestitution = impostor.getParam("mass");
  24436. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  24437. }
  24438. // Metadata
  24439. if (this.metadata) {
  24440. serializationObject.metadata = this.metadata;
  24441. }
  24442. // Instances
  24443. serializationObject.instances = [];
  24444. for (var index = 0; index < this.instances.length; index++) {
  24445. var instance = this.instances[index];
  24446. var serializationInstance = {
  24447. name: instance.name,
  24448. position: instance.position.asArray(),
  24449. scaling: instance.scaling.asArray()
  24450. };
  24451. if (instance.rotationQuaternion) {
  24452. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24453. }
  24454. else if (instance.rotation) {
  24455. serializationInstance.rotation = instance.rotation.asArray();
  24456. }
  24457. serializationObject.instances.push(serializationInstance);
  24458. // Animations
  24459. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24460. serializationInstance.ranges = instance.serializeAnimationRanges();
  24461. }
  24462. // Animations
  24463. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24464. serializationObject.ranges = this.serializeAnimationRanges();
  24465. // Layer mask
  24466. serializationObject.layerMask = this.layerMask;
  24467. // Alpha
  24468. serializationObject.alphaIndex = this.alphaIndex;
  24469. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24470. // Overlay
  24471. serializationObject.overlayAlpha = this.overlayAlpha;
  24472. serializationObject.overlayColor = this.overlayColor.asArray();
  24473. serializationObject.renderOverlay = this.renderOverlay;
  24474. // Fog
  24475. serializationObject.applyFog = this.applyFog;
  24476. // Action Manager
  24477. if (this.actionManager) {
  24478. serializationObject.actions = this.actionManager.serialize(this.name);
  24479. }
  24480. };
  24481. // Statics
  24482. /**
  24483. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24484. * The parameter `parsedMesh` is the mesh to be copied.
  24485. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24486. */
  24487. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24488. var mesh;
  24489. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24490. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24491. }
  24492. else {
  24493. mesh = new Mesh(parsedMesh.name, scene);
  24494. }
  24495. mesh.id = parsedMesh.id;
  24496. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24497. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24498. if (parsedMesh.metadata !== undefined) {
  24499. mesh.metadata = parsedMesh.metadata;
  24500. }
  24501. if (parsedMesh.rotationQuaternion) {
  24502. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24503. }
  24504. else if (parsedMesh.rotation) {
  24505. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24506. }
  24507. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24508. if (parsedMesh.localMatrix) {
  24509. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24510. }
  24511. else if (parsedMesh.pivotMatrix) {
  24512. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24513. }
  24514. mesh.setEnabled(parsedMesh.isEnabled);
  24515. mesh.isVisible = parsedMesh.isVisible;
  24516. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24517. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24518. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24519. if (parsedMesh.applyFog !== undefined) {
  24520. mesh.applyFog = parsedMesh.applyFog;
  24521. }
  24522. if (parsedMesh.pickable !== undefined) {
  24523. mesh.isPickable = parsedMesh.pickable;
  24524. }
  24525. if (parsedMesh.alphaIndex !== undefined) {
  24526. mesh.alphaIndex = parsedMesh.alphaIndex;
  24527. }
  24528. mesh.receiveShadows = parsedMesh.receiveShadows;
  24529. mesh.billboardMode = parsedMesh.billboardMode;
  24530. if (parsedMesh.visibility !== undefined) {
  24531. mesh.visibility = parsedMesh.visibility;
  24532. }
  24533. mesh.checkCollisions = parsedMesh.checkCollisions;
  24534. if (parsedMesh.isBlocker !== undefined) {
  24535. mesh.isBlocker = parsedMesh.isBlocker;
  24536. }
  24537. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24538. // freezeWorldMatrix
  24539. if (parsedMesh.freezeWorldMatrix) {
  24540. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24541. }
  24542. // Parent
  24543. if (parsedMesh.parentId) {
  24544. mesh._waitingParentId = parsedMesh.parentId;
  24545. }
  24546. // Actions
  24547. if (parsedMesh.actions !== undefined) {
  24548. mesh._waitingActions = parsedMesh.actions;
  24549. }
  24550. // Overlay
  24551. if (parsedMesh.overlayAlpha !== undefined) {
  24552. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24553. }
  24554. if (parsedMesh.overlayColor !== undefined) {
  24555. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24556. }
  24557. if (parsedMesh.renderOverlay !== undefined) {
  24558. mesh.renderOverlay = parsedMesh.renderOverlay;
  24559. }
  24560. // Geometry
  24561. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24562. if (parsedMesh.delayLoadingFile) {
  24563. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24564. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24565. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24566. if (parsedMesh._binaryInfo) {
  24567. mesh._binaryInfo = parsedMesh._binaryInfo;
  24568. }
  24569. mesh._delayInfo = [];
  24570. if (parsedMesh.hasUVs) {
  24571. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24572. }
  24573. if (parsedMesh.hasUVs2) {
  24574. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24575. }
  24576. if (parsedMesh.hasUVs3) {
  24577. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24578. }
  24579. if (parsedMesh.hasUVs4) {
  24580. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24581. }
  24582. if (parsedMesh.hasUVs5) {
  24583. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24584. }
  24585. if (parsedMesh.hasUVs6) {
  24586. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24587. }
  24588. if (parsedMesh.hasColors) {
  24589. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24590. }
  24591. if (parsedMesh.hasMatricesIndices) {
  24592. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24593. }
  24594. if (parsedMesh.hasMatricesWeights) {
  24595. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24596. }
  24597. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24598. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24599. mesh._checkDelayState();
  24600. }
  24601. }
  24602. else {
  24603. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24604. }
  24605. // Material
  24606. if (parsedMesh.materialId) {
  24607. mesh.setMaterialByID(parsedMesh.materialId);
  24608. }
  24609. else {
  24610. mesh.material = null;
  24611. }
  24612. // Skeleton
  24613. if (parsedMesh.skeletonId > -1) {
  24614. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24615. if (parsedMesh.numBoneInfluencers) {
  24616. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24617. }
  24618. }
  24619. // Animations
  24620. if (parsedMesh.animations) {
  24621. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24622. var parsedAnimation = parsedMesh.animations[animationIndex];
  24623. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24624. }
  24625. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24626. }
  24627. if (parsedMesh.autoAnimate) {
  24628. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24629. }
  24630. // Layer Mask
  24631. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24632. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24633. }
  24634. else {
  24635. mesh.layerMask = 0x0FFFFFFF;
  24636. }
  24637. // Physics
  24638. if (parsedMesh.physicsImpostor) {
  24639. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24640. mass: parsedMesh.physicsMass,
  24641. friction: parsedMesh.physicsFriction,
  24642. restitution: parsedMesh.physicsRestitution
  24643. }, scene);
  24644. }
  24645. // Instances
  24646. if (parsedMesh.instances) {
  24647. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24648. var parsedInstance = parsedMesh.instances[index];
  24649. var instance = mesh.createInstance(parsedInstance.name);
  24650. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24651. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24652. if (parsedInstance.parentId) {
  24653. instance._waitingParentId = parsedInstance.parentId;
  24654. }
  24655. if (parsedInstance.rotationQuaternion) {
  24656. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24657. }
  24658. else if (parsedInstance.rotation) {
  24659. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24660. }
  24661. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24662. instance.checkCollisions = mesh.checkCollisions;
  24663. if (parsedMesh.animations) {
  24664. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24665. parsedAnimation = parsedMesh.animations[animationIndex];
  24666. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24667. }
  24668. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24669. }
  24670. }
  24671. }
  24672. return mesh;
  24673. };
  24674. /**
  24675. * Creates a ribbon mesh.
  24676. * Please consider using the same method from the MeshBuilder class instead.
  24677. * 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.
  24678. *
  24679. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24680. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24681. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24682. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24683. * 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.
  24684. * 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.
  24685. * 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
  24686. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24687. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24689. */
  24690. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24691. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24692. pathArray: pathArray,
  24693. closeArray: closeArray,
  24694. closePath: closePath,
  24695. offset: offset,
  24696. updatable: updatable,
  24697. sideOrientation: sideOrientation,
  24698. instance: instance
  24699. }, scene);
  24700. };
  24701. /**
  24702. * Creates a plane polygonal mesh. By default, this is a disc.
  24703. * Please consider using the same method from the MeshBuilder class instead.
  24704. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24705. * 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.
  24706. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24707. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24708. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24709. */
  24710. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24711. var options = {
  24712. radius: radius,
  24713. tessellation: tessellation,
  24714. sideOrientation: sideOrientation,
  24715. updatable: updatable
  24716. };
  24717. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24718. };
  24719. /**
  24720. * Creates a box mesh.
  24721. * Please consider using the same method from the MeshBuilder class instead.
  24722. * The parameter `size` sets the size (float) of each box side (default 1).
  24723. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24724. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24726. */
  24727. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24728. var options = {
  24729. size: size,
  24730. sideOrientation: sideOrientation,
  24731. updatable: updatable
  24732. };
  24733. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24734. };
  24735. /**
  24736. * Creates a sphere mesh.
  24737. * Please consider using the same method from the MeshBuilder class instead.
  24738. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24739. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24740. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24741. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24743. */
  24744. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24745. var options = {
  24746. segments: segments,
  24747. diameterX: diameter,
  24748. diameterY: diameter,
  24749. diameterZ: diameter,
  24750. sideOrientation: sideOrientation,
  24751. updatable: updatable
  24752. };
  24753. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24754. };
  24755. /**
  24756. * Creates a cylinder or a cone mesh.
  24757. * Please consider using the same method from the MeshBuilder class instead.
  24758. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24759. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24760. * 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.
  24761. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24762. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24763. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24764. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24765. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24766. */
  24767. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24768. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24769. if (scene !== undefined) {
  24770. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24771. updatable = scene;
  24772. }
  24773. scene = subdivisions;
  24774. subdivisions = 1;
  24775. }
  24776. var options = {
  24777. height: height,
  24778. diameterTop: diameterTop,
  24779. diameterBottom: diameterBottom,
  24780. tessellation: tessellation,
  24781. subdivisions: subdivisions,
  24782. sideOrientation: sideOrientation,
  24783. updatable: updatable
  24784. };
  24785. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24786. };
  24787. // Torus (Code from SharpDX.org)
  24788. /**
  24789. * Creates a torus mesh.
  24790. * Please consider using the same method from the MeshBuilder class instead.
  24791. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24792. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24793. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24794. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24795. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24796. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24797. */
  24798. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24799. var options = {
  24800. diameter: diameter,
  24801. thickness: thickness,
  24802. tessellation: tessellation,
  24803. sideOrientation: sideOrientation,
  24804. updatable: updatable
  24805. };
  24806. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24807. };
  24808. /**
  24809. * Creates a torus knot mesh.
  24810. * Please consider using the same method from the MeshBuilder class instead.
  24811. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24812. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24813. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24814. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24815. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24816. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24817. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24818. */
  24819. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24820. var options = {
  24821. radius: radius,
  24822. tube: tube,
  24823. radialSegments: radialSegments,
  24824. tubularSegments: tubularSegments,
  24825. p: p,
  24826. q: q,
  24827. sideOrientation: sideOrientation,
  24828. updatable: updatable
  24829. };
  24830. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24831. };
  24832. /**
  24833. * Creates a line mesh.
  24834. * Please consider using the same method from the MeshBuilder class instead.
  24835. * 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.
  24836. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24837. * The parameter `points` is an array successive Vector3.
  24838. * 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
  24839. * When updating an instance, remember that only point positions can change, not the number of points.
  24840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24841. */
  24842. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24843. var options = {
  24844. points: points,
  24845. updatable: updatable,
  24846. instance: instance
  24847. };
  24848. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24849. };
  24850. /**
  24851. * Creates a dashed line mesh.
  24852. * Please consider using the same method from the MeshBuilder class instead.
  24853. * 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.
  24854. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24855. * The parameter `points` is an array successive Vector3.
  24856. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24857. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24858. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24859. * 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
  24860. * When updating an instance, remember that only point positions can change, not the number of points.
  24861. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24862. */
  24863. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24864. var options = {
  24865. points: points,
  24866. dashSize: dashSize,
  24867. gapSize: gapSize,
  24868. dashNb: dashNb,
  24869. updatable: updatable,
  24870. instance: instance
  24871. };
  24872. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24873. };
  24874. /**
  24875. * Creates an extruded shape mesh.
  24876. * 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.
  24877. * Please consider using the same method from the MeshBuilder class instead.
  24878. *
  24879. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24880. * 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
  24881. * extruded along the Z axis.
  24882. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24883. * 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.
  24884. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24885. * 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
  24886. * 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
  24887. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24888. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24889. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24891. */
  24892. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24893. var options = {
  24894. shape: shape,
  24895. path: path,
  24896. scale: scale,
  24897. rotation: rotation,
  24898. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24899. sideOrientation: sideOrientation,
  24900. instance: instance,
  24901. updatable: updatable
  24902. };
  24903. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24904. };
  24905. /**
  24906. * Creates an custom extruded shape mesh.
  24907. * 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.
  24908. * Please consider using the same method from the MeshBuilder class instead.
  24909. *
  24910. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24911. * 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
  24912. * extruded along the Z axis.
  24913. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24914. * 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
  24915. * and the distance of this point from the begining of the path :
  24916. * ```javascript
  24917. * var rotationFunction = function(i, distance) {
  24918. * // do things
  24919. * return rotationValue; }
  24920. * ```
  24921. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24922. * 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
  24923. * and the distance of this point from the begining of the path :
  24924. * ```javascript
  24925. * var scaleFunction = function(i, distance) {
  24926. * // do things
  24927. * return scaleValue;}
  24928. * ```
  24929. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24930. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24931. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24932. * 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
  24933. * 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
  24934. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24935. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24936. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24938. */
  24939. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24940. var options = {
  24941. shape: shape,
  24942. path: path,
  24943. scaleFunction: scaleFunction,
  24944. rotationFunction: rotationFunction,
  24945. ribbonCloseArray: ribbonCloseArray,
  24946. ribbonClosePath: ribbonClosePath,
  24947. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24948. sideOrientation: sideOrientation,
  24949. instance: instance,
  24950. updatable: updatable
  24951. };
  24952. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24953. };
  24954. /**
  24955. * Creates lathe mesh.
  24956. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24957. * Please consider using the same method from the MeshBuilder class instead.
  24958. * 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
  24959. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24960. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24961. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24962. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24963. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24964. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24965. */
  24966. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24967. var options = {
  24968. shape: shape,
  24969. radius: radius,
  24970. tessellation: tessellation,
  24971. sideOrientation: sideOrientation,
  24972. updatable: updatable
  24973. };
  24974. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24975. };
  24976. /**
  24977. * Creates a plane mesh.
  24978. * Please consider using the same method from the MeshBuilder class instead.
  24979. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24980. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24981. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24982. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24983. */
  24984. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24985. var options = {
  24986. size: size,
  24987. width: size,
  24988. height: size,
  24989. sideOrientation: sideOrientation,
  24990. updatable: updatable
  24991. };
  24992. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24993. };
  24994. /**
  24995. * Creates a ground mesh.
  24996. * Please consider using the same method from the MeshBuilder class instead.
  24997. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24998. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25000. */
  25001. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25002. var options = {
  25003. width: width,
  25004. height: height,
  25005. subdivisions: subdivisions,
  25006. updatable: updatable
  25007. };
  25008. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25009. };
  25010. /**
  25011. * Creates a tiled ground mesh.
  25012. * Please consider using the same method from the MeshBuilder class instead.
  25013. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25014. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25015. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25016. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25017. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25018. * numbers of subdivisions on the ground width and height of each tile.
  25019. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25020. */
  25021. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25022. var options = {
  25023. xmin: xmin,
  25024. zmin: zmin,
  25025. xmax: xmax,
  25026. zmax: zmax,
  25027. subdivisions: subdivisions,
  25028. precision: precision,
  25029. updatable: updatable
  25030. };
  25031. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25032. };
  25033. /**
  25034. * Creates a ground mesh from a height map.
  25035. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25036. * Please consider using the same method from the MeshBuilder class instead.
  25037. * The parameter `url` sets the URL of the height map image resource.
  25038. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25039. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25040. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25041. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25042. * 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).
  25043. * This function is passed the newly built mesh :
  25044. * ```javascript
  25045. * function(mesh) { // do things
  25046. * return; }
  25047. * ```
  25048. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25049. */
  25050. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25051. var options = {
  25052. width: width,
  25053. height: height,
  25054. subdivisions: subdivisions,
  25055. minHeight: minHeight,
  25056. maxHeight: maxHeight,
  25057. updatable: updatable,
  25058. onReady: onReady
  25059. };
  25060. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25061. };
  25062. /**
  25063. * Creates a tube mesh.
  25064. * 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.
  25065. * Please consider using the same method from the MeshBuilder class instead.
  25066. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25067. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25068. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25069. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25070. * 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.
  25071. * It must return a radius value (positive float) :
  25072. * ```javascript
  25073. * var radiusFunction = function(i, distance) {
  25074. * // do things
  25075. * return radius; }
  25076. * ```
  25077. * 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
  25078. * 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
  25079. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25080. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25082. */
  25083. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25084. var options = {
  25085. path: path,
  25086. radius: radius,
  25087. tessellation: tessellation,
  25088. radiusFunction: radiusFunction,
  25089. arc: 1,
  25090. cap: cap,
  25091. updatable: updatable,
  25092. sideOrientation: sideOrientation,
  25093. instance: instance
  25094. };
  25095. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25096. };
  25097. /**
  25098. * Creates a polyhedron mesh.
  25099. * Please consider using the same method from the MeshBuilder class instead.
  25100. * 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
  25101. * to choose the wanted type.
  25102. * The parameter `size` (positive float, default 1) sets the polygon size.
  25103. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25104. * 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`.
  25105. * 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
  25106. * 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)`).
  25107. * 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
  25108. * 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.
  25109. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25110. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25112. */
  25113. Mesh.CreatePolyhedron = function (name, options, scene) {
  25114. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25115. };
  25116. /**
  25117. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25118. * Please consider using the same method from the MeshBuilder class instead.
  25119. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25120. * 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`).
  25121. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25122. * 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.
  25123. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25124. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25125. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25126. */
  25127. Mesh.CreateIcoSphere = function (name, options, scene) {
  25128. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25129. };
  25130. /**
  25131. * Creates a decal mesh.
  25132. * Please consider using the same method from the MeshBuilder class instead.
  25133. * 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.
  25134. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25135. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25136. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25137. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25138. */
  25139. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25140. var options = {
  25141. position: position,
  25142. normal: normal,
  25143. size: size,
  25144. angle: angle
  25145. };
  25146. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25147. };
  25148. // Skeletons
  25149. /**
  25150. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25151. */
  25152. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25153. var source;
  25154. if (!this._sourcePositions) {
  25155. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25156. this._sourcePositions = new Float32Array(source);
  25157. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  25158. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25159. }
  25160. }
  25161. return this._sourcePositions;
  25162. };
  25163. /**
  25164. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25165. */
  25166. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25167. var source;
  25168. if (!this._sourceNormals) {
  25169. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25170. this._sourceNormals = new Float32Array(source);
  25171. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  25172. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25173. }
  25174. }
  25175. return this._sourceNormals;
  25176. };
  25177. /**
  25178. * Updates the vertex buffer by applying transformation from the bones.
  25179. * Returns the Mesh.
  25180. *
  25181. * @param {skeleton} skeleton to apply
  25182. */
  25183. Mesh.prototype.applySkeleton = function (skeleton) {
  25184. if (!this.geometry) {
  25185. return this;
  25186. }
  25187. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25188. return this;
  25189. }
  25190. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25191. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25192. return this;
  25193. }
  25194. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25195. return this;
  25196. }
  25197. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25198. return this;
  25199. }
  25200. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25201. return this;
  25202. }
  25203. if (!this._sourcePositions) {
  25204. var submeshes = this.subMeshes.slice();
  25205. this.setPositionsForCPUSkinning();
  25206. this.subMeshes = submeshes;
  25207. }
  25208. if (!this._sourceNormals) {
  25209. this.setNormalsForCPUSkinning();
  25210. }
  25211. // positionsData checks for not being Float32Array will only pass at most once
  25212. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25213. if (!(positionsData instanceof Float32Array)) {
  25214. positionsData = new Float32Array(positionsData);
  25215. }
  25216. // normalsData checks for not being Float32Array will only pass at most once
  25217. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25218. if (!(normalsData instanceof Float32Array)) {
  25219. normalsData = new Float32Array(normalsData);
  25220. }
  25221. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25222. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25223. var needExtras = this.numBoneInfluencers > 4;
  25224. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25225. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25226. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25227. var tempVector3 = BABYLON.Vector3.Zero();
  25228. var finalMatrix = new BABYLON.Matrix();
  25229. var tempMatrix = new BABYLON.Matrix();
  25230. var matWeightIdx = 0;
  25231. var inf;
  25232. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25233. var weight;
  25234. for (inf = 0; inf < 4; inf++) {
  25235. weight = matricesWeightsData[matWeightIdx + inf];
  25236. if (weight > 0) {
  25237. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25238. finalMatrix.addToSelf(tempMatrix);
  25239. }
  25240. else
  25241. break;
  25242. }
  25243. if (needExtras) {
  25244. for (inf = 0; inf < 4; inf++) {
  25245. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25246. if (weight > 0) {
  25247. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25248. finalMatrix.addToSelf(tempMatrix);
  25249. }
  25250. else
  25251. break;
  25252. }
  25253. }
  25254. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25255. tempVector3.toArray(positionsData, index);
  25256. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25257. tempVector3.toArray(normalsData, index);
  25258. finalMatrix.reset();
  25259. }
  25260. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25261. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25262. return this;
  25263. };
  25264. // Tools
  25265. /**
  25266. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25267. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25268. */
  25269. Mesh.MinMax = function (meshes) {
  25270. var minVector = null;
  25271. var maxVector = null;
  25272. meshes.forEach(function (mesh, index, array) {
  25273. var boundingBox = mesh.getBoundingInfo().boundingBox;
  25274. if (!minVector) {
  25275. minVector = boundingBox.minimumWorld;
  25276. maxVector = boundingBox.maximumWorld;
  25277. }
  25278. else {
  25279. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25280. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25281. }
  25282. });
  25283. return {
  25284. min: minVector,
  25285. max: maxVector
  25286. };
  25287. };
  25288. /**
  25289. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25290. */
  25291. Mesh.Center = function (meshesOrMinMaxVector) {
  25292. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25293. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25294. };
  25295. /**
  25296. * Merge the array of meshes into a single mesh for performance reasons.
  25297. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25298. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25299. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25300. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25301. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25302. */
  25303. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25304. if (disposeSource === void 0) { disposeSource = true; }
  25305. var index;
  25306. if (!allow32BitsIndices) {
  25307. var totalVertices = 0;
  25308. // Counting vertices
  25309. for (index = 0; index < meshes.length; index++) {
  25310. if (meshes[index]) {
  25311. totalVertices += meshes[index].getTotalVertices();
  25312. if (totalVertices > 65536) {
  25313. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25314. return null;
  25315. }
  25316. }
  25317. }
  25318. }
  25319. // Merge
  25320. var vertexData;
  25321. var otherVertexData;
  25322. var indiceArray = new Array();
  25323. var source;
  25324. for (index = 0; index < meshes.length; index++) {
  25325. if (meshes[index]) {
  25326. meshes[index].computeWorldMatrix(true);
  25327. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25328. otherVertexData.transform(meshes[index].getWorldMatrix());
  25329. if (vertexData) {
  25330. vertexData.merge(otherVertexData);
  25331. }
  25332. else {
  25333. vertexData = otherVertexData;
  25334. source = meshes[index];
  25335. }
  25336. if (subdivideWithSubMeshes) {
  25337. indiceArray.push(meshes[index].getTotalIndices());
  25338. }
  25339. }
  25340. }
  25341. if (!meshSubclass) {
  25342. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25343. }
  25344. vertexData.applyToMesh(meshSubclass);
  25345. // Setting properties
  25346. meshSubclass.material = source.material;
  25347. meshSubclass.checkCollisions = source.checkCollisions;
  25348. // Cleaning
  25349. if (disposeSource) {
  25350. for (index = 0; index < meshes.length; index++) {
  25351. if (meshes[index]) {
  25352. meshes[index].dispose();
  25353. }
  25354. }
  25355. }
  25356. // Subdivide
  25357. if (subdivideWithSubMeshes) {
  25358. //-- Suppresions du submesh global
  25359. meshSubclass.releaseSubMeshes();
  25360. index = 0;
  25361. var offset = 0;
  25362. //-- aplique la subdivision en fonction du tableau d'indices
  25363. while (index < indiceArray.length) {
  25364. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25365. offset += indiceArray[index];
  25366. index++;
  25367. }
  25368. }
  25369. return meshSubclass;
  25370. };
  25371. return Mesh;
  25372. }(BABYLON.AbstractMesh));
  25373. // Consts
  25374. Mesh._FRONTSIDE = 0;
  25375. Mesh._BACKSIDE = 1;
  25376. Mesh._DOUBLESIDE = 2;
  25377. Mesh._DEFAULTSIDE = 0;
  25378. Mesh._NO_CAP = 0;
  25379. Mesh._CAP_START = 1;
  25380. Mesh._CAP_END = 2;
  25381. Mesh._CAP_ALL = 3;
  25382. BABYLON.Mesh = Mesh;
  25383. })(BABYLON || (BABYLON = {}));
  25384. //# sourceMappingURL=babylon.mesh.js.map
  25385. var BABYLON;
  25386. (function (BABYLON) {
  25387. var SubMesh = (function () {
  25388. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25389. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25390. this.materialIndex = materialIndex;
  25391. this.verticesStart = verticesStart;
  25392. this.verticesCount = verticesCount;
  25393. this.indexStart = indexStart;
  25394. this.indexCount = indexCount;
  25395. this._renderId = 0;
  25396. this._mesh = mesh;
  25397. this._renderingMesh = renderingMesh || mesh;
  25398. mesh.subMeshes.push(this);
  25399. this._trianglePlanes = [];
  25400. this._id = mesh.subMeshes.length - 1;
  25401. if (createBoundingBox) {
  25402. this.refreshBoundingInfo();
  25403. mesh.computeWorldMatrix(true);
  25404. }
  25405. }
  25406. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25407. get: function () {
  25408. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25409. },
  25410. enumerable: true,
  25411. configurable: true
  25412. });
  25413. /**
  25414. * Returns the submesh BoudingInfo object.
  25415. */
  25416. SubMesh.prototype.getBoundingInfo = function () {
  25417. if (this.IsGlobal) {
  25418. return this._mesh.getBoundingInfo();
  25419. }
  25420. return this._boundingInfo;
  25421. };
  25422. /**
  25423. * Sets the submesh BoundingInfo.
  25424. * Return the SubMesh.
  25425. */
  25426. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25427. this._boundingInfo = boundingInfo;
  25428. return this;
  25429. };
  25430. /**
  25431. * Returns the mesh of the current submesh.
  25432. */
  25433. SubMesh.prototype.getMesh = function () {
  25434. return this._mesh;
  25435. };
  25436. /**
  25437. * Returns the rendering mesh of the submesh.
  25438. */
  25439. SubMesh.prototype.getRenderingMesh = function () {
  25440. return this._renderingMesh;
  25441. };
  25442. /**
  25443. * Returns the submesh material.
  25444. */
  25445. SubMesh.prototype.getMaterial = function () {
  25446. var rootMaterial = this._renderingMesh.material;
  25447. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  25448. var multiMaterial = rootMaterial;
  25449. return multiMaterial.getSubMaterial(this.materialIndex);
  25450. }
  25451. if (!rootMaterial) {
  25452. return this._mesh.getScene().defaultMaterial;
  25453. }
  25454. return rootMaterial;
  25455. };
  25456. // Methods
  25457. /**
  25458. * Sets a new updated BoundingInfo object to the submesh.
  25459. * Returns the SubMesh.
  25460. */
  25461. SubMesh.prototype.refreshBoundingInfo = function () {
  25462. this._lastColliderWorldVertices = null;
  25463. if (this.IsGlobal) {
  25464. return;
  25465. }
  25466. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25467. if (!data) {
  25468. this._boundingInfo = this._mesh._boundingInfo;
  25469. return;
  25470. }
  25471. var indices = this._renderingMesh.getIndices();
  25472. var extend;
  25473. //is this the only submesh?
  25474. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25475. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25476. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  25477. }
  25478. else {
  25479. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25480. }
  25481. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25482. return this;
  25483. };
  25484. SubMesh.prototype._checkCollision = function (collider) {
  25485. return this.getBoundingInfo()._checkCollision(collider);
  25486. };
  25487. /**
  25488. * Updates the submesh BoundingInfo.
  25489. * Returns the Submesh.
  25490. */
  25491. SubMesh.prototype.updateBoundingInfo = function (world) {
  25492. if (!this.getBoundingInfo()) {
  25493. this.refreshBoundingInfo();
  25494. }
  25495. this.getBoundingInfo().update(world);
  25496. return this;
  25497. };
  25498. /**
  25499. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25500. * Boolean returned.
  25501. */
  25502. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25503. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  25504. };
  25505. /**
  25506. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25507. * Boolean returned.
  25508. */
  25509. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25510. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  25511. };
  25512. /**
  25513. * Renders the submesh.
  25514. * Returns it.
  25515. */
  25516. SubMesh.prototype.render = function (enableAlphaMode) {
  25517. this._renderingMesh.render(this, enableAlphaMode);
  25518. return this;
  25519. };
  25520. /**
  25521. * Returns a new Index Buffer.
  25522. * Type returned : WebGLBuffer.
  25523. */
  25524. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25525. if (!this._linesIndexBuffer) {
  25526. var linesIndices = [];
  25527. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25528. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25529. }
  25530. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25531. this.linesIndexCount = linesIndices.length;
  25532. }
  25533. return this._linesIndexBuffer;
  25534. };
  25535. /**
  25536. * True is the passed Ray intersects the submesh bounding box.
  25537. * Boolean returned.
  25538. */
  25539. SubMesh.prototype.canIntersects = function (ray) {
  25540. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  25541. };
  25542. /**
  25543. * Returns an object IntersectionInfo.
  25544. */
  25545. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25546. var intersectInfo = null;
  25547. // LineMesh first as it's also a Mesh...
  25548. if (this._mesh instanceof BABYLON.LinesMesh) {
  25549. var lineMesh = this._mesh;
  25550. // Line test
  25551. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25552. var p0 = positions[indices[index]];
  25553. var p1 = positions[indices[index + 1]];
  25554. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25555. if (length < 0) {
  25556. continue;
  25557. }
  25558. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25559. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25560. if (fastCheck) {
  25561. break;
  25562. }
  25563. }
  25564. }
  25565. }
  25566. else {
  25567. // Triangles test
  25568. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25569. var p0 = positions[indices[index]];
  25570. var p1 = positions[indices[index + 1]];
  25571. var p2 = positions[indices[index + 2]];
  25572. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25573. if (currentIntersectInfo) {
  25574. if (currentIntersectInfo.distance < 0) {
  25575. continue;
  25576. }
  25577. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25578. intersectInfo = currentIntersectInfo;
  25579. intersectInfo.faceId = index / 3;
  25580. if (fastCheck) {
  25581. break;
  25582. }
  25583. }
  25584. }
  25585. }
  25586. }
  25587. return intersectInfo;
  25588. };
  25589. // Clone
  25590. /**
  25591. * Creates a new Submesh from the passed Mesh.
  25592. */
  25593. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25594. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25595. if (!this.IsGlobal) {
  25596. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  25597. }
  25598. return result;
  25599. };
  25600. // Dispose
  25601. /**
  25602. * Disposes the Submesh.
  25603. * Returns nothing.
  25604. */
  25605. SubMesh.prototype.dispose = function () {
  25606. if (this._linesIndexBuffer) {
  25607. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25608. this._linesIndexBuffer = null;
  25609. }
  25610. // Remove from mesh
  25611. var index = this._mesh.subMeshes.indexOf(this);
  25612. this._mesh.subMeshes.splice(index, 1);
  25613. };
  25614. // Statics
  25615. /**
  25616. * Creates a new Submesh from the passed parameters :
  25617. * - materialIndex (integer) : the index of the main mesh material.
  25618. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25619. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25620. * - mesh (Mesh) : the main mesh to create the submesh from.
  25621. * - renderingMesh (optional Mesh) : rendering mesh.
  25622. */
  25623. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25624. var minVertexIndex = Number.MAX_VALUE;
  25625. var maxVertexIndex = -Number.MAX_VALUE;
  25626. renderingMesh = renderingMesh || mesh;
  25627. var indices = renderingMesh.getIndices();
  25628. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25629. var vertexIndex = indices[index];
  25630. if (vertexIndex < minVertexIndex)
  25631. minVertexIndex = vertexIndex;
  25632. if (vertexIndex > maxVertexIndex)
  25633. maxVertexIndex = vertexIndex;
  25634. }
  25635. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25636. };
  25637. return SubMesh;
  25638. }());
  25639. BABYLON.SubMesh = SubMesh;
  25640. })(BABYLON || (BABYLON = {}));
  25641. //# sourceMappingURL=babylon.subMesh.js.map
  25642. var BABYLON;
  25643. (function (BABYLON) {
  25644. var MeshBuilder = (function () {
  25645. function MeshBuilder() {
  25646. }
  25647. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  25648. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  25649. return BABYLON.Mesh.DOUBLESIDE;
  25650. }
  25651. if (orientation === undefined || orientation === null) {
  25652. return BABYLON.Mesh.FRONTSIDE;
  25653. }
  25654. return orientation;
  25655. };
  25656. /**
  25657. * Creates a box mesh.
  25658. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  25659. * The parameter `size` sets the size (float) of each box side (default 1).
  25660. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  25661. * 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).
  25662. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  25663. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25664. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25665. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25666. */
  25667. MeshBuilder.CreateBox = function (name, options, scene) {
  25668. var box = new BABYLON.Mesh(name, scene);
  25669. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25670. box.sideOrientation = options.sideOrientation;
  25671. var vertexData = BABYLON.VertexData.CreateBox(options);
  25672. vertexData.applyToMesh(box, options.updatable);
  25673. return box;
  25674. };
  25675. /**
  25676. * Creates a sphere mesh.
  25677. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  25678. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25679. * 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`).
  25680. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25681. * 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
  25682. * 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).
  25683. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25684. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25686. */
  25687. MeshBuilder.CreateSphere = function (name, options, scene) {
  25688. var sphere = new BABYLON.Mesh(name, scene);
  25689. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25690. sphere.sideOrientation = options.sideOrientation;
  25691. var vertexData = BABYLON.VertexData.CreateSphere(options);
  25692. vertexData.applyToMesh(sphere, options.updatable);
  25693. return sphere;
  25694. };
  25695. /**
  25696. * Creates a plane polygonal mesh. By default, this is a disc.
  25697. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  25698. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25699. * 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.
  25700. * 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
  25701. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25702. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25703. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25704. */
  25705. MeshBuilder.CreateDisc = function (name, options, scene) {
  25706. var disc = new BABYLON.Mesh(name, scene);
  25707. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25708. disc.sideOrientation = options.sideOrientation;
  25709. var vertexData = BABYLON.VertexData.CreateDisc(options);
  25710. vertexData.applyToMesh(disc, options.updatable);
  25711. return disc;
  25712. };
  25713. /**
  25714. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25715. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  25716. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25717. * 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`).
  25718. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25719. * 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.
  25720. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25721. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25722. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25723. */
  25724. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  25725. var sphere = new BABYLON.Mesh(name, scene);
  25726. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25727. sphere.sideOrientation = options.sideOrientation;
  25728. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  25729. vertexData.applyToMesh(sphere, options.updatable);
  25730. return sphere;
  25731. };
  25732. ;
  25733. /**
  25734. * Creates a ribbon mesh.
  25735. * 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.
  25736. *
  25737. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25738. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25739. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25740. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25741. * 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.
  25742. * 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.
  25743. * 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
  25744. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25745. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25746. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25747. * The parameter `uvs` is an optional flat array of `Vector4` to update/set each ribbon vertex with its own custom UV values instead of the computed ones.
  25748. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  25749. * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that
  25750. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  25751. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  25752. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25753. */
  25754. MeshBuilder.CreateRibbon = function (name, options, scene) {
  25755. var pathArray = options.pathArray;
  25756. var closeArray = options.closeArray;
  25757. var closePath = options.closePath;
  25758. var offset = options.offset;
  25759. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25760. var instance = options.instance;
  25761. var updatable = options.updatable;
  25762. if (instance) {
  25763. // positionFunction : ribbon case
  25764. // only pathArray and sideOrientation parameters are taken into account for positions update
  25765. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  25766. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  25767. var positionFunction = function (positions) {
  25768. var minlg = pathArray[0].length;
  25769. var i = 0;
  25770. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  25771. for (var si = 1; si <= ns; si++) {
  25772. for (var p = 0; p < pathArray.length; p++) {
  25773. var path = pathArray[p];
  25774. var l = path.length;
  25775. minlg = (minlg < l) ? minlg : l;
  25776. var j = 0;
  25777. while (j < minlg) {
  25778. positions[i] = path[j].x;
  25779. positions[i + 1] = path[j].y;
  25780. positions[i + 2] = path[j].z;
  25781. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  25782. BABYLON.Tmp.Vector3[0].x = path[j].x;
  25783. }
  25784. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  25785. BABYLON.Tmp.Vector3[1].x = path[j].x;
  25786. }
  25787. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  25788. BABYLON.Tmp.Vector3[0].y = path[j].y;
  25789. }
  25790. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  25791. BABYLON.Tmp.Vector3[1].y = path[j].y;
  25792. }
  25793. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  25794. BABYLON.Tmp.Vector3[0].z = path[j].z;
  25795. }
  25796. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  25797. BABYLON.Tmp.Vector3[1].z = path[j].z;
  25798. }
  25799. j++;
  25800. i += 3;
  25801. }
  25802. if (instance._closePath) {
  25803. positions[i] = path[0].x;
  25804. positions[i + 1] = path[0].y;
  25805. positions[i + 2] = path[0].z;
  25806. i += 3;
  25807. }
  25808. }
  25809. }
  25810. };
  25811. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25812. positionFunction(positions);
  25813. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  25814. instance._boundingInfo.update(instance._worldMatrix);
  25815. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25816. if (options.colors) {
  25817. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  25818. for (var c = 0; c < options.colors.length; c++) {
  25819. colors[c * 4] = options.colors[c].r;
  25820. colors[c * 4 + 1] = options.colors[c].g;
  25821. colors[c * 4 + 2] = options.colors[c].b;
  25822. colors[c * 4 + 3] = options.colors[c].a;
  25823. }
  25824. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  25825. }
  25826. if (options.uvs) {
  25827. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25828. for (var i = 0; i < options.uvs.length; i++) {
  25829. uvs[i * 2] = options.uvs[i].x;
  25830. uvs[i * 2 + 1] = options.uvs[i].y;
  25831. }
  25832. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  25833. }
  25834. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  25835. var indices = instance.getIndices();
  25836. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25837. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  25838. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  25839. if (instance._closePath) {
  25840. var indexFirst = 0;
  25841. var indexLast = 0;
  25842. for (var p = 0; p < pathArray.length; p++) {
  25843. indexFirst = instance._idx[p] * 3;
  25844. if (p + 1 < pathArray.length) {
  25845. indexLast = (instance._idx[p + 1] - 1) * 3;
  25846. }
  25847. else {
  25848. indexLast = normals.length - 3;
  25849. }
  25850. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25851. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25852. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25853. normals[indexLast] = normals[indexFirst];
  25854. normals[indexLast + 1] = normals[indexFirst + 1];
  25855. normals[indexLast + 2] = normals[indexFirst + 2];
  25856. }
  25857. }
  25858. if (!(instance.areNormalsFrozen)) {
  25859. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25860. }
  25861. }
  25862. return instance;
  25863. }
  25864. else {
  25865. var ribbon = new BABYLON.Mesh(name, scene);
  25866. ribbon.sideOrientation = sideOrientation;
  25867. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  25868. if (closePath) {
  25869. ribbon._idx = vertexData._idx;
  25870. }
  25871. ribbon._closePath = closePath;
  25872. ribbon._closeArray = closeArray;
  25873. vertexData.applyToMesh(ribbon, updatable);
  25874. return ribbon;
  25875. }
  25876. };
  25877. /**
  25878. * Creates a cylinder or a cone mesh.
  25879. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  25880. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25881. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25882. * 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.
  25883. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25884. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25885. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  25886. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  25887. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  25888. * 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).
  25889. * 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
  25890. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  25891. * 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
  25892. * 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.
  25893. * If `enclose` is false, a ring surface is one element.
  25894. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  25895. * 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
  25896. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25897. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25898. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25899. */
  25900. MeshBuilder.CreateCylinder = function (name, options, scene) {
  25901. var cylinder = new BABYLON.Mesh(name, scene);
  25902. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25903. cylinder.sideOrientation = options.sideOrientation;
  25904. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  25905. vertexData.applyToMesh(cylinder, options.updatable);
  25906. return cylinder;
  25907. };
  25908. /**
  25909. * Creates a torus mesh.
  25910. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  25911. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25912. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25913. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25914. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25915. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25916. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25917. */
  25918. MeshBuilder.CreateTorus = function (name, options, scene) {
  25919. var torus = new BABYLON.Mesh(name, scene);
  25920. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25921. torus.sideOrientation = options.sideOrientation;
  25922. var vertexData = BABYLON.VertexData.CreateTorus(options);
  25923. vertexData.applyToMesh(torus, options.updatable);
  25924. return torus;
  25925. };
  25926. /**
  25927. * Creates a torus knot mesh.
  25928. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  25929. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25930. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25931. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25932. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25933. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25934. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25935. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25936. */
  25937. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  25938. var torusKnot = new BABYLON.Mesh(name, scene);
  25939. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25940. torusKnot.sideOrientation = options.sideOrientation;
  25941. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  25942. vertexData.applyToMesh(torusKnot, options.updatable);
  25943. return torusKnot;
  25944. };
  25945. /**
  25946. * Creates a line system mesh.
  25947. * A line system is a pool of many lines gathered in a single mesh.
  25948. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  25949. * 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.
  25950. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  25951. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  25952. * 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
  25953. * 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
  25954. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  25955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25956. */
  25957. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  25958. var instance = options.instance;
  25959. var lines = options.lines;
  25960. if (instance) {
  25961. var positionFunction = function (positions) {
  25962. var i = 0;
  25963. for (var l = 0; l < lines.length; l++) {
  25964. var points = lines[l];
  25965. for (var p = 0; p < points.length; p++) {
  25966. positions[i] = points[p].x;
  25967. positions[i + 1] = points[p].y;
  25968. positions[i + 2] = points[p].z;
  25969. i += 3;
  25970. }
  25971. }
  25972. };
  25973. instance.updateMeshPositions(positionFunction, false);
  25974. return instance;
  25975. }
  25976. // line system creation
  25977. var lineSystem = new BABYLON.LinesMesh(name, scene);
  25978. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  25979. vertexData.applyToMesh(lineSystem, options.updatable);
  25980. return lineSystem;
  25981. };
  25982. /**
  25983. * Creates a line mesh.
  25984. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  25985. * 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.
  25986. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25987. * The parameter `points` is an array successive Vector3.
  25988. * 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
  25989. * When updating an instance, remember that only point positions can change, not the number of points.
  25990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25991. */
  25992. MeshBuilder.CreateLines = function (name, options, scene) {
  25993. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  25994. return lines;
  25995. };
  25996. /**
  25997. * Creates a dashed line mesh.
  25998. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  25999. * 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.
  26000. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26001. * The parameter `points` is an array successive Vector3.
  26002. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26003. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26004. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26005. * 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
  26006. * When updating an instance, remember that only point positions can change, not the number of points.
  26007. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26008. */
  26009. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  26010. var points = options.points;
  26011. var instance = options.instance;
  26012. var gapSize = options.gapSize;
  26013. var dashNb = options.dashNb;
  26014. var dashSize = options.dashSize;
  26015. if (instance) {
  26016. var positionFunction = function (positions) {
  26017. var curvect = BABYLON.Vector3.Zero();
  26018. var nbSeg = positions.length / 6;
  26019. var lg = 0;
  26020. var nb = 0;
  26021. var shft = 0;
  26022. var dashshft = 0;
  26023. var curshft = 0;
  26024. var p = 0;
  26025. var i = 0;
  26026. var j = 0;
  26027. for (i = 0; i < points.length - 1; i++) {
  26028. points[i + 1].subtractToRef(points[i], curvect);
  26029. lg += curvect.length();
  26030. }
  26031. shft = lg / nbSeg;
  26032. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  26033. for (i = 0; i < points.length - 1; i++) {
  26034. points[i + 1].subtractToRef(points[i], curvect);
  26035. nb = Math.floor(curvect.length() / shft);
  26036. curvect.normalize();
  26037. j = 0;
  26038. while (j < nb && p < positions.length) {
  26039. curshft = shft * j;
  26040. positions[p] = points[i].x + curshft * curvect.x;
  26041. positions[p + 1] = points[i].y + curshft * curvect.y;
  26042. positions[p + 2] = points[i].z + curshft * curvect.z;
  26043. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  26044. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  26045. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  26046. p += 6;
  26047. j++;
  26048. }
  26049. }
  26050. while (p < positions.length) {
  26051. positions[p] = points[i].x;
  26052. positions[p + 1] = points[i].y;
  26053. positions[p + 2] = points[i].z;
  26054. p += 3;
  26055. }
  26056. };
  26057. instance.updateMeshPositions(positionFunction, false);
  26058. return instance;
  26059. }
  26060. // dashed lines creation
  26061. var dashedLines = new BABYLON.LinesMesh(name, scene);
  26062. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  26063. vertexData.applyToMesh(dashedLines, options.updatable);
  26064. dashedLines.dashSize = dashSize;
  26065. dashedLines.gapSize = gapSize;
  26066. return dashedLines;
  26067. };
  26068. /**
  26069. * Creates an extruded shape mesh.
  26070. * 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.
  26071. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  26072. *
  26073. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26074. * 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
  26075. * extruded along the Z axis.
  26076. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26077. * 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.
  26078. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26079. * 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
  26080. * 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
  26081. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26082. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26083. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26084. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26085. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26086. */
  26087. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  26088. var path = options.path;
  26089. var shape = options.shape;
  26090. var scale = options.scale || 1;
  26091. var rotation = options.rotation || 0;
  26092. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26093. var updatable = options.updatable;
  26094. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26095. var instance = options.instance;
  26096. var invertUV = options.invertUV || false;
  26097. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  26098. };
  26099. /**
  26100. * Creates an custom extruded shape mesh.
  26101. * 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.
  26102. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  26103. *
  26104. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26105. * 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
  26106. * extruded along the Z axis.
  26107. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26108. * 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
  26109. * and the distance of this point from the begining of the path :
  26110. * ```javascript
  26111. * var rotationFunction = function(i, distance) {
  26112. * // do things
  26113. * return rotationValue; }
  26114. * ```
  26115. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26116. * 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
  26117. * and the distance of this point from the begining of the path :
  26118. * ```javascript
  26119. * var scaleFunction = function(i, distance) {
  26120. * // do things
  26121. * return scaleValue;}
  26122. * ```
  26123. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26124. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26125. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26126. * 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
  26127. * 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
  26128. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26129. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26130. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26131. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26133. */
  26134. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  26135. var path = options.path;
  26136. var shape = options.shape;
  26137. var scaleFunction = options.scaleFunction || (function () { return 1; });
  26138. var rotationFunction = options.rotationFunction || (function () { return 0; });
  26139. var ribbonCloseArray = options.ribbonCloseArray || false;
  26140. var ribbonClosePath = options.ribbonClosePath || false;
  26141. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26142. var updatable = options.updatable;
  26143. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26144. var instance = options.instance;
  26145. var invertUV = options.invertUV || false;
  26146. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  26147. };
  26148. /**
  26149. * Creates lathe mesh.
  26150. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  26151. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  26152. *
  26153. * 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
  26154. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  26155. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  26156. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  26157. * 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.
  26158. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  26159. * 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
  26160. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26161. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26162. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26163. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26164. */
  26165. MeshBuilder.CreateLathe = function (name, options, scene) {
  26166. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  26167. var closed = (options.closed === undefined) ? true : options.closed;
  26168. var shape = options.shape;
  26169. var radius = options.radius || 1;
  26170. var tessellation = options.tessellation || 64;
  26171. var updatable = options.updatable;
  26172. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26173. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26174. var pi2 = Math.PI * 2;
  26175. var paths = new Array();
  26176. var invertUV = options.invertUV || false;
  26177. var i = 0;
  26178. var p = 0;
  26179. var step = pi2 / tessellation * arc;
  26180. var rotated;
  26181. var path = new Array();
  26182. ;
  26183. for (i = 0; i <= tessellation; i++) {
  26184. var path = [];
  26185. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  26186. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  26187. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  26188. }
  26189. for (p = 0; p < shape.length; p++) {
  26190. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  26191. path.push(rotated);
  26192. }
  26193. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  26194. 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));
  26195. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  26196. }
  26197. paths.push(path);
  26198. }
  26199. // lathe ribbon
  26200. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  26201. return lathe;
  26202. };
  26203. /**
  26204. * Creates a plane mesh.
  26205. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26206. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  26207. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  26208. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  26209. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26210. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26211. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26212. */
  26213. MeshBuilder.CreatePlane = function (name, options, scene) {
  26214. var plane = new BABYLON.Mesh(name, scene);
  26215. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26216. plane.sideOrientation = options.sideOrientation;
  26217. var vertexData = BABYLON.VertexData.CreatePlane(options);
  26218. vertexData.applyToMesh(plane, options.updatable);
  26219. if (options.sourcePlane) {
  26220. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  26221. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  26222. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  26223. plane.rotate(vectorProduct, product);
  26224. }
  26225. return plane;
  26226. };
  26227. /**
  26228. * Creates a ground mesh.
  26229. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26230. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  26231. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  26232. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26233. */
  26234. MeshBuilder.CreateGround = function (name, options, scene) {
  26235. var ground = new BABYLON.GroundMesh(name, scene);
  26236. ground._setReady(false);
  26237. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26238. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26239. ground._width = options.width || 1;
  26240. ground._height = options.height || 1;
  26241. ground._maxX = ground._width / 2;
  26242. ground._maxZ = ground._height / 2;
  26243. ground._minX = -ground._maxX;
  26244. ground._minZ = -ground._maxZ;
  26245. var vertexData = BABYLON.VertexData.CreateGround(options);
  26246. vertexData.applyToMesh(ground, options.updatable);
  26247. ground._setReady(true);
  26248. return ground;
  26249. };
  26250. /**
  26251. * Creates a tiled ground mesh.
  26252. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  26253. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  26254. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  26255. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  26256. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  26257. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  26258. * numbers of subdivisions on the ground width and height of each tile.
  26259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26260. */
  26261. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  26262. var tiledGround = new BABYLON.Mesh(name, scene);
  26263. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  26264. vertexData.applyToMesh(tiledGround, options.updatable);
  26265. return tiledGround;
  26266. };
  26267. /**
  26268. * Creates a ground mesh from a height map.
  26269. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  26270. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  26271. * The parameter `url` sets the URL of the height map image resource.
  26272. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  26273. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  26274. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  26275. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  26276. * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  26277. * 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).
  26278. * This function is passed the newly built mesh :
  26279. * ```javascript
  26280. * function(mesh) { // do things
  26281. * return; }
  26282. * ```
  26283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26284. */
  26285. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  26286. var width = options.width || 10.0;
  26287. var height = options.height || 10.0;
  26288. var subdivisions = options.subdivisions || 1 | 0;
  26289. var minHeight = options.minHeight || 0.0;
  26290. var maxHeight = options.maxHeight || 10.0;
  26291. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26292. var updatable = options.updatable;
  26293. var onReady = options.onReady;
  26294. var ground = new BABYLON.GroundMesh(name, scene);
  26295. ground._subdivisionsX = subdivisions;
  26296. ground._subdivisionsY = subdivisions;
  26297. ground._width = width;
  26298. ground._height = height;
  26299. ground._maxX = ground._width / 2.0;
  26300. ground._maxZ = ground._height / 2.0;
  26301. ground._minX = -ground._maxX;
  26302. ground._minZ = -ground._maxZ;
  26303. ground._setReady(false);
  26304. var onload = function (img) {
  26305. // Getting height map data
  26306. var canvas = document.createElement("canvas");
  26307. var context = canvas.getContext("2d");
  26308. var bufferWidth = img.width;
  26309. var bufferHeight = img.height;
  26310. canvas.width = bufferWidth;
  26311. canvas.height = bufferHeight;
  26312. context.drawImage(img, 0, 0);
  26313. // Create VertexData from map data
  26314. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26315. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  26316. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  26317. width: width, height: height,
  26318. subdivisions: subdivisions,
  26319. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  26320. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  26321. });
  26322. vertexData.applyToMesh(ground, updatable);
  26323. ground._setReady(true);
  26324. //execute ready callback, if set
  26325. if (onReady) {
  26326. onReady(ground);
  26327. }
  26328. };
  26329. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26330. return ground;
  26331. };
  26332. /**
  26333. * Creates a tube mesh.
  26334. * 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.
  26335. *
  26336. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  26337. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  26338. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  26339. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  26340. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  26341. * 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.
  26342. * It must return a radius value (positive float) :
  26343. * ```javascript
  26344. * var radiusFunction = function(i, distance) {
  26345. * // do things
  26346. * return radius; }
  26347. * ```
  26348. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  26349. * 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
  26350. * 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
  26351. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26352. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26353. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26354. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26355. */
  26356. MeshBuilder.CreateTube = function (name, options, scene) {
  26357. var path = options.path;
  26358. var radius = options.radius || 1.0;
  26359. var tessellation = options.tessellation || 64 | 0;
  26360. var radiusFunction = options.radiusFunction;
  26361. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26362. var invertUV = options.invertUV || false;
  26363. var updatable = options.updatable;
  26364. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26365. var instance = options.instance;
  26366. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  26367. // tube geometry
  26368. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  26369. var tangents = path3D.getTangents();
  26370. var normals = path3D.getNormals();
  26371. var distances = path3D.getDistances();
  26372. var pi2 = Math.PI * 2;
  26373. var step = pi2 / tessellation * arc;
  26374. var returnRadius = function () { return radius; };
  26375. var radiusFunctionFinal = radiusFunction || returnRadius;
  26376. var circlePath;
  26377. var rad;
  26378. var normal;
  26379. var rotated;
  26380. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26381. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26382. for (var i = 0; i < path.length; i++) {
  26383. rad = radiusFunctionFinal(i, distances[i]); // current radius
  26384. circlePath = Array(); // current circle array
  26385. normal = normals[i]; // current normal
  26386. for (var t = 0; t < tessellation; t++) {
  26387. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  26388. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  26389. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  26390. rotated.scaleInPlace(rad).addInPlace(path[i]);
  26391. circlePath[t] = rotated;
  26392. }
  26393. circlePaths[index] = circlePath;
  26394. index++;
  26395. }
  26396. // cap
  26397. var capPath = function (nbPoints, pathIndex) {
  26398. var pointCap = Array();
  26399. for (var i = 0; i < nbPoints; i++) {
  26400. pointCap.push(path[pathIndex]);
  26401. }
  26402. return pointCap;
  26403. };
  26404. switch (cap) {
  26405. case BABYLON.Mesh.NO_CAP:
  26406. break;
  26407. case BABYLON.Mesh.CAP_START:
  26408. circlePaths[0] = capPath(tessellation, 0);
  26409. circlePaths[1] = circlePaths[2].slice(0);
  26410. break;
  26411. case BABYLON.Mesh.CAP_END:
  26412. circlePaths[index] = circlePaths[index - 1].slice(0);
  26413. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  26414. break;
  26415. case BABYLON.Mesh.CAP_ALL:
  26416. circlePaths[0] = capPath(tessellation, 0);
  26417. circlePaths[1] = circlePaths[2].slice(0);
  26418. circlePaths[index] = circlePaths[index - 1].slice(0);
  26419. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  26420. break;
  26421. default:
  26422. break;
  26423. }
  26424. return circlePaths;
  26425. };
  26426. var path3D;
  26427. var pathArray;
  26428. if (instance) {
  26429. var arc = options.arc || instance.arc;
  26430. path3D = (instance.path3D).update(path);
  26431. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  26432. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  26433. instance.path3D = path3D;
  26434. instance.pathArray = pathArray;
  26435. instance.arc = arc;
  26436. return instance;
  26437. }
  26438. // tube creation
  26439. path3D = new BABYLON.Path3D(path);
  26440. var newPathArray = new Array();
  26441. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26442. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  26443. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  26444. tube.pathArray = pathArray;
  26445. tube.path3D = path3D;
  26446. tube.tessellation = tessellation;
  26447. tube.cap = cap;
  26448. tube.arc = options.arc;
  26449. return tube;
  26450. };
  26451. /**
  26452. * Creates a polyhedron mesh.
  26453. *
  26454. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  26455. * 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
  26456. * to choose the wanted type.
  26457. * The parameter `size` (positive float, default 1) sets the polygon size.
  26458. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  26459. * 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`.
  26460. * 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
  26461. * 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)`).
  26462. * 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
  26463. * 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.
  26464. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26465. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26467. */
  26468. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  26469. var polyhedron = new BABYLON.Mesh(name, scene);
  26470. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26471. polyhedron.sideOrientation = options.sideOrientation;
  26472. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  26473. vertexData.applyToMesh(polyhedron, options.updatable);
  26474. return polyhedron;
  26475. };
  26476. /**
  26477. * Creates a decal mesh.
  26478. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  26479. * 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.
  26480. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  26481. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  26482. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  26483. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  26484. */
  26485. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  26486. var indices = sourceMesh.getIndices();
  26487. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26488. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26489. var position = options.position || BABYLON.Vector3.Zero();
  26490. var normal = options.normal || BABYLON.Vector3.Up();
  26491. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  26492. var angle = options.angle || 0;
  26493. // Getting correct rotation
  26494. if (!normal) {
  26495. var target = new BABYLON.Vector3(0, 0, 1);
  26496. var camera = sourceMesh.getScene().activeCamera;
  26497. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  26498. normal = camera.globalPosition.subtract(cameraWorldTarget);
  26499. }
  26500. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  26501. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  26502. var pitch = Math.atan2(normal.y, len);
  26503. // Matrix
  26504. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  26505. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  26506. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  26507. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  26508. var vertexData = new BABYLON.VertexData();
  26509. vertexData.indices = [];
  26510. vertexData.positions = [];
  26511. vertexData.normals = [];
  26512. vertexData.uvs = [];
  26513. var currentVertexDataIndex = 0;
  26514. var extractDecalVector3 = function (indexId) {
  26515. var vertexId = indices[indexId];
  26516. var result = new BABYLON.PositionNormalVertex();
  26517. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  26518. // Send vector to decal local world
  26519. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  26520. // Get normal
  26521. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  26522. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  26523. return result;
  26524. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  26525. var clip = function (vertices, axis) {
  26526. if (vertices.length === 0) {
  26527. return vertices;
  26528. }
  26529. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  26530. var clipVertices = function (v0, v1) {
  26531. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  26532. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  26533. };
  26534. var result = new Array();
  26535. for (var index = 0; index < vertices.length; index += 3) {
  26536. var v1Out;
  26537. var v2Out;
  26538. var v3Out;
  26539. var total = 0;
  26540. var nV1, nV2, nV3, nV4;
  26541. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  26542. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  26543. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  26544. v1Out = d1 > 0;
  26545. v2Out = d2 > 0;
  26546. v3Out = d3 > 0;
  26547. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  26548. switch (total) {
  26549. case 0:
  26550. result.push(vertices[index]);
  26551. result.push(vertices[index + 1]);
  26552. result.push(vertices[index + 2]);
  26553. break;
  26554. case 1:
  26555. if (v1Out) {
  26556. nV1 = vertices[index + 1];
  26557. nV2 = vertices[index + 2];
  26558. nV3 = clipVertices(vertices[index], nV1);
  26559. nV4 = clipVertices(vertices[index], nV2);
  26560. }
  26561. if (v2Out) {
  26562. nV1 = vertices[index];
  26563. nV2 = vertices[index + 2];
  26564. nV3 = clipVertices(vertices[index + 1], nV1);
  26565. nV4 = clipVertices(vertices[index + 1], nV2);
  26566. result.push(nV3);
  26567. result.push(nV2.clone());
  26568. result.push(nV1.clone());
  26569. result.push(nV2.clone());
  26570. result.push(nV3.clone());
  26571. result.push(nV4);
  26572. break;
  26573. }
  26574. if (v3Out) {
  26575. nV1 = vertices[index];
  26576. nV2 = vertices[index + 1];
  26577. nV3 = clipVertices(vertices[index + 2], nV1);
  26578. nV4 = clipVertices(vertices[index + 2], nV2);
  26579. }
  26580. result.push(nV1.clone());
  26581. result.push(nV2.clone());
  26582. result.push(nV3);
  26583. result.push(nV4);
  26584. result.push(nV3.clone());
  26585. result.push(nV2.clone());
  26586. break;
  26587. case 2:
  26588. if (!v1Out) {
  26589. nV1 = vertices[index].clone();
  26590. nV2 = clipVertices(nV1, vertices[index + 1]);
  26591. nV3 = clipVertices(nV1, vertices[index + 2]);
  26592. result.push(nV1);
  26593. result.push(nV2);
  26594. result.push(nV3);
  26595. }
  26596. if (!v2Out) {
  26597. nV1 = vertices[index + 1].clone();
  26598. nV2 = clipVertices(nV1, vertices[index + 2]);
  26599. nV3 = clipVertices(nV1, vertices[index]);
  26600. result.push(nV1);
  26601. result.push(nV2);
  26602. result.push(nV3);
  26603. }
  26604. if (!v3Out) {
  26605. nV1 = vertices[index + 2].clone();
  26606. nV2 = clipVertices(nV1, vertices[index]);
  26607. nV3 = clipVertices(nV1, vertices[index + 1]);
  26608. result.push(nV1);
  26609. result.push(nV2);
  26610. result.push(nV3);
  26611. }
  26612. break;
  26613. case 3:
  26614. break;
  26615. }
  26616. }
  26617. return result;
  26618. };
  26619. for (var index = 0; index < indices.length; index += 3) {
  26620. var faceVertices = new Array();
  26621. faceVertices.push(extractDecalVector3(index));
  26622. faceVertices.push(extractDecalVector3(index + 1));
  26623. faceVertices.push(extractDecalVector3(index + 2));
  26624. // Clip
  26625. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  26626. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  26627. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  26628. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  26629. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  26630. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  26631. if (faceVertices.length === 0) {
  26632. continue;
  26633. }
  26634. // Add UVs and get back to world
  26635. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  26636. var vertex = faceVertices[vIndex];
  26637. //TODO check for Int32Array | Uint32Array | Uint16Array
  26638. vertexData.indices.push(currentVertexDataIndex);
  26639. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  26640. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  26641. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  26642. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  26643. currentVertexDataIndex++;
  26644. }
  26645. }
  26646. // Return mesh
  26647. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  26648. vertexData.applyToMesh(decal);
  26649. decal.position = position.clone();
  26650. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  26651. return decal;
  26652. };
  26653. // Privates
  26654. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  26655. // extrusion geometry
  26656. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  26657. var tangents = path3D.getTangents();
  26658. var normals = path3D.getNormals();
  26659. var binormals = path3D.getBinormals();
  26660. var distances = path3D.getDistances();
  26661. var angle = 0;
  26662. var returnScale = function () { return scale; };
  26663. var returnRotation = function () { return rotation; };
  26664. var rotate = custom ? rotateFunction : returnRotation;
  26665. var scl = custom ? scaleFunction : returnScale;
  26666. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26667. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26668. for (var i = 0; i < curve.length; i++) {
  26669. var shapePath = new Array();
  26670. var angleStep = rotate(i, distances[i]);
  26671. var scaleRatio = scl(i, distances[i]);
  26672. for (var p = 0; p < shape.length; p++) {
  26673. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  26674. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  26675. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  26676. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  26677. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  26678. shapePath[p] = rotated;
  26679. }
  26680. shapePaths[index] = shapePath;
  26681. angle += angleStep;
  26682. index++;
  26683. }
  26684. // cap
  26685. var capPath = function (shapePath) {
  26686. var pointCap = Array();
  26687. var barycenter = BABYLON.Vector3.Zero();
  26688. var i;
  26689. for (i = 0; i < shapePath.length; i++) {
  26690. barycenter.addInPlace(shapePath[i]);
  26691. }
  26692. barycenter.scaleInPlace(1.0 / shapePath.length);
  26693. for (i = 0; i < shapePath.length; i++) {
  26694. pointCap.push(barycenter);
  26695. }
  26696. return pointCap;
  26697. };
  26698. switch (cap) {
  26699. case BABYLON.Mesh.NO_CAP:
  26700. break;
  26701. case BABYLON.Mesh.CAP_START:
  26702. shapePaths[0] = capPath(shapePaths[2]);
  26703. shapePaths[1] = shapePaths[2];
  26704. break;
  26705. case BABYLON.Mesh.CAP_END:
  26706. shapePaths[index] = shapePaths[index - 1];
  26707. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26708. break;
  26709. case BABYLON.Mesh.CAP_ALL:
  26710. shapePaths[0] = capPath(shapePaths[2]);
  26711. shapePaths[1] = shapePaths[2];
  26712. shapePaths[index] = shapePaths[index - 1];
  26713. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26714. break;
  26715. default:
  26716. break;
  26717. }
  26718. return shapePaths;
  26719. };
  26720. var path3D;
  26721. var pathArray;
  26722. if (instance) {
  26723. path3D = (instance.path3D).update(curve);
  26724. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  26725. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  26726. return instance;
  26727. }
  26728. // extruded shape creation
  26729. path3D = new BABYLON.Path3D(curve);
  26730. var newShapePaths = new Array();
  26731. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26732. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  26733. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  26734. extrudedGeneric.pathArray = pathArray;
  26735. extrudedGeneric.path3D = path3D;
  26736. extrudedGeneric.cap = cap;
  26737. return extrudedGeneric;
  26738. };
  26739. return MeshBuilder;
  26740. }());
  26741. BABYLON.MeshBuilder = MeshBuilder;
  26742. })(BABYLON || (BABYLON = {}));
  26743. //# sourceMappingURL=babylon.meshBuilder.js.map
  26744. var BABYLON;
  26745. (function (BABYLON) {
  26746. var BaseTexture = (function () {
  26747. function BaseTexture(scene) {
  26748. this.hasAlpha = false;
  26749. this.getAlphaFromRGB = false;
  26750. this.level = 1;
  26751. this.coordinatesIndex = 0;
  26752. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26753. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26754. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26755. this.anisotropicFilteringLevel = 4;
  26756. this.isCube = false;
  26757. this.isRenderTarget = false;
  26758. this.animations = new Array();
  26759. /**
  26760. * An event triggered when the texture is disposed.
  26761. * @type {BABYLON.Observable}
  26762. */
  26763. this.onDisposeObservable = new BABYLON.Observable();
  26764. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26765. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26766. this._scene.textures.push(this);
  26767. this._uid = null;
  26768. }
  26769. Object.defineProperty(BaseTexture.prototype, "uid", {
  26770. get: function () {
  26771. if (!this._uid) {
  26772. this._uid = BABYLON.Tools.RandomId();
  26773. }
  26774. return this._uid;
  26775. },
  26776. enumerable: true,
  26777. configurable: true
  26778. });
  26779. BaseTexture.prototype.toString = function () {
  26780. return this.name;
  26781. };
  26782. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26783. set: function (callback) {
  26784. if (this._onDisposeObserver) {
  26785. this.onDisposeObservable.remove(this._onDisposeObserver);
  26786. }
  26787. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26788. },
  26789. enumerable: true,
  26790. configurable: true
  26791. });
  26792. BaseTexture.prototype.getScene = function () {
  26793. return this._scene;
  26794. };
  26795. BaseTexture.prototype.getTextureMatrix = function () {
  26796. return null;
  26797. };
  26798. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26799. return null;
  26800. };
  26801. BaseTexture.prototype.getInternalTexture = function () {
  26802. return this._texture;
  26803. };
  26804. BaseTexture.prototype.isReady = function () {
  26805. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26806. return true;
  26807. }
  26808. if (this._texture) {
  26809. return this._texture.isReady;
  26810. }
  26811. return false;
  26812. };
  26813. BaseTexture.prototype.getSize = function () {
  26814. if (this._texture._width) {
  26815. return new BABYLON.Size(this._texture._width, this._texture._height);
  26816. }
  26817. if (this._texture._size) {
  26818. return new BABYLON.Size(this._texture._size, this._texture._size);
  26819. }
  26820. return BABYLON.Size.Zero();
  26821. };
  26822. BaseTexture.prototype.getBaseSize = function () {
  26823. if (!this.isReady() || !this._texture)
  26824. return BABYLON.Size.Zero();
  26825. if (this._texture._size) {
  26826. return new BABYLON.Size(this._texture._size, this._texture._size);
  26827. }
  26828. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  26829. };
  26830. BaseTexture.prototype.scale = function (ratio) {
  26831. };
  26832. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26833. get: function () {
  26834. return false;
  26835. },
  26836. enumerable: true,
  26837. configurable: true
  26838. });
  26839. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  26840. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26841. for (var index = 0; index < texturesCache.length; index++) {
  26842. var texturesCacheEntry = texturesCache[index];
  26843. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26844. texturesCache.splice(index, 1);
  26845. return;
  26846. }
  26847. }
  26848. };
  26849. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26850. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26851. for (var index = 0; index < texturesCache.length; index++) {
  26852. var texturesCacheEntry = texturesCache[index];
  26853. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26854. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26855. texturesCacheEntry.references++;
  26856. return texturesCacheEntry;
  26857. }
  26858. }
  26859. }
  26860. return null;
  26861. };
  26862. BaseTexture.prototype.delayLoad = function () {
  26863. };
  26864. BaseTexture.prototype.clone = function () {
  26865. return null;
  26866. };
  26867. BaseTexture.prototype.releaseInternalTexture = function () {
  26868. if (this._texture) {
  26869. this._scene.getEngine().releaseInternalTexture(this._texture);
  26870. delete this._texture;
  26871. }
  26872. };
  26873. BaseTexture.prototype.dispose = function () {
  26874. // Animations
  26875. this.getScene().stopAnimation(this);
  26876. // Remove from scene
  26877. this._scene._removePendingData(this);
  26878. var index = this._scene.textures.indexOf(this);
  26879. if (index >= 0) {
  26880. this._scene.textures.splice(index, 1);
  26881. }
  26882. if (this._texture === undefined) {
  26883. return;
  26884. }
  26885. // Release
  26886. this.releaseInternalTexture();
  26887. // Callback
  26888. this.onDisposeObservable.notifyObservers(this);
  26889. this.onDisposeObservable.clear();
  26890. };
  26891. BaseTexture.prototype.serialize = function () {
  26892. if (!this.name) {
  26893. return null;
  26894. }
  26895. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26896. // Animations
  26897. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26898. return serializationObject;
  26899. };
  26900. return BaseTexture;
  26901. }());
  26902. __decorate([
  26903. BABYLON.serialize()
  26904. ], BaseTexture.prototype, "name", void 0);
  26905. __decorate([
  26906. BABYLON.serialize()
  26907. ], BaseTexture.prototype, "hasAlpha", void 0);
  26908. __decorate([
  26909. BABYLON.serialize()
  26910. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26911. __decorate([
  26912. BABYLON.serialize()
  26913. ], BaseTexture.prototype, "level", void 0);
  26914. __decorate([
  26915. BABYLON.serialize()
  26916. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26917. __decorate([
  26918. BABYLON.serialize()
  26919. ], BaseTexture.prototype, "coordinatesMode", void 0);
  26920. __decorate([
  26921. BABYLON.serialize()
  26922. ], BaseTexture.prototype, "wrapU", void 0);
  26923. __decorate([
  26924. BABYLON.serialize()
  26925. ], BaseTexture.prototype, "wrapV", void 0);
  26926. __decorate([
  26927. BABYLON.serialize()
  26928. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26929. __decorate([
  26930. BABYLON.serialize()
  26931. ], BaseTexture.prototype, "isCube", void 0);
  26932. __decorate([
  26933. BABYLON.serialize()
  26934. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26935. BABYLON.BaseTexture = BaseTexture;
  26936. })(BABYLON || (BABYLON = {}));
  26937. //# sourceMappingURL=babylon.baseTexture.js.map
  26938. var BABYLON;
  26939. (function (BABYLON) {
  26940. var Texture = (function (_super) {
  26941. __extends(Texture, _super);
  26942. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26943. if (noMipmap === void 0) { noMipmap = false; }
  26944. if (invertY === void 0) { invertY = true; }
  26945. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26946. if (onLoad === void 0) { onLoad = null; }
  26947. if (onError === void 0) { onError = null; }
  26948. if (buffer === void 0) { buffer = null; }
  26949. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26950. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26951. var _this = _super.call(this, scene) || this;
  26952. _this.uOffset = 0;
  26953. _this.vOffset = 0;
  26954. _this.uScale = 1.0;
  26955. _this.vScale = 1.0;
  26956. _this.uAng = 0;
  26957. _this.vAng = 0;
  26958. _this.wAng = 0;
  26959. _this.name = url;
  26960. _this.url = url;
  26961. _this._noMipmap = noMipmap;
  26962. _this._invertY = invertY;
  26963. _this._samplingMode = samplingMode;
  26964. _this._buffer = buffer;
  26965. _this._deleteBuffer = deleteBuffer;
  26966. _this._format = format;
  26967. if (!url) {
  26968. return _this;
  26969. }
  26970. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  26971. var load = function () {
  26972. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  26973. _this.onLoadObservable.notifyObservers(true);
  26974. }
  26975. if (onLoad) {
  26976. onLoad();
  26977. }
  26978. };
  26979. if (!_this._texture) {
  26980. if (!scene.useDelayedTextureLoading) {
  26981. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  26982. if (deleteBuffer) {
  26983. delete _this._buffer;
  26984. }
  26985. }
  26986. else {
  26987. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26988. _this._delayedOnLoad = load;
  26989. _this._delayedOnError = onError;
  26990. }
  26991. }
  26992. else {
  26993. if (_this._texture.isReady) {
  26994. BABYLON.Tools.SetImmediate(function () { return load(); });
  26995. }
  26996. else {
  26997. _this._texture.onLoadedCallbacks.push(load);
  26998. }
  26999. }
  27000. return _this;
  27001. }
  27002. Object.defineProperty(Texture.prototype, "noMipmap", {
  27003. get: function () {
  27004. return this._noMipmap;
  27005. },
  27006. enumerable: true,
  27007. configurable: true
  27008. });
  27009. Texture.prototype.delayLoad = function () {
  27010. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27011. return;
  27012. }
  27013. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27014. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27015. if (!this._texture) {
  27016. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27017. if (this._deleteBuffer) {
  27018. delete this._buffer;
  27019. }
  27020. }
  27021. };
  27022. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27023. if (!this._texture) {
  27024. return;
  27025. }
  27026. this._samplingMode = samplingMode;
  27027. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27028. };
  27029. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27030. x *= this.uScale;
  27031. y *= this.vScale;
  27032. x -= 0.5 * this.uScale;
  27033. y -= 0.5 * this.vScale;
  27034. z -= 0.5;
  27035. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27036. t.x += 0.5 * this.uScale + this.uOffset;
  27037. t.y += 0.5 * this.vScale + this.vOffset;
  27038. t.z += 0.5;
  27039. };
  27040. Texture.prototype.getTextureMatrix = function () {
  27041. if (this.uOffset === this._cachedUOffset &&
  27042. this.vOffset === this._cachedVOffset &&
  27043. this.uScale === this._cachedUScale &&
  27044. this.vScale === this._cachedVScale &&
  27045. this.uAng === this._cachedUAng &&
  27046. this.vAng === this._cachedVAng &&
  27047. this.wAng === this._cachedWAng) {
  27048. return this._cachedTextureMatrix;
  27049. }
  27050. this._cachedUOffset = this.uOffset;
  27051. this._cachedVOffset = this.vOffset;
  27052. this._cachedUScale = this.uScale;
  27053. this._cachedVScale = this.vScale;
  27054. this._cachedUAng = this.uAng;
  27055. this._cachedVAng = this.vAng;
  27056. this._cachedWAng = this.wAng;
  27057. if (!this._cachedTextureMatrix) {
  27058. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27059. this._rowGenerationMatrix = new BABYLON.Matrix();
  27060. this._t0 = BABYLON.Vector3.Zero();
  27061. this._t1 = BABYLON.Vector3.Zero();
  27062. this._t2 = BABYLON.Vector3.Zero();
  27063. }
  27064. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27065. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27066. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27067. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27068. this._t1.subtractInPlace(this._t0);
  27069. this._t2.subtractInPlace(this._t0);
  27070. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27071. this._cachedTextureMatrix.m[0] = this._t1.x;
  27072. this._cachedTextureMatrix.m[1] = this._t1.y;
  27073. this._cachedTextureMatrix.m[2] = this._t1.z;
  27074. this._cachedTextureMatrix.m[4] = this._t2.x;
  27075. this._cachedTextureMatrix.m[5] = this._t2.y;
  27076. this._cachedTextureMatrix.m[6] = this._t2.z;
  27077. this._cachedTextureMatrix.m[8] = this._t0.x;
  27078. this._cachedTextureMatrix.m[9] = this._t0.y;
  27079. this._cachedTextureMatrix.m[10] = this._t0.z;
  27080. return this._cachedTextureMatrix;
  27081. };
  27082. Texture.prototype.getReflectionTextureMatrix = function () {
  27083. if (this.uOffset === this._cachedUOffset &&
  27084. this.vOffset === this._cachedVOffset &&
  27085. this.uScale === this._cachedUScale &&
  27086. this.vScale === this._cachedVScale &&
  27087. this.coordinatesMode === this._cachedCoordinatesMode) {
  27088. return this._cachedTextureMatrix;
  27089. }
  27090. if (!this._cachedTextureMatrix) {
  27091. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27092. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27093. }
  27094. this._cachedCoordinatesMode = this.coordinatesMode;
  27095. switch (this.coordinatesMode) {
  27096. case Texture.PLANAR_MODE:
  27097. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27098. this._cachedTextureMatrix[0] = this.uScale;
  27099. this._cachedTextureMatrix[5] = this.vScale;
  27100. this._cachedTextureMatrix[12] = this.uOffset;
  27101. this._cachedTextureMatrix[13] = this.vOffset;
  27102. break;
  27103. case Texture.PROJECTION_MODE:
  27104. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27105. this._projectionModeMatrix.m[0] = 0.5;
  27106. this._projectionModeMatrix.m[5] = -0.5;
  27107. this._projectionModeMatrix.m[10] = 0.0;
  27108. this._projectionModeMatrix.m[12] = 0.5;
  27109. this._projectionModeMatrix.m[13] = 0.5;
  27110. this._projectionModeMatrix.m[14] = 1.0;
  27111. this._projectionModeMatrix.m[15] = 1.0;
  27112. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27113. break;
  27114. default:
  27115. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27116. break;
  27117. }
  27118. return this._cachedTextureMatrix;
  27119. };
  27120. Texture.prototype.clone = function () {
  27121. var _this = this;
  27122. return BABYLON.SerializationHelper.Clone(function () {
  27123. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27124. }, this);
  27125. };
  27126. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27127. get: function () {
  27128. if (!this._onLoadObservarble) {
  27129. this._onLoadObservarble = new BABYLON.Observable();
  27130. }
  27131. return this._onLoadObservarble;
  27132. },
  27133. enumerable: true,
  27134. configurable: true
  27135. });
  27136. // Statics
  27137. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27138. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27139. if (onLoad === void 0) { onLoad = null; }
  27140. if (onError === void 0) { onError = null; }
  27141. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27142. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27143. };
  27144. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27145. if (parsedTexture.customType) {
  27146. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27147. return customTexture.Parse(parsedTexture, scene, rootUrl);
  27148. }
  27149. if (parsedTexture.isCube) {
  27150. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27151. }
  27152. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27153. return null;
  27154. }
  27155. var texture = BABYLON.SerializationHelper.Parse(function () {
  27156. if (parsedTexture.mirrorPlane) {
  27157. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27158. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27159. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27160. return mirrorTexture;
  27161. }
  27162. else if (parsedTexture.isRenderTarget) {
  27163. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27164. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27165. return renderTargetTexture;
  27166. }
  27167. else {
  27168. var texture;
  27169. if (parsedTexture.base64String) {
  27170. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  27171. }
  27172. else {
  27173. texture = new Texture(rootUrl + parsedTexture.name, scene);
  27174. }
  27175. return texture;
  27176. }
  27177. }, parsedTexture, scene);
  27178. // Animations
  27179. if (parsedTexture.animations) {
  27180. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27181. var parsedAnimation = parsedTexture.animations[animationIndex];
  27182. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27183. }
  27184. }
  27185. return texture;
  27186. };
  27187. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27188. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27189. if (noMipmap === void 0) { noMipmap = false; }
  27190. if (invertY === void 0) { invertY = true; }
  27191. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27192. if (onLoad === void 0) { onLoad = null; }
  27193. if (onError === void 0) { onError = null; }
  27194. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27195. if (name.substr(0, 5) !== "data:") {
  27196. name = "data:" + name;
  27197. }
  27198. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27199. };
  27200. return Texture;
  27201. }(BABYLON.BaseTexture));
  27202. // Constants
  27203. Texture.NEAREST_SAMPLINGMODE = 1;
  27204. Texture.BILINEAR_SAMPLINGMODE = 2;
  27205. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27206. Texture.EXPLICIT_MODE = 0;
  27207. Texture.SPHERICAL_MODE = 1;
  27208. Texture.PLANAR_MODE = 2;
  27209. Texture.CUBIC_MODE = 3;
  27210. Texture.PROJECTION_MODE = 4;
  27211. Texture.SKYBOX_MODE = 5;
  27212. Texture.INVCUBIC_MODE = 6;
  27213. Texture.EQUIRECTANGULAR_MODE = 7;
  27214. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27215. Texture.CLAMP_ADDRESSMODE = 0;
  27216. Texture.WRAP_ADDRESSMODE = 1;
  27217. Texture.MIRROR_ADDRESSMODE = 2;
  27218. __decorate([
  27219. BABYLON.serialize()
  27220. ], Texture.prototype, "url", void 0);
  27221. __decorate([
  27222. BABYLON.serialize()
  27223. ], Texture.prototype, "uOffset", void 0);
  27224. __decorate([
  27225. BABYLON.serialize()
  27226. ], Texture.prototype, "vOffset", void 0);
  27227. __decorate([
  27228. BABYLON.serialize()
  27229. ], Texture.prototype, "uScale", void 0);
  27230. __decorate([
  27231. BABYLON.serialize()
  27232. ], Texture.prototype, "vScale", void 0);
  27233. __decorate([
  27234. BABYLON.serialize()
  27235. ], Texture.prototype, "uAng", void 0);
  27236. __decorate([
  27237. BABYLON.serialize()
  27238. ], Texture.prototype, "vAng", void 0);
  27239. __decorate([
  27240. BABYLON.serialize()
  27241. ], Texture.prototype, "wAng", void 0);
  27242. BABYLON.Texture = Texture;
  27243. })(BABYLON || (BABYLON = {}));
  27244. //# sourceMappingURL=babylon.texture.js.map
  27245. var BABYLON;
  27246. (function (BABYLON) {
  27247. var CubeTexture = (function (_super) {
  27248. __extends(CubeTexture, _super);
  27249. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  27250. if (onLoad === void 0) { onLoad = null; }
  27251. if (onError === void 0) { onError = null; }
  27252. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27253. var _this = _super.call(this, scene) || this;
  27254. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  27255. _this.name = rootUrl;
  27256. _this.url = rootUrl;
  27257. _this._noMipmap = noMipmap;
  27258. _this.hasAlpha = false;
  27259. _this._format = format;
  27260. if (!rootUrl && !files) {
  27261. return _this;
  27262. }
  27263. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  27264. if (!files) {
  27265. if (!extensions) {
  27266. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  27267. }
  27268. files = [];
  27269. for (var index = 0; index < extensions.length; index++) {
  27270. files.push(rootUrl + extensions[index]);
  27271. }
  27272. _this._extensions = extensions;
  27273. }
  27274. _this._files = files;
  27275. if (!_this._texture) {
  27276. if (!scene.useDelayedTextureLoading) {
  27277. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  27278. }
  27279. else {
  27280. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27281. }
  27282. }
  27283. else if (onLoad) {
  27284. if (_this._texture.isReady) {
  27285. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  27286. }
  27287. else {
  27288. _this._texture.onLoadedCallbacks.push(onLoad);
  27289. }
  27290. }
  27291. _this.isCube = true;
  27292. _this._textureMatrix = BABYLON.Matrix.Identity();
  27293. return _this;
  27294. }
  27295. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  27296. return new CubeTexture("", scene, null, noMipmap, files);
  27297. };
  27298. // Methods
  27299. CubeTexture.prototype.delayLoad = function () {
  27300. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27301. return;
  27302. }
  27303. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27304. this._texture = this._getFromCache(this.url, this._noMipmap);
  27305. if (!this._texture) {
  27306. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  27307. }
  27308. };
  27309. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  27310. return this._textureMatrix;
  27311. };
  27312. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  27313. var texture = BABYLON.SerializationHelper.Parse(function () {
  27314. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  27315. }, parsedTexture, scene);
  27316. // Animations
  27317. if (parsedTexture.animations) {
  27318. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27319. var parsedAnimation = parsedTexture.animations[animationIndex];
  27320. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27321. }
  27322. }
  27323. return texture;
  27324. };
  27325. CubeTexture.prototype.clone = function () {
  27326. var _this = this;
  27327. return BABYLON.SerializationHelper.Clone(function () {
  27328. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  27329. }, this);
  27330. };
  27331. return CubeTexture;
  27332. }(BABYLON.BaseTexture));
  27333. BABYLON.CubeTexture = CubeTexture;
  27334. })(BABYLON || (BABYLON = {}));
  27335. //# sourceMappingURL=babylon.cubeTexture.js.map
  27336. var BABYLON;
  27337. (function (BABYLON) {
  27338. var RenderTargetTexture = (function (_super) {
  27339. __extends(RenderTargetTexture, _super);
  27340. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  27341. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  27342. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27343. if (isCube === void 0) { isCube = false; }
  27344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27345. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  27346. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  27347. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27348. _this.isCube = isCube;
  27349. /**
  27350. * Use this list to define the list of mesh you want to render.
  27351. */
  27352. _this.renderList = new Array();
  27353. _this.renderParticles = true;
  27354. _this.renderSprites = false;
  27355. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  27356. // Events
  27357. /**
  27358. * An event triggered when the texture is unbind.
  27359. * @type {BABYLON.Observable}
  27360. */
  27361. _this.onAfterUnbindObservable = new BABYLON.Observable();
  27362. /**
  27363. * An event triggered before rendering the texture
  27364. * @type {BABYLON.Observable}
  27365. */
  27366. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27367. /**
  27368. * An event triggered after rendering the texture
  27369. * @type {BABYLON.Observable}
  27370. */
  27371. _this.onAfterRenderObservable = new BABYLON.Observable();
  27372. /**
  27373. * An event triggered after the texture clear
  27374. * @type {BABYLON.Observable}
  27375. */
  27376. _this.onClearObservable = new BABYLON.Observable();
  27377. _this._currentRefreshId = -1;
  27378. _this._refreshRate = 1;
  27379. _this._samples = 1;
  27380. _this.name = name;
  27381. _this.isRenderTarget = true;
  27382. _this._size = size;
  27383. _this._generateMipMaps = generateMipMaps;
  27384. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  27385. _this._renderTargetOptions = {
  27386. generateMipMaps: generateMipMaps,
  27387. type: type,
  27388. samplingMode: samplingMode,
  27389. generateDepthBuffer: generateDepthBuffer,
  27390. generateStencilBuffer: generateStencilBuffer
  27391. };
  27392. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  27393. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27394. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27395. }
  27396. if (isCube) {
  27397. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  27398. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  27399. _this._textureMatrix = BABYLON.Matrix.Identity();
  27400. }
  27401. else {
  27402. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  27403. }
  27404. // Rendering groups
  27405. _this._renderingManager = new BABYLON.RenderingManager(scene);
  27406. return _this;
  27407. }
  27408. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  27409. get: function () {
  27410. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  27411. },
  27412. enumerable: true,
  27413. configurable: true
  27414. });
  27415. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  27416. get: function () {
  27417. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  27418. },
  27419. enumerable: true,
  27420. configurable: true
  27421. });
  27422. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  27423. get: function () {
  27424. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  27425. },
  27426. enumerable: true,
  27427. configurable: true
  27428. });
  27429. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  27430. set: function (callback) {
  27431. if (this._onAfterUnbindObserver) {
  27432. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  27433. }
  27434. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  27435. },
  27436. enumerable: true,
  27437. configurable: true
  27438. });
  27439. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  27440. set: function (callback) {
  27441. if (this._onBeforeRenderObserver) {
  27442. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27443. }
  27444. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27445. },
  27446. enumerable: true,
  27447. configurable: true
  27448. });
  27449. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  27450. set: function (callback) {
  27451. if (this._onAfterRenderObserver) {
  27452. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27453. }
  27454. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27455. },
  27456. enumerable: true,
  27457. configurable: true
  27458. });
  27459. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  27460. set: function (callback) {
  27461. if (this._onClearObserver) {
  27462. this.onClearObservable.remove(this._onClearObserver);
  27463. }
  27464. this._onClearObserver = this.onClearObservable.add(callback);
  27465. },
  27466. enumerable: true,
  27467. configurable: true
  27468. });
  27469. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  27470. get: function () {
  27471. return this._samples;
  27472. },
  27473. set: function (value) {
  27474. if (this._samples === value) {
  27475. return;
  27476. }
  27477. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  27478. },
  27479. enumerable: true,
  27480. configurable: true
  27481. });
  27482. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  27483. this._currentRefreshId = -1;
  27484. };
  27485. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  27486. get: function () {
  27487. return this._refreshRate;
  27488. },
  27489. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27490. set: function (value) {
  27491. this._refreshRate = value;
  27492. this.resetRefreshCounter();
  27493. },
  27494. enumerable: true,
  27495. configurable: true
  27496. });
  27497. RenderTargetTexture.prototype._shouldRender = function () {
  27498. if (this._currentRefreshId === -1) {
  27499. this._currentRefreshId = 1;
  27500. return true;
  27501. }
  27502. if (this.refreshRate === this._currentRefreshId) {
  27503. this._currentRefreshId = 1;
  27504. return true;
  27505. }
  27506. this._currentRefreshId++;
  27507. return false;
  27508. };
  27509. RenderTargetTexture.prototype.isReady = function () {
  27510. if (!this.getScene().renderTargetsEnabled) {
  27511. return false;
  27512. }
  27513. return _super.prototype.isReady.call(this);
  27514. };
  27515. RenderTargetTexture.prototype.getRenderSize = function () {
  27516. return this._size;
  27517. };
  27518. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  27519. get: function () {
  27520. return true;
  27521. },
  27522. enumerable: true,
  27523. configurable: true
  27524. });
  27525. RenderTargetTexture.prototype.scale = function (ratio) {
  27526. var newSize = this._size * ratio;
  27527. this.resize(newSize);
  27528. };
  27529. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  27530. if (this.isCube) {
  27531. return this._textureMatrix;
  27532. }
  27533. return _super.prototype.getReflectionTextureMatrix.call(this);
  27534. };
  27535. RenderTargetTexture.prototype.resize = function (size) {
  27536. this.releaseInternalTexture();
  27537. if (this.isCube) {
  27538. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  27539. }
  27540. else {
  27541. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  27542. }
  27543. };
  27544. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  27545. var scene = this.getScene();
  27546. var engine = scene.getEngine();
  27547. if (this.useCameraPostProcesses !== undefined) {
  27548. useCameraPostProcess = this.useCameraPostProcesses;
  27549. }
  27550. if (this._waitingRenderList) {
  27551. this.renderList = [];
  27552. for (var index = 0; index < this._waitingRenderList.length; index++) {
  27553. var id = this._waitingRenderList[index];
  27554. this.renderList.push(scene.getMeshByID(id));
  27555. }
  27556. delete this._waitingRenderList;
  27557. }
  27558. // Is predicate defined?
  27559. if (this.renderListPredicate) {
  27560. this.renderList.splice(0); // Clear previous renderList
  27561. var sceneMeshes = this.getScene().meshes;
  27562. for (var index = 0; index < sceneMeshes.length; index++) {
  27563. var mesh = sceneMeshes[index];
  27564. if (this.renderListPredicate(mesh)) {
  27565. this.renderList.push(mesh);
  27566. }
  27567. }
  27568. }
  27569. if (this.renderList && this.renderList.length === 0) {
  27570. return;
  27571. }
  27572. // Set custom projection.
  27573. // Needs to be before binding to prevent changing the aspect ratio.
  27574. if (this.activeCamera) {
  27575. engine.setViewport(this.activeCamera.viewport);
  27576. if (this.activeCamera !== scene.activeCamera) {
  27577. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  27578. }
  27579. }
  27580. else {
  27581. engine.setViewport(scene.activeCamera.viewport);
  27582. }
  27583. // Prepare renderingManager
  27584. this._renderingManager.reset();
  27585. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  27586. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  27587. var sceneRenderId = scene.getRenderId();
  27588. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  27589. var mesh = currentRenderList[meshIndex];
  27590. if (mesh) {
  27591. if (!mesh.isReady()) {
  27592. // Reset _currentRefreshId
  27593. this.resetRefreshCounter();
  27594. continue;
  27595. }
  27596. mesh._preActivateForIntermediateRendering(sceneRenderId);
  27597. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  27598. mesh._activate(sceneRenderId);
  27599. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27600. var subMesh = mesh.subMeshes[subIndex];
  27601. scene._activeIndices.addCount(subMesh.indexCount, false);
  27602. this._renderingManager.dispatch(subMesh);
  27603. }
  27604. }
  27605. }
  27606. }
  27607. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  27608. var particleSystem = scene.particleSystems[particleIndex];
  27609. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  27610. continue;
  27611. }
  27612. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  27613. this._renderingManager.dispatchParticles(particleSystem);
  27614. }
  27615. }
  27616. if (this.isCube) {
  27617. for (var face = 0; face < 6; face++) {
  27618. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  27619. scene.incrementRenderId();
  27620. scene.resetCachedMaterial();
  27621. }
  27622. }
  27623. else {
  27624. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  27625. }
  27626. this.onAfterUnbindObservable.notifyObservers(this);
  27627. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  27628. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  27629. }
  27630. engine.setViewport(scene.activeCamera.viewport);
  27631. scene.resetCachedMaterial();
  27632. };
  27633. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  27634. var _this = this;
  27635. var scene = this.getScene();
  27636. var engine = scene.getEngine();
  27637. // Bind
  27638. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  27639. if (this.isCube) {
  27640. engine.bindFramebuffer(this._texture, faceIndex);
  27641. }
  27642. else {
  27643. engine.bindFramebuffer(this._texture);
  27644. }
  27645. }
  27646. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  27647. // Clear
  27648. if (this.onClearObservable.hasObservers()) {
  27649. this.onClearObservable.notifyObservers(engine);
  27650. }
  27651. else {
  27652. engine.clear(scene.clearColor, true, true, true);
  27653. }
  27654. if (!this._doNotChangeAspectRatio) {
  27655. scene.updateTransformMatrix(true);
  27656. }
  27657. // Render
  27658. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  27659. if (useCameraPostProcess) {
  27660. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  27661. }
  27662. if (!this._doNotChangeAspectRatio) {
  27663. scene.updateTransformMatrix(true);
  27664. }
  27665. // Dump ?
  27666. if (dumpForDebug) {
  27667. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  27668. }
  27669. // Unbind
  27670. if (!this.isCube || faceIndex === 5) {
  27671. if (this.isCube) {
  27672. if (faceIndex === 5) {
  27673. engine.generateMipMapsForCubemap(this._texture);
  27674. }
  27675. }
  27676. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  27677. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  27678. });
  27679. }
  27680. else {
  27681. this.onAfterRenderObservable.notifyObservers(faceIndex);
  27682. }
  27683. };
  27684. /**
  27685. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  27686. * This allowed control for front to back rendering or reversly depending of the special needs.
  27687. *
  27688. * @param renderingGroupId The rendering group id corresponding to its index
  27689. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  27690. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  27691. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  27692. */
  27693. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  27694. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  27695. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  27696. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  27697. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  27698. };
  27699. /**
  27700. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  27701. *
  27702. * @param renderingGroupId The rendering group id corresponding to its index
  27703. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  27704. */
  27705. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  27706. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  27707. };
  27708. RenderTargetTexture.prototype.clone = function () {
  27709. var textureSize = this.getSize();
  27710. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  27711. // Base texture
  27712. newTexture.hasAlpha = this.hasAlpha;
  27713. newTexture.level = this.level;
  27714. // RenderTarget Texture
  27715. newTexture.coordinatesMode = this.coordinatesMode;
  27716. newTexture.renderList = this.renderList.slice(0);
  27717. return newTexture;
  27718. };
  27719. RenderTargetTexture.prototype.serialize = function () {
  27720. if (!this.name) {
  27721. return null;
  27722. }
  27723. var serializationObject = _super.prototype.serialize.call(this);
  27724. serializationObject.renderTargetSize = this.getRenderSize();
  27725. serializationObject.renderList = [];
  27726. for (var index = 0; index < this.renderList.length; index++) {
  27727. serializationObject.renderList.push(this.renderList[index].id);
  27728. }
  27729. return serializationObject;
  27730. };
  27731. return RenderTargetTexture;
  27732. }(BABYLON.Texture));
  27733. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  27734. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  27735. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  27736. BABYLON.RenderTargetTexture = RenderTargetTexture;
  27737. })(BABYLON || (BABYLON = {}));
  27738. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  27739. var BABYLON;
  27740. (function (BABYLON) {
  27741. var ProceduralTexture = (function (_super) {
  27742. __extends(ProceduralTexture, _super);
  27743. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  27744. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27745. if (isCube === void 0) { isCube = false; }
  27746. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27747. _this.isCube = isCube;
  27748. _this.isEnabled = true;
  27749. _this._currentRefreshId = -1;
  27750. _this._refreshRate = 1;
  27751. _this._vertexBuffers = {};
  27752. _this._uniforms = new Array();
  27753. _this._samplers = new Array();
  27754. _this._textures = new Array();
  27755. _this._floats = new Array();
  27756. _this._floatsArrays = {};
  27757. _this._colors3 = new Array();
  27758. _this._colors4 = new Array();
  27759. _this._vectors2 = new Array();
  27760. _this._vectors3 = new Array();
  27761. _this._matrices = new Array();
  27762. _this._fallbackTextureUsed = false;
  27763. scene._proceduralTextures.push(_this);
  27764. _this.name = name;
  27765. _this.isRenderTarget = true;
  27766. _this._size = size;
  27767. _this._generateMipMaps = generateMipMaps;
  27768. _this.setFragment(fragment);
  27769. _this._fallbackTexture = fallbackTexture;
  27770. var engine = scene.getEngine();
  27771. if (isCube) {
  27772. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  27773. _this.setFloat("face", 0);
  27774. }
  27775. else {
  27776. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  27777. }
  27778. // VBO
  27779. var vertices = [];
  27780. vertices.push(1, 1);
  27781. vertices.push(-1, 1);
  27782. vertices.push(-1, -1);
  27783. vertices.push(1, -1);
  27784. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27785. // Indices
  27786. var indices = [];
  27787. indices.push(0);
  27788. indices.push(1);
  27789. indices.push(2);
  27790. indices.push(0);
  27791. indices.push(2);
  27792. indices.push(3);
  27793. _this._indexBuffer = engine.createIndexBuffer(indices);
  27794. return _this;
  27795. }
  27796. ProceduralTexture.prototype.reset = function () {
  27797. if (this._effect === undefined) {
  27798. return;
  27799. }
  27800. var engine = this.getScene().getEngine();
  27801. engine._releaseEffect(this._effect);
  27802. };
  27803. ProceduralTexture.prototype.isReady = function () {
  27804. var _this = this;
  27805. var engine = this.getScene().getEngine();
  27806. var shaders;
  27807. if (!this._fragment) {
  27808. return false;
  27809. }
  27810. if (this._fallbackTextureUsed) {
  27811. return true;
  27812. }
  27813. if (this._fragment.fragmentElement !== undefined) {
  27814. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  27815. }
  27816. else {
  27817. shaders = { vertex: "procedural", fragment: this._fragment };
  27818. }
  27819. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  27820. _this.releaseInternalTexture();
  27821. if (_this._fallbackTexture) {
  27822. _this._texture = _this._fallbackTexture._texture;
  27823. _this._texture.references++;
  27824. }
  27825. _this._fallbackTextureUsed = true;
  27826. });
  27827. return this._effect.isReady();
  27828. };
  27829. ProceduralTexture.prototype.resetRefreshCounter = function () {
  27830. this._currentRefreshId = -1;
  27831. };
  27832. ProceduralTexture.prototype.setFragment = function (fragment) {
  27833. this._fragment = fragment;
  27834. };
  27835. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  27836. get: function () {
  27837. return this._refreshRate;
  27838. },
  27839. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27840. set: function (value) {
  27841. this._refreshRate = value;
  27842. this.resetRefreshCounter();
  27843. },
  27844. enumerable: true,
  27845. configurable: true
  27846. });
  27847. ProceduralTexture.prototype._shouldRender = function () {
  27848. if (!this.isEnabled || !this.isReady() || !this._texture) {
  27849. return false;
  27850. }
  27851. if (this._fallbackTextureUsed) {
  27852. return false;
  27853. }
  27854. if (this._currentRefreshId === -1) {
  27855. this._currentRefreshId = 1;
  27856. return true;
  27857. }
  27858. if (this.refreshRate === this._currentRefreshId) {
  27859. this._currentRefreshId = 1;
  27860. return true;
  27861. }
  27862. this._currentRefreshId++;
  27863. return false;
  27864. };
  27865. ProceduralTexture.prototype.getRenderSize = function () {
  27866. return this._size;
  27867. };
  27868. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  27869. if (this._fallbackTextureUsed) {
  27870. return;
  27871. }
  27872. this.releaseInternalTexture();
  27873. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  27874. };
  27875. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  27876. if (this._uniforms.indexOf(uniformName) === -1) {
  27877. this._uniforms.push(uniformName);
  27878. }
  27879. };
  27880. ProceduralTexture.prototype.setTexture = function (name, texture) {
  27881. if (this._samplers.indexOf(name) === -1) {
  27882. this._samplers.push(name);
  27883. }
  27884. this._textures[name] = texture;
  27885. return this;
  27886. };
  27887. ProceduralTexture.prototype.setFloat = function (name, value) {
  27888. this._checkUniform(name);
  27889. this._floats[name] = value;
  27890. return this;
  27891. };
  27892. ProceduralTexture.prototype.setFloats = function (name, value) {
  27893. this._checkUniform(name);
  27894. this._floatsArrays[name] = value;
  27895. return this;
  27896. };
  27897. ProceduralTexture.prototype.setColor3 = function (name, value) {
  27898. this._checkUniform(name);
  27899. this._colors3[name] = value;
  27900. return this;
  27901. };
  27902. ProceduralTexture.prototype.setColor4 = function (name, value) {
  27903. this._checkUniform(name);
  27904. this._colors4[name] = value;
  27905. return this;
  27906. };
  27907. ProceduralTexture.prototype.setVector2 = function (name, value) {
  27908. this._checkUniform(name);
  27909. this._vectors2[name] = value;
  27910. return this;
  27911. };
  27912. ProceduralTexture.prototype.setVector3 = function (name, value) {
  27913. this._checkUniform(name);
  27914. this._vectors3[name] = value;
  27915. return this;
  27916. };
  27917. ProceduralTexture.prototype.setMatrix = function (name, value) {
  27918. this._checkUniform(name);
  27919. this._matrices[name] = value;
  27920. return this;
  27921. };
  27922. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  27923. var scene = this.getScene();
  27924. var engine = scene.getEngine();
  27925. // Render
  27926. engine.enableEffect(this._effect);
  27927. engine.setState(false);
  27928. // Texture
  27929. for (var name in this._textures) {
  27930. this._effect.setTexture(name, this._textures[name]);
  27931. }
  27932. // Float
  27933. for (name in this._floats) {
  27934. this._effect.setFloat(name, this._floats[name]);
  27935. }
  27936. // Floats
  27937. for (name in this._floatsArrays) {
  27938. this._effect.setArray(name, this._floatsArrays[name]);
  27939. }
  27940. // Color3
  27941. for (name in this._colors3) {
  27942. this._effect.setColor3(name, this._colors3[name]);
  27943. }
  27944. // Color4
  27945. for (name in this._colors4) {
  27946. var color = this._colors4[name];
  27947. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27948. }
  27949. // Vector2
  27950. for (name in this._vectors2) {
  27951. this._effect.setVector2(name, this._vectors2[name]);
  27952. }
  27953. // Vector3
  27954. for (name in this._vectors3) {
  27955. this._effect.setVector3(name, this._vectors3[name]);
  27956. }
  27957. // Matrix
  27958. for (name in this._matrices) {
  27959. this._effect.setMatrix(name, this._matrices[name]);
  27960. }
  27961. if (this.isCube) {
  27962. for (var face = 0; face < 6; face++) {
  27963. engine.bindFramebuffer(this._texture, face);
  27964. // VBOs
  27965. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  27966. this._effect.setFloat("face", face);
  27967. // Clear
  27968. engine.clear(scene.clearColor, true, true, true);
  27969. // Draw order
  27970. engine.draw(true, 0, 6);
  27971. // Mipmaps
  27972. if (face === 5) {
  27973. engine.generateMipMapsForCubemap(this._texture);
  27974. }
  27975. }
  27976. }
  27977. else {
  27978. engine.bindFramebuffer(this._texture);
  27979. // VBOs
  27980. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  27981. // Clear
  27982. engine.clear(scene.clearColor, true, true, true);
  27983. // Draw order
  27984. engine.draw(true, 0, 6);
  27985. }
  27986. // Unbind
  27987. engine.unBindFramebuffer(this._texture, this.isCube);
  27988. if (this.onGenerated) {
  27989. this.onGenerated();
  27990. }
  27991. };
  27992. ProceduralTexture.prototype.clone = function () {
  27993. var textureSize = this.getSize();
  27994. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  27995. // Base texture
  27996. newTexture.hasAlpha = this.hasAlpha;
  27997. newTexture.level = this.level;
  27998. // RenderTarget Texture
  27999. newTexture.coordinatesMode = this.coordinatesMode;
  28000. return newTexture;
  28001. };
  28002. ProceduralTexture.prototype.dispose = function () {
  28003. var index = this.getScene()._proceduralTextures.indexOf(this);
  28004. if (index >= 0) {
  28005. this.getScene()._proceduralTextures.splice(index, 1);
  28006. }
  28007. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28008. if (vertexBuffer) {
  28009. vertexBuffer.dispose();
  28010. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28011. }
  28012. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  28013. this._indexBuffer = null;
  28014. }
  28015. _super.prototype.dispose.call(this);
  28016. };
  28017. return ProceduralTexture;
  28018. }(BABYLON.Texture));
  28019. BABYLON.ProceduralTexture = ProceduralTexture;
  28020. })(BABYLON || (BABYLON = {}));
  28021. //# sourceMappingURL=babylon.proceduralTexture.js.map
  28022. /// <reference path="babylon.renderTargetTexture.ts" />
  28023. var BABYLON;
  28024. (function (BABYLON) {
  28025. var MirrorTexture = (function (_super) {
  28026. __extends(MirrorTexture, _super);
  28027. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  28028. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28029. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28030. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  28031. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  28032. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  28033. _this._transformMatrix = BABYLON.Matrix.Zero();
  28034. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  28035. _this.onBeforeRenderObservable.add(function () {
  28036. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  28037. _this._savedViewMatrix = scene.getViewMatrix();
  28038. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  28039. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  28040. scene.clipPlane = _this.mirrorPlane;
  28041. scene.getEngine().cullBackFaces = false;
  28042. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  28043. });
  28044. _this.onAfterRenderObservable.add(function () {
  28045. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  28046. scene.getEngine().cullBackFaces = true;
  28047. scene._mirroredCameraPosition = null;
  28048. delete scene.clipPlane;
  28049. });
  28050. return _this;
  28051. }
  28052. MirrorTexture.prototype.clone = function () {
  28053. var textureSize = this.getSize();
  28054. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  28055. // Base texture
  28056. newTexture.hasAlpha = this.hasAlpha;
  28057. newTexture.level = this.level;
  28058. // Mirror Texture
  28059. newTexture.mirrorPlane = this.mirrorPlane.clone();
  28060. newTexture.renderList = this.renderList.slice(0);
  28061. return newTexture;
  28062. };
  28063. MirrorTexture.prototype.serialize = function () {
  28064. if (!this.name) {
  28065. return null;
  28066. }
  28067. var serializationObject = _super.prototype.serialize.call(this);
  28068. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  28069. return serializationObject;
  28070. };
  28071. return MirrorTexture;
  28072. }(BABYLON.RenderTargetTexture));
  28073. BABYLON.MirrorTexture = MirrorTexture;
  28074. })(BABYLON || (BABYLON = {}));
  28075. //# sourceMappingURL=babylon.mirrorTexture.js.map
  28076. /// <reference path="babylon.renderTargetTexture.ts" />
  28077. var BABYLON;
  28078. (function (BABYLON) {
  28079. /**
  28080. * Creates a refraction texture used by refraction channel of the standard material.
  28081. * @param name the texture name
  28082. * @param size size of the underlying texture
  28083. * @param scene root scene
  28084. */
  28085. var RefractionTexture = (function (_super) {
  28086. __extends(RefractionTexture, _super);
  28087. function RefractionTexture(name, size, scene, generateMipMaps) {
  28088. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  28089. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  28090. _this.depth = 2.0;
  28091. _this.onBeforeRenderObservable.add(function () {
  28092. scene.clipPlane = _this.refractionPlane;
  28093. });
  28094. _this.onAfterRenderObservable.add(function () {
  28095. delete scene.clipPlane;
  28096. });
  28097. return _this;
  28098. }
  28099. RefractionTexture.prototype.clone = function () {
  28100. var textureSize = this.getSize();
  28101. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  28102. // Base texture
  28103. newTexture.hasAlpha = this.hasAlpha;
  28104. newTexture.level = this.level;
  28105. // Refraction Texture
  28106. newTexture.refractionPlane = this.refractionPlane.clone();
  28107. newTexture.renderList = this.renderList.slice(0);
  28108. newTexture.depth = this.depth;
  28109. return newTexture;
  28110. };
  28111. RefractionTexture.prototype.serialize = function () {
  28112. if (!this.name) {
  28113. return null;
  28114. }
  28115. var serializationObject = _super.prototype.serialize.call(this);
  28116. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  28117. serializationObject.depth = this.depth;
  28118. return serializationObject;
  28119. };
  28120. return RefractionTexture;
  28121. }(BABYLON.RenderTargetTexture));
  28122. BABYLON.RefractionTexture = RefractionTexture;
  28123. })(BABYLON || (BABYLON = {}));
  28124. //# sourceMappingURL=babylon.refractionTexture.js.map
  28125. /// <reference path="babylon.texture.ts" />
  28126. var BABYLON;
  28127. (function (BABYLON) {
  28128. var DynamicTexture = (function (_super) {
  28129. __extends(DynamicTexture, _super);
  28130. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  28131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28132. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28133. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  28134. _this.name = name;
  28135. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28136. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28137. _this._generateMipMaps = generateMipMaps;
  28138. if (options.getContext) {
  28139. _this._canvas = options;
  28140. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28141. }
  28142. else {
  28143. _this._canvas = document.createElement("canvas");
  28144. if (options.width) {
  28145. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28146. }
  28147. else {
  28148. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  28149. }
  28150. }
  28151. var textureSize = _this.getSize();
  28152. _this._canvas.width = textureSize.width;
  28153. _this._canvas.height = textureSize.height;
  28154. _this._context = _this._canvas.getContext("2d");
  28155. return _this;
  28156. }
  28157. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  28158. get: function () {
  28159. return true;
  28160. },
  28161. enumerable: true,
  28162. configurable: true
  28163. });
  28164. DynamicTexture.prototype.scale = function (ratio) {
  28165. var textureSize = this.getSize();
  28166. textureSize.width *= ratio;
  28167. textureSize.height *= ratio;
  28168. this._canvas.width = textureSize.width;
  28169. this._canvas.height = textureSize.height;
  28170. this.releaseInternalTexture();
  28171. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  28172. };
  28173. DynamicTexture.prototype.getContext = function () {
  28174. return this._context;
  28175. };
  28176. DynamicTexture.prototype.clear = function () {
  28177. var size = this.getSize();
  28178. this._context.fillRect(0, 0, size.width, size.height);
  28179. };
  28180. DynamicTexture.prototype.update = function (invertY) {
  28181. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  28182. };
  28183. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  28184. if (update === void 0) { update = true; }
  28185. var size = this.getSize();
  28186. if (clearColor) {
  28187. this._context.fillStyle = clearColor;
  28188. this._context.fillRect(0, 0, size.width, size.height);
  28189. }
  28190. this._context.font = font;
  28191. if (x === null || x === undefined) {
  28192. var textSize = this._context.measureText(text);
  28193. x = (size.width - textSize.width) / 2;
  28194. }
  28195. if (y === null || y === undefined) {
  28196. var fontSize = parseInt((font.replace(/\D/g, '')));
  28197. ;
  28198. y = (size.height / 2) + (fontSize / 3.65);
  28199. }
  28200. this._context.fillStyle = color;
  28201. this._context.fillText(text, x, y);
  28202. if (update) {
  28203. this.update(invertY);
  28204. }
  28205. };
  28206. DynamicTexture.prototype.clone = function () {
  28207. var textureSize = this.getSize();
  28208. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  28209. // Base texture
  28210. newTexture.hasAlpha = this.hasAlpha;
  28211. newTexture.level = this.level;
  28212. // Dynamic Texture
  28213. newTexture.wrapU = this.wrapU;
  28214. newTexture.wrapV = this.wrapV;
  28215. return newTexture;
  28216. };
  28217. return DynamicTexture;
  28218. }(BABYLON.Texture));
  28219. BABYLON.DynamicTexture = DynamicTexture;
  28220. })(BABYLON || (BABYLON = {}));
  28221. //# sourceMappingURL=babylon.dynamicTexture.js.map
  28222. var BABYLON;
  28223. (function (BABYLON) {
  28224. var VideoTexture = (function (_super) {
  28225. __extends(VideoTexture, _super);
  28226. /**
  28227. * Creates a video texture.
  28228. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  28229. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  28230. * @param {BABYLON.Scene} scene is obviously the current scene.
  28231. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  28232. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  28233. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  28234. */
  28235. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  28236. if (generateMipMaps === void 0) { generateMipMaps = false; }
  28237. if (invertY === void 0) { invertY = false; }
  28238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28239. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  28240. _this._autoLaunch = true;
  28241. var urls;
  28242. _this.name = name;
  28243. if (urlsOrVideo instanceof HTMLVideoElement) {
  28244. _this.video = urlsOrVideo;
  28245. }
  28246. else {
  28247. urls = urlsOrVideo;
  28248. _this.video = document.createElement("video");
  28249. _this.video.autoplay = false;
  28250. _this.video.loop = true;
  28251. }
  28252. _this._generateMipMaps = generateMipMaps;
  28253. _this._samplingMode = samplingMode;
  28254. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  28255. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28256. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28257. }
  28258. else {
  28259. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28260. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28261. _this._generateMipMaps = false;
  28262. }
  28263. if (urls) {
  28264. _this.video.addEventListener("canplaythrough", function () {
  28265. _this._createTexture();
  28266. });
  28267. urls.forEach(function (url) {
  28268. var source = document.createElement("source");
  28269. source.src = url;
  28270. _this.video.appendChild(source);
  28271. });
  28272. }
  28273. else {
  28274. _this._createTexture();
  28275. }
  28276. _this._lastUpdate = BABYLON.Tools.Now;
  28277. return _this;
  28278. }
  28279. VideoTexture.prototype._createTexture = function () {
  28280. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  28281. this._texture.isReady = true;
  28282. };
  28283. VideoTexture.prototype.update = function () {
  28284. if (this._autoLaunch) {
  28285. this._autoLaunch = false;
  28286. this.video.play();
  28287. }
  28288. var now = BABYLON.Tools.Now;
  28289. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  28290. return false;
  28291. }
  28292. this._lastUpdate = now;
  28293. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  28294. return true;
  28295. };
  28296. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  28297. var video = document.createElement("video");
  28298. var constraintsDeviceId;
  28299. if (constraints && constraints.deviceId) {
  28300. constraintsDeviceId = {
  28301. exact: constraints.deviceId
  28302. };
  28303. }
  28304. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  28305. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  28306. if (navigator.getUserMedia) {
  28307. navigator.getUserMedia({
  28308. video: {
  28309. deviceId: constraintsDeviceId,
  28310. width: {
  28311. min: (constraints && constraints.minWidth) || 256,
  28312. max: (constraints && constraints.maxWidth) || 640
  28313. },
  28314. height: {
  28315. min: (constraints && constraints.minHeight) || 256,
  28316. max: (constraints && constraints.maxHeight) || 480
  28317. }
  28318. }
  28319. }, function (stream) {
  28320. if (video.mozSrcObject !== undefined) {
  28321. video.mozSrcObject = stream;
  28322. }
  28323. else {
  28324. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  28325. }
  28326. video.play();
  28327. if (onReady) {
  28328. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  28329. }
  28330. }, function (e) {
  28331. BABYLON.Tools.Error(e.name);
  28332. });
  28333. }
  28334. };
  28335. return VideoTexture;
  28336. }(BABYLON.Texture));
  28337. BABYLON.VideoTexture = VideoTexture;
  28338. })(BABYLON || (BABYLON = {}));
  28339. //# sourceMappingURL=babylon.videoTexture.js.map
  28340. /// <reference path="babylon.proceduralTexture.ts" />
  28341. var BABYLON;
  28342. (function (BABYLON) {
  28343. var CustomProceduralTexture = (function (_super) {
  28344. __extends(CustomProceduralTexture, _super);
  28345. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  28346. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  28347. _this._animate = true;
  28348. _this._time = 0;
  28349. _this._texturePath = texturePath;
  28350. //Try to load json
  28351. _this.loadJson(texturePath);
  28352. _this.refreshRate = 1;
  28353. return _this;
  28354. }
  28355. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  28356. var _this = this;
  28357. var that = this;
  28358. function noConfigFile() {
  28359. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  28360. try {
  28361. that.setFragment(that._texturePath);
  28362. }
  28363. catch (ex) {
  28364. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  28365. }
  28366. }
  28367. var configFileUrl = jsonUrl + "/config.json";
  28368. var xhr = new XMLHttpRequest();
  28369. xhr.open("GET", configFileUrl, true);
  28370. xhr.addEventListener("load", function () {
  28371. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  28372. try {
  28373. _this._config = JSON.parse(xhr.response);
  28374. _this.updateShaderUniforms();
  28375. _this.updateTextures();
  28376. _this.setFragment(_this._texturePath + "/custom");
  28377. _this._animate = _this._config.animate;
  28378. _this.refreshRate = _this._config.refreshrate;
  28379. }
  28380. catch (ex) {
  28381. noConfigFile();
  28382. }
  28383. }
  28384. else {
  28385. noConfigFile();
  28386. }
  28387. }, false);
  28388. xhr.addEventListener("error", function () {
  28389. noConfigFile();
  28390. }, false);
  28391. try {
  28392. xhr.send();
  28393. }
  28394. catch (ex) {
  28395. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  28396. }
  28397. };
  28398. CustomProceduralTexture.prototype.isReady = function () {
  28399. if (!_super.prototype.isReady.call(this)) {
  28400. return false;
  28401. }
  28402. for (var name in this._textures) {
  28403. var texture = this._textures[name];
  28404. if (!texture.isReady()) {
  28405. return false;
  28406. }
  28407. }
  28408. return true;
  28409. };
  28410. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  28411. if (this._animate) {
  28412. this._time += this.getScene().getAnimationRatio() * 0.03;
  28413. this.updateShaderUniforms();
  28414. }
  28415. _super.prototype.render.call(this, useCameraPostProcess);
  28416. };
  28417. CustomProceduralTexture.prototype.updateTextures = function () {
  28418. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  28419. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  28420. }
  28421. };
  28422. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  28423. if (this._config) {
  28424. for (var j = 0; j < this._config.uniforms.length; j++) {
  28425. var uniform = this._config.uniforms[j];
  28426. switch (uniform.type) {
  28427. case "float":
  28428. this.setFloat(uniform.name, uniform.value);
  28429. break;
  28430. case "color3":
  28431. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  28432. break;
  28433. case "color4":
  28434. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  28435. break;
  28436. case "vector2":
  28437. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  28438. break;
  28439. case "vector3":
  28440. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  28441. break;
  28442. }
  28443. }
  28444. }
  28445. this.setFloat("time", this._time);
  28446. };
  28447. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  28448. get: function () {
  28449. return this._animate;
  28450. },
  28451. set: function (value) {
  28452. this._animate = value;
  28453. },
  28454. enumerable: true,
  28455. configurable: true
  28456. });
  28457. return CustomProceduralTexture;
  28458. }(BABYLON.ProceduralTexture));
  28459. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  28460. })(BABYLON || (BABYLON = {}));
  28461. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  28462. var BABYLON;
  28463. (function (BABYLON) {
  28464. var EffectFallbacks = (function () {
  28465. function EffectFallbacks() {
  28466. this._defines = {};
  28467. this._currentRank = 32;
  28468. this._maxRank = -1;
  28469. }
  28470. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28471. if (!this._defines[rank]) {
  28472. if (rank < this._currentRank) {
  28473. this._currentRank = rank;
  28474. }
  28475. if (rank > this._maxRank) {
  28476. this._maxRank = rank;
  28477. }
  28478. this._defines[rank] = new Array();
  28479. }
  28480. this._defines[rank].push(define);
  28481. };
  28482. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  28483. this._meshRank = rank;
  28484. this._mesh = mesh;
  28485. if (rank < this._currentRank) {
  28486. this._currentRank = rank;
  28487. }
  28488. if (rank > this._maxRank) {
  28489. this._maxRank = rank;
  28490. }
  28491. };
  28492. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  28493. get: function () {
  28494. return this._currentRank <= this._maxRank;
  28495. },
  28496. enumerable: true,
  28497. configurable: true
  28498. });
  28499. EffectFallbacks.prototype.reduce = function (currentDefines) {
  28500. // First we try to switch to CPU skinning
  28501. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  28502. this._mesh.computeBonesUsingShaders = false;
  28503. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  28504. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  28505. var scene = this._mesh.getScene();
  28506. for (var index = 0; index < scene.meshes.length; index++) {
  28507. var otherMesh = scene.meshes[index];
  28508. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  28509. otherMesh.computeBonesUsingShaders = false;
  28510. }
  28511. }
  28512. }
  28513. else {
  28514. var currentFallbacks = this._defines[this._currentRank];
  28515. if (currentFallbacks) {
  28516. for (var index = 0; index < currentFallbacks.length; index++) {
  28517. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  28518. }
  28519. }
  28520. this._currentRank++;
  28521. }
  28522. return currentDefines;
  28523. };
  28524. return EffectFallbacks;
  28525. }());
  28526. BABYLON.EffectFallbacks = EffectFallbacks;
  28527. var Effect = (function () {
  28528. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  28529. var _this = this;
  28530. this.uniqueId = 0;
  28531. this._isReady = false;
  28532. this._compilationError = "";
  28533. this._valueCache = {};
  28534. this._engine = engine;
  28535. this.name = baseName;
  28536. this.defines = defines;
  28537. this._uniformsNames = uniformsNames.concat(samplers);
  28538. this._samplers = samplers;
  28539. this._attributesNames = attributesNames;
  28540. this.onError = onError;
  28541. this.onCompiled = onCompiled;
  28542. this._indexParameters = indexParameters;
  28543. this.uniqueId = Effect._uniqueIdSeed++;
  28544. var vertexSource;
  28545. var fragmentSource;
  28546. if (baseName.vertexElement) {
  28547. vertexSource = document.getElementById(baseName.vertexElement);
  28548. if (!vertexSource) {
  28549. vertexSource = baseName.vertexElement;
  28550. }
  28551. }
  28552. else {
  28553. vertexSource = baseName.vertex || baseName;
  28554. }
  28555. if (baseName.fragmentElement) {
  28556. fragmentSource = document.getElementById(baseName.fragmentElement);
  28557. if (!fragmentSource) {
  28558. fragmentSource = baseName.fragmentElement;
  28559. }
  28560. }
  28561. else {
  28562. fragmentSource = baseName.fragment || baseName;
  28563. }
  28564. this._loadVertexShader(vertexSource, function (vertexCode) {
  28565. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  28566. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  28567. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  28568. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  28569. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  28570. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  28571. });
  28572. });
  28573. });
  28574. });
  28575. });
  28576. });
  28577. }
  28578. Object.defineProperty(Effect.prototype, "key", {
  28579. get: function () {
  28580. return this._key;
  28581. },
  28582. enumerable: true,
  28583. configurable: true
  28584. });
  28585. // Properties
  28586. Effect.prototype.isReady = function () {
  28587. return this._isReady;
  28588. };
  28589. Effect.prototype.getProgram = function () {
  28590. return this._program;
  28591. };
  28592. Effect.prototype.getAttributesNames = function () {
  28593. return this._attributesNames;
  28594. };
  28595. Effect.prototype.getAttributeLocation = function (index) {
  28596. return this._attributes[index];
  28597. };
  28598. Effect.prototype.getAttributeLocationByName = function (name) {
  28599. var index = this._attributesNames.indexOf(name);
  28600. return this._attributes[index];
  28601. };
  28602. Effect.prototype.getAttributesCount = function () {
  28603. return this._attributes.length;
  28604. };
  28605. Effect.prototype.getUniformIndex = function (uniformName) {
  28606. return this._uniformsNames.indexOf(uniformName);
  28607. };
  28608. Effect.prototype.getUniform = function (uniformName) {
  28609. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  28610. };
  28611. Effect.prototype.getSamplers = function () {
  28612. return this._samplers;
  28613. };
  28614. Effect.prototype.getCompilationError = function () {
  28615. return this._compilationError;
  28616. };
  28617. Effect.prototype.getVertexShaderSource = function () {
  28618. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  28619. };
  28620. Effect.prototype.getFragmentShaderSource = function () {
  28621. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  28622. };
  28623. // Methods
  28624. Effect.prototype._loadVertexShader = function (vertex, callback) {
  28625. // DOM element ?
  28626. if (vertex instanceof HTMLElement) {
  28627. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  28628. callback(vertexCode);
  28629. return;
  28630. }
  28631. // Base64 encoded ?
  28632. if (vertex.substr(0, 7) === "base64:") {
  28633. var vertexBinary = window.atob(vertex.substr(7));
  28634. callback(vertexBinary);
  28635. return;
  28636. }
  28637. // Is in local store ?
  28638. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  28639. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  28640. return;
  28641. }
  28642. var vertexShaderUrl;
  28643. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  28644. vertexShaderUrl = vertex;
  28645. }
  28646. else {
  28647. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  28648. }
  28649. // Vertex shader
  28650. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  28651. };
  28652. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  28653. // DOM element ?
  28654. if (fragment instanceof HTMLElement) {
  28655. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  28656. callback(fragmentCode);
  28657. return;
  28658. }
  28659. // Base64 encoded ?
  28660. if (fragment.substr(0, 7) === "base64:") {
  28661. var fragmentBinary = window.atob(fragment.substr(7));
  28662. callback(fragmentBinary);
  28663. return;
  28664. }
  28665. // Is in local store ?
  28666. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  28667. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  28668. return;
  28669. }
  28670. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  28671. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  28672. return;
  28673. }
  28674. var fragmentShaderUrl;
  28675. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  28676. fragmentShaderUrl = fragment;
  28677. }
  28678. else {
  28679. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  28680. }
  28681. // Fragment shader
  28682. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  28683. };
  28684. Effect.prototype._dumpShadersName = function () {
  28685. if (this.name.vertexElement) {
  28686. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  28687. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  28688. }
  28689. else if (this.name.vertex) {
  28690. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  28691. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  28692. }
  28693. else {
  28694. BABYLON.Tools.Error("Vertex shader:" + this.name);
  28695. BABYLON.Tools.Error("Fragment shader:" + this.name);
  28696. }
  28697. };
  28698. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  28699. var preparedSourceCode = this._processPrecision(sourceCode);
  28700. if (this._engine.webGLVersion == 1) {
  28701. callback(preparedSourceCode);
  28702. return;
  28703. }
  28704. // Already converted
  28705. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  28706. callback(preparedSourceCode);
  28707. return;
  28708. }
  28709. // Remove extensions
  28710. // #extension GL_OES_standard_derivatives : enable
  28711. // #extension GL_EXT_shader_texture_lod : enable
  28712. // #extension GL_EXT_frag_depth : enable
  28713. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  28714. var result = preparedSourceCode.replace(regex, "");
  28715. // Migrate to GLSL v300
  28716. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  28717. result = result.replace(/attribute[ \t]/g, "in ");
  28718. result = result.replace(/[ \t]attribute/g, " in");
  28719. if (isFragment) {
  28720. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  28721. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  28722. result = result.replace(/texture2D\(/g, "texture(");
  28723. result = result.replace(/textureCube\(/g, "texture(");
  28724. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  28725. result = result.replace(/gl_FragColor/g, "glFragColor");
  28726. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  28727. }
  28728. callback(result);
  28729. };
  28730. Effect.prototype._processIncludes = function (sourceCode, callback) {
  28731. var _this = this;
  28732. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  28733. var match = regex.exec(sourceCode);
  28734. var returnValue = new String(sourceCode);
  28735. while (match != null) {
  28736. var includeFile = match[1];
  28737. if (Effect.IncludesShadersStore[includeFile]) {
  28738. // Substitution
  28739. var includeContent = Effect.IncludesShadersStore[includeFile];
  28740. if (match[2]) {
  28741. var splits = match[3].split(",");
  28742. for (var index = 0; index < splits.length; index += 2) {
  28743. var source = new RegExp(splits[index], "g");
  28744. var dest = splits[index + 1];
  28745. includeContent = includeContent.replace(source, dest);
  28746. }
  28747. }
  28748. if (match[4]) {
  28749. var indexString = match[5];
  28750. if (indexString.indexOf("..") !== -1) {
  28751. var indexSplits = indexString.split("..");
  28752. var minIndex = parseInt(indexSplits[0]);
  28753. var maxIndex = parseInt(indexSplits[1]);
  28754. var sourceIncludeContent = includeContent.slice(0);
  28755. includeContent = "";
  28756. if (isNaN(maxIndex)) {
  28757. maxIndex = this._indexParameters[indexSplits[1]];
  28758. }
  28759. for (var i = minIndex; i <= maxIndex; i++) {
  28760. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  28761. }
  28762. }
  28763. else {
  28764. includeContent = includeContent.replace(/\{X\}/g, indexString);
  28765. }
  28766. }
  28767. // Replace
  28768. returnValue = returnValue.replace(match[0], includeContent);
  28769. }
  28770. else {
  28771. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  28772. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  28773. Effect.IncludesShadersStore[includeFile] = fileContent;
  28774. _this._processIncludes(returnValue, callback);
  28775. });
  28776. return;
  28777. }
  28778. match = regex.exec(sourceCode);
  28779. }
  28780. callback(returnValue);
  28781. };
  28782. Effect.prototype._processPrecision = function (source) {
  28783. if (source.indexOf("precision highp float") === -1) {
  28784. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28785. source = "precision mediump float;\n" + source;
  28786. }
  28787. else {
  28788. source = "precision highp float;\n" + source;
  28789. }
  28790. }
  28791. else {
  28792. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28793. source = source.replace("precision highp float", "precision mediump float");
  28794. }
  28795. }
  28796. return source;
  28797. };
  28798. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  28799. try {
  28800. var engine = this._engine;
  28801. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  28802. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  28803. this._attributes = engine.getAttributes(this._program, attributesNames);
  28804. var index;
  28805. for (index = 0; index < this._samplers.length; index++) {
  28806. var sampler = this.getUniform(this._samplers[index]);
  28807. if (sampler == null) {
  28808. this._samplers.splice(index, 1);
  28809. index--;
  28810. }
  28811. }
  28812. engine.bindSamplers(this);
  28813. this._compilationError = "";
  28814. this._isReady = true;
  28815. if (this.onCompiled) {
  28816. this.onCompiled(this);
  28817. }
  28818. }
  28819. catch (e) {
  28820. this._compilationError = e.message;
  28821. // Let's go through fallbacks then
  28822. BABYLON.Tools.Error("Unable to compile effect: ");
  28823. BABYLON.Tools.Error("Defines: " + defines);
  28824. BABYLON.Tools.Error("Error: " + this._compilationError);
  28825. this._dumpShadersName();
  28826. if (fallbacks && fallbacks.isMoreFallbacks) {
  28827. BABYLON.Tools.Error("Trying next fallback.");
  28828. defines = fallbacks.reduce(defines);
  28829. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  28830. }
  28831. else {
  28832. if (this.onError) {
  28833. this.onError(this, this._compilationError);
  28834. }
  28835. }
  28836. }
  28837. };
  28838. Object.defineProperty(Effect.prototype, "isSupported", {
  28839. get: function () {
  28840. return this._compilationError === "";
  28841. },
  28842. enumerable: true,
  28843. configurable: true
  28844. });
  28845. Effect.prototype._bindTexture = function (channel, texture) {
  28846. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  28847. };
  28848. Effect.prototype.setTexture = function (channel, texture) {
  28849. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  28850. };
  28851. Effect.prototype.setTextureArray = function (channel, textures) {
  28852. if (this._samplers.indexOf(channel + "Ex") === -1) {
  28853. var initialPos = this._samplers.indexOf(channel);
  28854. for (var index = 1; index < textures.length; index++) {
  28855. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  28856. }
  28857. }
  28858. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  28859. };
  28860. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  28861. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  28862. };
  28863. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  28864. var changed = false;
  28865. var cache = this._valueCache[uniformName];
  28866. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  28867. changed = true;
  28868. cache = new BABYLON.Matrix();
  28869. }
  28870. var tm = cache.m;
  28871. var om = matrix.m;
  28872. for (var index = 0; index < 16; index++) {
  28873. if (tm[index] !== om[index]) {
  28874. tm[index] = om[index];
  28875. changed = true;
  28876. }
  28877. }
  28878. this._valueCache[uniformName] = cache;
  28879. return changed;
  28880. };
  28881. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  28882. var cache = this._valueCache[uniformName];
  28883. if (!cache) {
  28884. cache = [x, y];
  28885. this._valueCache[uniformName] = cache;
  28886. return true;
  28887. }
  28888. var changed = false;
  28889. if (cache[0] !== x) {
  28890. cache[0] = x;
  28891. changed = true;
  28892. }
  28893. if (cache[1] !== y) {
  28894. cache[1] = y;
  28895. changed = true;
  28896. }
  28897. return changed;
  28898. };
  28899. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  28900. var cache = this._valueCache[uniformName];
  28901. if (!cache) {
  28902. cache = [x, y, z];
  28903. this._valueCache[uniformName] = cache;
  28904. return true;
  28905. }
  28906. var changed = false;
  28907. if (cache[0] !== x) {
  28908. cache[0] = x;
  28909. changed = true;
  28910. }
  28911. if (cache[1] !== y) {
  28912. cache[1] = y;
  28913. changed = true;
  28914. }
  28915. if (cache[2] !== z) {
  28916. cache[2] = z;
  28917. changed = true;
  28918. }
  28919. return changed;
  28920. };
  28921. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  28922. var cache = this._valueCache[uniformName];
  28923. if (!cache) {
  28924. cache = [x, y, z, w];
  28925. this._valueCache[uniformName] = cache;
  28926. return true;
  28927. }
  28928. var changed = false;
  28929. if (cache[0] !== x) {
  28930. cache[0] = x;
  28931. changed = true;
  28932. }
  28933. if (cache[1] !== y) {
  28934. cache[1] = y;
  28935. changed = true;
  28936. }
  28937. if (cache[2] !== z) {
  28938. cache[2] = z;
  28939. changed = true;
  28940. }
  28941. if (cache[3] !== w) {
  28942. cache[3] = w;
  28943. changed = true;
  28944. }
  28945. return changed;
  28946. };
  28947. Effect.prototype.setIntArray = function (uniformName, array) {
  28948. this._valueCache[uniformName] = null;
  28949. this._engine.setIntArray(this.getUniform(uniformName), array);
  28950. return this;
  28951. };
  28952. Effect.prototype.setIntArray2 = function (uniformName, array) {
  28953. this._valueCache[uniformName] = null;
  28954. this._engine.setIntArray2(this.getUniform(uniformName), array);
  28955. return this;
  28956. };
  28957. Effect.prototype.setIntArray3 = function (uniformName, array) {
  28958. this._valueCache[uniformName] = null;
  28959. this._engine.setIntArray3(this.getUniform(uniformName), array);
  28960. return this;
  28961. };
  28962. Effect.prototype.setIntArray4 = function (uniformName, array) {
  28963. this._valueCache[uniformName] = null;
  28964. this._engine.setIntArray4(this.getUniform(uniformName), array);
  28965. return this;
  28966. };
  28967. Effect.prototype.setFloatArray = function (uniformName, array) {
  28968. this._valueCache[uniformName] = null;
  28969. this._engine.setFloatArray(this.getUniform(uniformName), array);
  28970. return this;
  28971. };
  28972. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  28973. this._valueCache[uniformName] = null;
  28974. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  28975. return this;
  28976. };
  28977. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  28978. this._valueCache[uniformName] = null;
  28979. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  28980. return this;
  28981. };
  28982. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  28983. this._valueCache[uniformName] = null;
  28984. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  28985. return this;
  28986. };
  28987. Effect.prototype.setArray = function (uniformName, array) {
  28988. this._valueCache[uniformName] = null;
  28989. this._engine.setArray(this.getUniform(uniformName), array);
  28990. return this;
  28991. };
  28992. Effect.prototype.setArray2 = function (uniformName, array) {
  28993. this._valueCache[uniformName] = null;
  28994. this._engine.setArray2(this.getUniform(uniformName), array);
  28995. return this;
  28996. };
  28997. Effect.prototype.setArray3 = function (uniformName, array) {
  28998. this._valueCache[uniformName] = null;
  28999. this._engine.setArray3(this.getUniform(uniformName), array);
  29000. return this;
  29001. };
  29002. Effect.prototype.setArray4 = function (uniformName, array) {
  29003. this._valueCache[uniformName] = null;
  29004. this._engine.setArray4(this.getUniform(uniformName), array);
  29005. return this;
  29006. };
  29007. Effect.prototype.setMatrices = function (uniformName, matrices) {
  29008. this._valueCache[uniformName] = null;
  29009. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  29010. return this;
  29011. };
  29012. Effect.prototype.setMatrix = function (uniformName, matrix) {
  29013. if (this._cacheMatrix(uniformName, matrix)) {
  29014. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  29015. }
  29016. return this;
  29017. };
  29018. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  29019. this._valueCache[uniformName] = null;
  29020. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  29021. return this;
  29022. };
  29023. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  29024. this._valueCache[uniformName] = null;
  29025. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  29026. return this;
  29027. };
  29028. Effect.prototype.setFloat = function (uniformName, value) {
  29029. var cache = this._valueCache[uniformName];
  29030. if (cache !== undefined && cache === value)
  29031. return this;
  29032. this._valueCache[uniformName] = value;
  29033. this._engine.setFloat(this.getUniform(uniformName), value);
  29034. return this;
  29035. };
  29036. Effect.prototype.setBool = function (uniformName, bool) {
  29037. var cache = this._valueCache[uniformName];
  29038. if (cache !== undefined && cache === bool)
  29039. return this;
  29040. this._valueCache[uniformName] = bool;
  29041. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  29042. return this;
  29043. };
  29044. Effect.prototype.setVector2 = function (uniformName, vector2) {
  29045. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  29046. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  29047. }
  29048. return this;
  29049. };
  29050. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  29051. if (this._cacheFloat2(uniformName, x, y)) {
  29052. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  29053. }
  29054. return this;
  29055. };
  29056. Effect.prototype.setVector3 = function (uniformName, vector3) {
  29057. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  29058. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  29059. }
  29060. return this;
  29061. };
  29062. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  29063. if (this._cacheFloat3(uniformName, x, y, z)) {
  29064. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  29065. }
  29066. return this;
  29067. };
  29068. Effect.prototype.setVector4 = function (uniformName, vector4) {
  29069. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  29070. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  29071. }
  29072. return this;
  29073. };
  29074. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  29075. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  29076. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  29077. }
  29078. return this;
  29079. };
  29080. Effect.prototype.setColor3 = function (uniformName, color3) {
  29081. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  29082. this._engine.setColor3(this.getUniform(uniformName), color3);
  29083. }
  29084. return this;
  29085. };
  29086. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  29087. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  29088. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  29089. }
  29090. return this;
  29091. };
  29092. Effect.prototype._recombineShader = function (node) {
  29093. if (node.define) {
  29094. if (node.condition) {
  29095. var defineIndex = this.defines.indexOf("#define " + node.define);
  29096. if (defineIndex === -1) {
  29097. return null;
  29098. }
  29099. var nextComma = this.defines.indexOf("\n", defineIndex);
  29100. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  29101. var condition = defineValue + node.condition;
  29102. if (!eval(condition)) {
  29103. return null;
  29104. }
  29105. }
  29106. else if (node.ndef) {
  29107. if (this.defines.indexOf("#define " + node.define) !== -1) {
  29108. return null;
  29109. }
  29110. }
  29111. else if (this.defines.indexOf("#define " + node.define) === -1) {
  29112. return null;
  29113. }
  29114. }
  29115. var result = "";
  29116. for (var index = 0; index < node.children.length; index++) {
  29117. var line = node.children[index];
  29118. if (line.children) {
  29119. var combined = this._recombineShader(line);
  29120. if (combined !== null) {
  29121. result += combined + "\r\n";
  29122. }
  29123. continue;
  29124. }
  29125. if (line.length > 0) {
  29126. result += line + "\r\n";
  29127. }
  29128. }
  29129. return result;
  29130. };
  29131. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  29132. var root = {
  29133. children: []
  29134. };
  29135. var currentNode = root;
  29136. var lines = shaderString.split("\n");
  29137. for (var index = 0; index < lines.length; index++) {
  29138. var line = lines[index].trim();
  29139. // #ifdef
  29140. var pos = line.indexOf("#ifdef ");
  29141. if (pos !== -1) {
  29142. var define = line.substr(pos + 7);
  29143. var newNode = {
  29144. condition: null,
  29145. ndef: false,
  29146. define: define,
  29147. children: [],
  29148. parent: currentNode
  29149. };
  29150. currentNode.children.push(newNode);
  29151. currentNode = newNode;
  29152. continue;
  29153. }
  29154. // #ifndef
  29155. var pos = line.indexOf("#ifndef ");
  29156. if (pos !== -1) {
  29157. var define = line.substr(pos + 8);
  29158. newNode = {
  29159. condition: null,
  29160. define: define,
  29161. ndef: true,
  29162. children: [],
  29163. parent: currentNode
  29164. };
  29165. currentNode.children.push(newNode);
  29166. currentNode = newNode;
  29167. continue;
  29168. }
  29169. // #if
  29170. var pos = line.indexOf("#if ");
  29171. if (pos !== -1) {
  29172. var define = line.substr(pos + 4).trim();
  29173. var conditionPos = define.indexOf(" ");
  29174. newNode = {
  29175. condition: define.substr(conditionPos + 1),
  29176. define: define.substr(0, conditionPos),
  29177. ndef: false,
  29178. children: [],
  29179. parent: currentNode
  29180. };
  29181. currentNode.children.push(newNode);
  29182. currentNode = newNode;
  29183. continue;
  29184. }
  29185. // #endif
  29186. pos = line.indexOf("#endif");
  29187. if (pos !== -1) {
  29188. currentNode = currentNode.parent;
  29189. continue;
  29190. }
  29191. currentNode.children.push(line);
  29192. }
  29193. // Recombine
  29194. return this._recombineShader(root);
  29195. };
  29196. return Effect;
  29197. }());
  29198. Effect._uniqueIdSeed = 0;
  29199. // Statics
  29200. Effect.ShadersStore = {};
  29201. Effect.IncludesShadersStore = {};
  29202. BABYLON.Effect = Effect;
  29203. })(BABYLON || (BABYLON = {}));
  29204. //# sourceMappingURL=babylon.effect.js.map
  29205. var BABYLON;
  29206. (function (BABYLON) {
  29207. var MaterialHelper = (function () {
  29208. function MaterialHelper() {
  29209. }
  29210. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  29211. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29212. var lightIndex = 0;
  29213. var needNormals = false;
  29214. var needRebuild = false;
  29215. var needShadows = false;
  29216. var lightmapMode = false;
  29217. for (var index = 0; index < scene.lights.length; index++) {
  29218. var light = scene.lights[index];
  29219. if (!light.isEnabled()) {
  29220. continue;
  29221. }
  29222. // Excluded check
  29223. if (light._excludedMeshesIds.length > 0) {
  29224. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  29225. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  29226. if (excludedMesh) {
  29227. light.excludedMeshes.push(excludedMesh);
  29228. }
  29229. }
  29230. light._excludedMeshesIds = [];
  29231. }
  29232. // Included check
  29233. if (light._includedOnlyMeshesIds.length > 0) {
  29234. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  29235. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  29236. if (includedOnlyMesh) {
  29237. light.includedOnlyMeshes.push(includedOnlyMesh);
  29238. }
  29239. }
  29240. light._includedOnlyMeshesIds = [];
  29241. }
  29242. if (!light.canAffectMesh(mesh)) {
  29243. continue;
  29244. }
  29245. needNormals = true;
  29246. if (defines["LIGHT" + lightIndex] === undefined) {
  29247. needRebuild = true;
  29248. }
  29249. defines["LIGHT" + lightIndex] = true;
  29250. var type;
  29251. if (light instanceof BABYLON.SpotLight) {
  29252. type = "SPOTLIGHT" + lightIndex;
  29253. }
  29254. else if (light instanceof BABYLON.HemisphericLight) {
  29255. type = "HEMILIGHT" + lightIndex;
  29256. }
  29257. else if (light instanceof BABYLON.PointLight) {
  29258. type = "POINTLIGHT" + lightIndex;
  29259. }
  29260. else {
  29261. type = "DIRLIGHT" + lightIndex;
  29262. }
  29263. if (defines[type] === undefined) {
  29264. needRebuild = true;
  29265. }
  29266. defines[type] = true;
  29267. // Specular
  29268. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  29269. defines["SPECULARTERM"] = true;
  29270. }
  29271. // Shadows
  29272. if (scene.shadowsEnabled) {
  29273. var shadowGenerator = light.getShadowGenerator();
  29274. if (mesh && mesh.receiveShadows && shadowGenerator) {
  29275. if (defines["SHADOW" + lightIndex] === undefined) {
  29276. needRebuild = true;
  29277. }
  29278. defines["SHADOW" + lightIndex] = true;
  29279. defines["SHADOWS"] = true;
  29280. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  29281. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  29282. needRebuild = true;
  29283. }
  29284. defines["SHADOWVSM" + lightIndex] = true;
  29285. }
  29286. else if (shadowGenerator.usePoissonSampling) {
  29287. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  29288. needRebuild = true;
  29289. }
  29290. defines["SHADOWPCF" + lightIndex] = true;
  29291. }
  29292. else if (shadowGenerator.useExponentialShadowMap) {
  29293. if (defines["SHADOWESM" + lightIndex] === undefined) {
  29294. needRebuild = true;
  29295. }
  29296. defines["SHADOWESM" + lightIndex] = true;
  29297. }
  29298. needShadows = true;
  29299. }
  29300. }
  29301. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  29302. lightmapMode = true;
  29303. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  29304. needRebuild = true;
  29305. }
  29306. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  29307. needRebuild = true;
  29308. }
  29309. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  29310. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  29311. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  29312. }
  29313. }
  29314. lightIndex++;
  29315. if (lightIndex === maxSimultaneousLights)
  29316. break;
  29317. }
  29318. var caps = scene.getEngine().getCaps();
  29319. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  29320. if (defines["SHADOWFULLFLOAT"] === undefined) {
  29321. needRebuild = true;
  29322. }
  29323. defines["SHADOWFULLFLOAT"] = true;
  29324. }
  29325. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  29326. needRebuild = true;
  29327. }
  29328. if (lightmapMode) {
  29329. defines["LIGHTMAPEXCLUDED"] = true;
  29330. }
  29331. if (needRebuild) {
  29332. defines.rebuild();
  29333. }
  29334. return needNormals;
  29335. };
  29336. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  29337. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29338. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29339. if (!defines["LIGHT" + lightIndex]) {
  29340. break;
  29341. }
  29342. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  29343. samplersList.push("shadowSampler" + lightIndex);
  29344. }
  29345. };
  29346. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  29347. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29348. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29349. if (!defines["LIGHT" + lightIndex]) {
  29350. break;
  29351. }
  29352. if (lightIndex > 0) {
  29353. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  29354. }
  29355. if (defines["SHADOW" + lightIndex]) {
  29356. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  29357. }
  29358. if (defines["SHADOWPCF" + lightIndex]) {
  29359. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  29360. }
  29361. if (defines["SHADOWVSM" + lightIndex]) {
  29362. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  29363. }
  29364. if (defines["SHADOWESM" + lightIndex]) {
  29365. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  29366. }
  29367. }
  29368. };
  29369. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  29370. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  29371. fallbacks.addCPUSkinningFallback(0, mesh);
  29372. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29373. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29374. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  29375. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  29376. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  29377. }
  29378. }
  29379. };
  29380. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  29381. if (defines["INSTANCES"]) {
  29382. attribs.push("world0");
  29383. attribs.push("world1");
  29384. attribs.push("world2");
  29385. attribs.push("world3");
  29386. }
  29387. };
  29388. // Bindings
  29389. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  29390. var shadowGenerator = light.getShadowGenerator();
  29391. if (mesh.receiveShadows && shadowGenerator) {
  29392. if (!light.needCube()) {
  29393. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  29394. }
  29395. else {
  29396. if (!depthValuesAlreadySet) {
  29397. depthValuesAlreadySet = true;
  29398. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  29399. }
  29400. }
  29401. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  29402. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  29403. }
  29404. return depthValuesAlreadySet;
  29405. };
  29406. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  29407. if (light instanceof BABYLON.PointLight) {
  29408. // Point Light
  29409. light.transferToEffect(effect, "vLightData" + lightIndex);
  29410. }
  29411. else if (light instanceof BABYLON.DirectionalLight) {
  29412. // Directional Light
  29413. light.transferToEffect(effect, "vLightData" + lightIndex);
  29414. }
  29415. else if (light instanceof BABYLON.SpotLight) {
  29416. // Spot Light
  29417. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  29418. }
  29419. else if (light instanceof BABYLON.HemisphericLight) {
  29420. // Hemispheric Light
  29421. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  29422. }
  29423. };
  29424. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  29425. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29426. var lightIndex = 0;
  29427. var depthValuesAlreadySet = false;
  29428. for (var index = 0; index < scene.lights.length; index++) {
  29429. var light = scene.lights[index];
  29430. if (!light.isEnabled()) {
  29431. continue;
  29432. }
  29433. if (!light.canAffectMesh(mesh)) {
  29434. continue;
  29435. }
  29436. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  29437. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  29438. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  29439. if (defines["SPECULARTERM"]) {
  29440. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  29441. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  29442. }
  29443. // Shadows
  29444. if (scene.shadowsEnabled) {
  29445. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  29446. }
  29447. lightIndex++;
  29448. if (lightIndex === maxSimultaneousLights)
  29449. break;
  29450. }
  29451. };
  29452. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  29453. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  29454. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  29455. effect.setColor3("vFogColor", scene.fogColor);
  29456. }
  29457. };
  29458. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  29459. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29460. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  29461. if (matrices) {
  29462. effect.setMatrices("mBones", matrices);
  29463. }
  29464. }
  29465. };
  29466. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  29467. if (defines["LOGARITHMICDEPTH"]) {
  29468. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  29469. }
  29470. };
  29471. MaterialHelper.BindClipPlane = function (effect, scene) {
  29472. if (scene.clipPlane) {
  29473. var clipPlane = scene.clipPlane;
  29474. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  29475. }
  29476. };
  29477. return MaterialHelper;
  29478. }());
  29479. BABYLON.MaterialHelper = MaterialHelper;
  29480. })(BABYLON || (BABYLON = {}));
  29481. //# sourceMappingURL=babylon.materialHelper.js.map
  29482. var BABYLON;
  29483. (function (BABYLON) {
  29484. var FresnelParameters = (function () {
  29485. function FresnelParameters() {
  29486. this.isEnabled = true;
  29487. this.leftColor = BABYLON.Color3.White();
  29488. this.rightColor = BABYLON.Color3.Black();
  29489. this.bias = 0;
  29490. this.power = 1;
  29491. }
  29492. FresnelParameters.prototype.clone = function () {
  29493. var newFresnelParameters = new FresnelParameters();
  29494. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  29495. return newFresnelParameters;
  29496. };
  29497. FresnelParameters.prototype.serialize = function () {
  29498. var serializationObject = {};
  29499. serializationObject.isEnabled = this.isEnabled;
  29500. serializationObject.leftColor = this.leftColor;
  29501. serializationObject.rightColor = this.rightColor;
  29502. serializationObject.bias = this.bias;
  29503. serializationObject.power = this.power;
  29504. return serializationObject;
  29505. };
  29506. FresnelParameters.Parse = function (parsedFresnelParameters) {
  29507. var fresnelParameters = new FresnelParameters();
  29508. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  29509. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  29510. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  29511. fresnelParameters.bias = parsedFresnelParameters.bias;
  29512. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  29513. return fresnelParameters;
  29514. };
  29515. return FresnelParameters;
  29516. }());
  29517. BABYLON.FresnelParameters = FresnelParameters;
  29518. })(BABYLON || (BABYLON = {}));
  29519. //# sourceMappingURL=babylon.fresnelParameters.js.map
  29520. var BABYLON;
  29521. (function (BABYLON) {
  29522. var MaterialDefines = (function () {
  29523. function MaterialDefines() {
  29524. }
  29525. MaterialDefines.prototype.rebuild = function () {
  29526. if (this._keys) {
  29527. delete this._keys;
  29528. }
  29529. this._keys = Object.keys(this);
  29530. };
  29531. MaterialDefines.prototype.isEqual = function (other) {
  29532. if (this._keys.length !== other._keys.length) {
  29533. return false;
  29534. }
  29535. for (var index = 0; index < this._keys.length; index++) {
  29536. var prop = this._keys[index];
  29537. if (this[prop] !== other[prop]) {
  29538. return false;
  29539. }
  29540. }
  29541. return true;
  29542. };
  29543. MaterialDefines.prototype.cloneTo = function (other) {
  29544. if (this._keys.length !== other._keys.length) {
  29545. other._keys = this._keys.slice(0);
  29546. }
  29547. for (var index = 0; index < this._keys.length; index++) {
  29548. var prop = this._keys[index];
  29549. other[prop] = this[prop];
  29550. }
  29551. };
  29552. MaterialDefines.prototype.reset = function () {
  29553. for (var index = 0; index < this._keys.length; index++) {
  29554. var prop = this._keys[index];
  29555. if (typeof (this[prop]) === "number") {
  29556. this[prop] = 0;
  29557. }
  29558. else {
  29559. this[prop] = false;
  29560. }
  29561. }
  29562. };
  29563. MaterialDefines.prototype.toString = function () {
  29564. var result = "";
  29565. for (var index = 0; index < this._keys.length; index++) {
  29566. var prop = this._keys[index];
  29567. if (typeof (this[prop]) === "number") {
  29568. result += "#define " + prop + " " + this[prop] + "\n";
  29569. }
  29570. else if (this[prop]) {
  29571. result += "#define " + prop + "\n";
  29572. }
  29573. }
  29574. return result;
  29575. };
  29576. return MaterialDefines;
  29577. }());
  29578. BABYLON.MaterialDefines = MaterialDefines;
  29579. var Material = (function () {
  29580. function Material(name, scene, doNotAdd) {
  29581. this.checkReadyOnEveryCall = false;
  29582. this.checkReadyOnlyOnce = false;
  29583. this.state = "";
  29584. this.alpha = 1.0;
  29585. this.backFaceCulling = true;
  29586. this.doNotSerialize = false;
  29587. /**
  29588. * An event triggered when the material is disposed.
  29589. * @type {BABYLON.Observable}
  29590. */
  29591. this.onDisposeObservable = new BABYLON.Observable();
  29592. /**
  29593. * An event triggered when the material is bound.
  29594. * @type {BABYLON.Observable}
  29595. */
  29596. this.onBindObservable = new BABYLON.Observable();
  29597. /**
  29598. * An event triggered when the material is unbound.
  29599. * @type {BABYLON.Observable}
  29600. */
  29601. this.onUnBindObservable = new BABYLON.Observable();
  29602. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29603. this.disableDepthWrite = false;
  29604. this.fogEnabled = true;
  29605. this.pointSize = 1.0;
  29606. this.zOffset = 0;
  29607. this._wasPreviouslyReady = false;
  29608. this._fillMode = Material.TriangleFillMode;
  29609. this.name = name;
  29610. this.id = name;
  29611. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29612. if (this._scene.useRightHandedSystem) {
  29613. this.sideOrientation = Material.ClockWiseSideOrientation;
  29614. }
  29615. else {
  29616. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29617. }
  29618. if (!doNotAdd) {
  29619. this._scene.materials.push(this);
  29620. }
  29621. }
  29622. Object.defineProperty(Material, "TriangleFillMode", {
  29623. get: function () {
  29624. return Material._TriangleFillMode;
  29625. },
  29626. enumerable: true,
  29627. configurable: true
  29628. });
  29629. Object.defineProperty(Material, "WireFrameFillMode", {
  29630. get: function () {
  29631. return Material._WireFrameFillMode;
  29632. },
  29633. enumerable: true,
  29634. configurable: true
  29635. });
  29636. Object.defineProperty(Material, "PointFillMode", {
  29637. get: function () {
  29638. return Material._PointFillMode;
  29639. },
  29640. enumerable: true,
  29641. configurable: true
  29642. });
  29643. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29644. get: function () {
  29645. return Material._ClockWiseSideOrientation;
  29646. },
  29647. enumerable: true,
  29648. configurable: true
  29649. });
  29650. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29651. get: function () {
  29652. return Material._CounterClockWiseSideOrientation;
  29653. },
  29654. enumerable: true,
  29655. configurable: true
  29656. });
  29657. Object.defineProperty(Material.prototype, "onDispose", {
  29658. set: function (callback) {
  29659. if (this._onDisposeObserver) {
  29660. this.onDisposeObservable.remove(this._onDisposeObserver);
  29661. }
  29662. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29663. },
  29664. enumerable: true,
  29665. configurable: true
  29666. });
  29667. Object.defineProperty(Material.prototype, "onBind", {
  29668. set: function (callback) {
  29669. if (this._onBindObserver) {
  29670. this.onBindObservable.remove(this._onBindObserver);
  29671. }
  29672. this._onBindObserver = this.onBindObservable.add(callback);
  29673. },
  29674. enumerable: true,
  29675. configurable: true
  29676. });
  29677. Object.defineProperty(Material.prototype, "wireframe", {
  29678. get: function () {
  29679. return this._fillMode === Material.WireFrameFillMode;
  29680. },
  29681. set: function (value) {
  29682. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29683. },
  29684. enumerable: true,
  29685. configurable: true
  29686. });
  29687. Object.defineProperty(Material.prototype, "pointsCloud", {
  29688. get: function () {
  29689. return this._fillMode === Material.PointFillMode;
  29690. },
  29691. set: function (value) {
  29692. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29693. },
  29694. enumerable: true,
  29695. configurable: true
  29696. });
  29697. Object.defineProperty(Material.prototype, "fillMode", {
  29698. get: function () {
  29699. return this._fillMode;
  29700. },
  29701. set: function (value) {
  29702. this._fillMode = value;
  29703. },
  29704. enumerable: true,
  29705. configurable: true
  29706. });
  29707. /**
  29708. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29709. * subclasses should override adding information pertainent to themselves
  29710. */
  29711. Material.prototype.toString = function (fullDetails) {
  29712. var ret = "Name: " + this.name;
  29713. if (fullDetails) {
  29714. }
  29715. return ret;
  29716. };
  29717. Material.prototype.getClassName = function () {
  29718. return "Material";
  29719. };
  29720. Object.defineProperty(Material.prototype, "isFrozen", {
  29721. get: function () {
  29722. return this.checkReadyOnlyOnce;
  29723. },
  29724. enumerable: true,
  29725. configurable: true
  29726. });
  29727. Material.prototype.freeze = function () {
  29728. this.checkReadyOnlyOnce = true;
  29729. };
  29730. Material.prototype.unfreeze = function () {
  29731. this.checkReadyOnlyOnce = false;
  29732. };
  29733. Material.prototype.isReady = function (mesh, useInstances) {
  29734. return true;
  29735. };
  29736. Material.prototype.getEffect = function () {
  29737. return this._effect;
  29738. };
  29739. Material.prototype.getScene = function () {
  29740. return this._scene;
  29741. };
  29742. Material.prototype.needAlphaBlending = function () {
  29743. return (this.alpha < 1.0);
  29744. };
  29745. Material.prototype.needAlphaTesting = function () {
  29746. return false;
  29747. };
  29748. Material.prototype.getAlphaTestTexture = function () {
  29749. return null;
  29750. };
  29751. Material.prototype.markDirty = function () {
  29752. this._wasPreviouslyReady = false;
  29753. };
  29754. Material.prototype._preBind = function () {
  29755. var engine = this._scene.getEngine();
  29756. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  29757. engine.enableEffect(this._effect);
  29758. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29759. };
  29760. Material.prototype.bind = function (world, mesh) {
  29761. this._scene._cachedMaterial = this;
  29762. this.onBindObservable.notifyObservers(mesh);
  29763. if (this.disableDepthWrite) {
  29764. var engine = this._scene.getEngine();
  29765. this._cachedDepthWriteState = engine.getDepthWrite();
  29766. engine.setDepthWrite(false);
  29767. }
  29768. };
  29769. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29770. };
  29771. Material.prototype.unbind = function () {
  29772. this.onUnBindObservable.notifyObservers(this);
  29773. if (this.disableDepthWrite) {
  29774. var engine = this._scene.getEngine();
  29775. engine.setDepthWrite(this._cachedDepthWriteState);
  29776. }
  29777. };
  29778. Material.prototype.clone = function (name) {
  29779. return null;
  29780. };
  29781. Material.prototype.getBindedMeshes = function () {
  29782. var result = new Array();
  29783. for (var index = 0; index < this._scene.meshes.length; index++) {
  29784. var mesh = this._scene.meshes[index];
  29785. if (mesh.material === this) {
  29786. result.push(mesh);
  29787. }
  29788. }
  29789. return result;
  29790. };
  29791. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29792. // Animations
  29793. this.getScene().stopAnimation(this);
  29794. // Remove from scene
  29795. var index = this._scene.materials.indexOf(this);
  29796. if (index >= 0) {
  29797. this._scene.materials.splice(index, 1);
  29798. }
  29799. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29800. if (forceDisposeEffect && this._effect) {
  29801. this._scene.getEngine()._releaseEffect(this._effect);
  29802. this._effect = null;
  29803. }
  29804. // Remove from meshes
  29805. for (index = 0; index < this._scene.meshes.length; index++) {
  29806. var mesh = this._scene.meshes[index];
  29807. if (mesh.material === this) {
  29808. mesh.material = null;
  29809. }
  29810. }
  29811. // Callback
  29812. this.onDisposeObservable.notifyObservers(this);
  29813. this.onDisposeObservable.clear();
  29814. this.onBindObservable.clear();
  29815. this.onUnBindObservable.clear();
  29816. };
  29817. Material.prototype.serialize = function () {
  29818. return BABYLON.SerializationHelper.Serialize(this);
  29819. };
  29820. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29821. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29822. multiMaterial.id = parsedMultiMaterial.id;
  29823. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29824. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29825. var subMatId = parsedMultiMaterial.materials[matIndex];
  29826. if (subMatId) {
  29827. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29828. }
  29829. else {
  29830. multiMaterial.subMaterials.push(null);
  29831. }
  29832. }
  29833. return multiMaterial;
  29834. };
  29835. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29836. if (!parsedMaterial.customType) {
  29837. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29838. }
  29839. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29840. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29841. ;
  29842. };
  29843. return Material;
  29844. }());
  29845. Material._TriangleFillMode = 0;
  29846. Material._WireFrameFillMode = 1;
  29847. Material._PointFillMode = 2;
  29848. Material._ClockWiseSideOrientation = 0;
  29849. Material._CounterClockWiseSideOrientation = 1;
  29850. __decorate([
  29851. BABYLON.serialize()
  29852. ], Material.prototype, "id", void 0);
  29853. __decorate([
  29854. BABYLON.serialize()
  29855. ], Material.prototype, "name", void 0);
  29856. __decorate([
  29857. BABYLON.serialize()
  29858. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29859. __decorate([
  29860. BABYLON.serialize()
  29861. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29862. __decorate([
  29863. BABYLON.serialize()
  29864. ], Material.prototype, "state", void 0);
  29865. __decorate([
  29866. BABYLON.serialize()
  29867. ], Material.prototype, "alpha", void 0);
  29868. __decorate([
  29869. BABYLON.serialize()
  29870. ], Material.prototype, "backFaceCulling", void 0);
  29871. __decorate([
  29872. BABYLON.serialize()
  29873. ], Material.prototype, "sideOrientation", void 0);
  29874. __decorate([
  29875. BABYLON.serialize()
  29876. ], Material.prototype, "alphaMode", void 0);
  29877. __decorate([
  29878. BABYLON.serialize()
  29879. ], Material.prototype, "disableDepthWrite", void 0);
  29880. __decorate([
  29881. BABYLON.serialize()
  29882. ], Material.prototype, "fogEnabled", void 0);
  29883. __decorate([
  29884. BABYLON.serialize()
  29885. ], Material.prototype, "pointSize", void 0);
  29886. __decorate([
  29887. BABYLON.serialize()
  29888. ], Material.prototype, "zOffset", void 0);
  29889. __decorate([
  29890. BABYLON.serialize()
  29891. ], Material.prototype, "wireframe", null);
  29892. __decorate([
  29893. BABYLON.serialize()
  29894. ], Material.prototype, "pointsCloud", null);
  29895. __decorate([
  29896. BABYLON.serialize()
  29897. ], Material.prototype, "fillMode", null);
  29898. BABYLON.Material = Material;
  29899. })(BABYLON || (BABYLON = {}));
  29900. //# sourceMappingURL=babylon.material.js.map
  29901. var BABYLON;
  29902. (function (BABYLON) {
  29903. var StandardMaterialDefines = (function (_super) {
  29904. __extends(StandardMaterialDefines, _super);
  29905. function StandardMaterialDefines() {
  29906. var _this = _super.call(this) || this;
  29907. _this.DIFFUSE = false;
  29908. _this.AMBIENT = false;
  29909. _this.OPACITY = false;
  29910. _this.OPACITYRGB = false;
  29911. _this.REFLECTION = false;
  29912. _this.EMISSIVE = false;
  29913. _this.SPECULAR = false;
  29914. _this.BUMP = false;
  29915. _this.PARALLAX = false;
  29916. _this.PARALLAXOCCLUSION = false;
  29917. _this.SPECULAROVERALPHA = false;
  29918. _this.CLIPPLANE = false;
  29919. _this.ALPHATEST = false;
  29920. _this.ALPHAFROMDIFFUSE = false;
  29921. _this.POINTSIZE = false;
  29922. _this.FOG = false;
  29923. _this.SPECULARTERM = false;
  29924. _this.DIFFUSEFRESNEL = false;
  29925. _this.OPACITYFRESNEL = false;
  29926. _this.REFLECTIONFRESNEL = false;
  29927. _this.REFRACTIONFRESNEL = false;
  29928. _this.EMISSIVEFRESNEL = false;
  29929. _this.FRESNEL = false;
  29930. _this.NORMAL = false;
  29931. _this.UV1 = false;
  29932. _this.UV2 = false;
  29933. _this.VERTEXCOLOR = false;
  29934. _this.VERTEXALPHA = false;
  29935. _this.NUM_BONE_INFLUENCERS = 0;
  29936. _this.BonesPerMesh = 0;
  29937. _this.INSTANCES = false;
  29938. _this.GLOSSINESS = false;
  29939. _this.ROUGHNESS = false;
  29940. _this.EMISSIVEASILLUMINATION = false;
  29941. _this.LINKEMISSIVEWITHDIFFUSE = false;
  29942. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  29943. _this.LIGHTMAP = false;
  29944. _this.USELIGHTMAPASSHADOWMAP = false;
  29945. _this.REFLECTIONMAP_3D = false;
  29946. _this.REFLECTIONMAP_SPHERICAL = false;
  29947. _this.REFLECTIONMAP_PLANAR = false;
  29948. _this.REFLECTIONMAP_CUBIC = false;
  29949. _this.REFLECTIONMAP_PROJECTION = false;
  29950. _this.REFLECTIONMAP_SKYBOX = false;
  29951. _this.REFLECTIONMAP_EXPLICIT = false;
  29952. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29953. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29954. _this.INVERTCUBICMAP = false;
  29955. _this.LOGARITHMICDEPTH = false;
  29956. _this.REFRACTION = false;
  29957. _this.REFRACTIONMAP_3D = false;
  29958. _this.REFLECTIONOVERALPHA = false;
  29959. _this.INVERTNORMALMAPX = false;
  29960. _this.INVERTNORMALMAPY = false;
  29961. _this.SHADOWFULLFLOAT = false;
  29962. _this.CAMERACOLORGRADING = false;
  29963. _this.CAMERACOLORCURVES = false;
  29964. _this.rebuild();
  29965. return _this;
  29966. }
  29967. return StandardMaterialDefines;
  29968. }(BABYLON.MaterialDefines));
  29969. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  29970. var StandardMaterial = (function (_super) {
  29971. __extends(StandardMaterial, _super);
  29972. function StandardMaterial(name, scene) {
  29973. var _this = _super.call(this, name, scene) || this;
  29974. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  29975. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  29976. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  29977. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  29978. _this.specularPower = 64;
  29979. _this.useAlphaFromDiffuseTexture = false;
  29980. _this.useEmissiveAsIllumination = false;
  29981. _this.linkEmissiveWithDiffuse = false;
  29982. _this.useReflectionFresnelFromSpecular = false;
  29983. _this.useSpecularOverAlpha = false;
  29984. _this.useReflectionOverAlpha = false;
  29985. _this.disableLighting = false;
  29986. _this.useParallax = false;
  29987. _this.useParallaxOcclusion = false;
  29988. _this.parallaxScaleBias = 0.05;
  29989. _this.roughness = 0;
  29990. _this.indexOfRefraction = 0.98;
  29991. _this.invertRefractionY = true;
  29992. _this.useLightmapAsShadowmap = false;
  29993. _this.useGlossinessFromSpecularMapAlpha = false;
  29994. _this.maxSimultaneousLights = 4;
  29995. /**
  29996. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29997. */
  29998. _this.invertNormalMapX = false;
  29999. /**
  30000. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30001. */
  30002. _this.invertNormalMapY = false;
  30003. /**
  30004. * Color Grading 2D Lookup Texture.
  30005. * This allows special effects like sepia, black and white to sixties rendering style.
  30006. */
  30007. _this.cameraColorGradingTexture = null;
  30008. /**
  30009. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30010. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30011. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  30012. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30013. */
  30014. _this.cameraColorCurves = null;
  30015. _this._renderTargets = new BABYLON.SmartArray(16);
  30016. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30017. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30018. _this._defines = new StandardMaterialDefines();
  30019. _this._cachedDefines = new StandardMaterialDefines();
  30020. _this._cachedDefines.BonesPerMesh = -1;
  30021. _this.getRenderTargetTextures = function () {
  30022. _this._renderTargets.reset();
  30023. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  30024. _this._renderTargets.push(_this.reflectionTexture);
  30025. }
  30026. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  30027. _this._renderTargets.push(_this.refractionTexture);
  30028. }
  30029. return _this._renderTargets;
  30030. };
  30031. return _this;
  30032. }
  30033. StandardMaterial.prototype.getClassName = function () {
  30034. return "StandardMaterial";
  30035. };
  30036. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30037. get: function () {
  30038. return this._useLogarithmicDepth;
  30039. },
  30040. set: function (value) {
  30041. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30042. },
  30043. enumerable: true,
  30044. configurable: true
  30045. });
  30046. StandardMaterial.prototype.needAlphaBlending = function () {
  30047. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  30048. };
  30049. StandardMaterial.prototype.needAlphaTesting = function () {
  30050. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  30051. };
  30052. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30053. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  30054. };
  30055. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30056. return this.diffuseTexture;
  30057. };
  30058. // Methods
  30059. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  30060. if (!mesh) {
  30061. return true;
  30062. }
  30063. if (this._defines.INSTANCES !== useInstances) {
  30064. return false;
  30065. }
  30066. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  30067. return true;
  30068. }
  30069. return false;
  30070. };
  30071. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  30072. if (this.isFrozen) {
  30073. if (this._wasPreviouslyReady) {
  30074. return true;
  30075. }
  30076. }
  30077. var scene = this.getScene();
  30078. var engine = scene.getEngine();
  30079. var needUVs = false;
  30080. var needNormals = false;
  30081. this._defines.reset();
  30082. // Lights
  30083. if (scene.lightsEnabled && !this.disableLighting) {
  30084. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  30085. }
  30086. if (!this.checkReadyOnEveryCall) {
  30087. if (this._renderId === scene.getRenderId()) {
  30088. if (this._checkCache(scene, mesh, useInstances)) {
  30089. return true;
  30090. }
  30091. }
  30092. }
  30093. // Textures
  30094. if (scene.texturesEnabled) {
  30095. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30096. if (!this.diffuseTexture.isReady()) {
  30097. return false;
  30098. }
  30099. else {
  30100. needUVs = true;
  30101. this._defines.DIFFUSE = true;
  30102. }
  30103. }
  30104. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30105. if (!this.ambientTexture.isReady()) {
  30106. return false;
  30107. }
  30108. else {
  30109. needUVs = true;
  30110. this._defines.AMBIENT = true;
  30111. }
  30112. }
  30113. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30114. if (!this.opacityTexture.isReady()) {
  30115. return false;
  30116. }
  30117. else {
  30118. needUVs = true;
  30119. this._defines.OPACITY = true;
  30120. if (this.opacityTexture.getAlphaFromRGB) {
  30121. this._defines.OPACITYRGB = true;
  30122. }
  30123. }
  30124. }
  30125. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30126. if (!this.reflectionTexture.isReady()) {
  30127. return false;
  30128. }
  30129. else {
  30130. needNormals = true;
  30131. this._defines.REFLECTION = true;
  30132. if (this.roughness > 0) {
  30133. this._defines.ROUGHNESS = true;
  30134. }
  30135. if (this.useReflectionOverAlpha) {
  30136. this._defines.REFLECTIONOVERALPHA = true;
  30137. }
  30138. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  30139. this._defines.INVERTCUBICMAP = true;
  30140. }
  30141. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  30142. switch (this.reflectionTexture.coordinatesMode) {
  30143. case BABYLON.Texture.CUBIC_MODE:
  30144. case BABYLON.Texture.INVCUBIC_MODE:
  30145. this._defines.REFLECTIONMAP_CUBIC = true;
  30146. break;
  30147. case BABYLON.Texture.EXPLICIT_MODE:
  30148. this._defines.REFLECTIONMAP_EXPLICIT = true;
  30149. break;
  30150. case BABYLON.Texture.PLANAR_MODE:
  30151. this._defines.REFLECTIONMAP_PLANAR = true;
  30152. break;
  30153. case BABYLON.Texture.PROJECTION_MODE:
  30154. this._defines.REFLECTIONMAP_PROJECTION = true;
  30155. break;
  30156. case BABYLON.Texture.SKYBOX_MODE:
  30157. this._defines.REFLECTIONMAP_SKYBOX = true;
  30158. break;
  30159. case BABYLON.Texture.SPHERICAL_MODE:
  30160. this._defines.REFLECTIONMAP_SPHERICAL = true;
  30161. break;
  30162. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30163. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  30164. break;
  30165. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30166. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  30167. break;
  30168. }
  30169. }
  30170. }
  30171. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30172. if (!this.emissiveTexture.isReady()) {
  30173. return false;
  30174. }
  30175. else {
  30176. needUVs = true;
  30177. this._defines.EMISSIVE = true;
  30178. }
  30179. }
  30180. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30181. if (!this.lightmapTexture.isReady()) {
  30182. return false;
  30183. }
  30184. else {
  30185. needUVs = true;
  30186. this._defines.LIGHTMAP = true;
  30187. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  30188. }
  30189. }
  30190. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30191. if (!this.specularTexture.isReady()) {
  30192. return false;
  30193. }
  30194. else {
  30195. needUVs = true;
  30196. this._defines.SPECULAR = true;
  30197. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  30198. }
  30199. }
  30200. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30201. if (!this.bumpTexture.isReady()) {
  30202. return false;
  30203. }
  30204. else {
  30205. needUVs = true;
  30206. this._defines.BUMP = true;
  30207. if (this.useParallax) {
  30208. this._defines.PARALLAX = true;
  30209. if (this.useParallaxOcclusion) {
  30210. this._defines.PARALLAXOCCLUSION = true;
  30211. }
  30212. }
  30213. if (this.invertNormalMapX) {
  30214. this._defines.INVERTNORMALMAPX = true;
  30215. }
  30216. if (this.invertNormalMapY) {
  30217. this._defines.INVERTNORMALMAPY = true;
  30218. }
  30219. if (scene._mirroredCameraPosition) {
  30220. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  30221. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  30222. }
  30223. }
  30224. }
  30225. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30226. if (!this.refractionTexture.isReady()) {
  30227. return false;
  30228. }
  30229. else {
  30230. needUVs = true;
  30231. this._defines.REFRACTION = true;
  30232. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  30233. }
  30234. }
  30235. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  30236. if (!this.cameraColorGradingTexture.isReady()) {
  30237. return false;
  30238. }
  30239. else {
  30240. this._defines.CAMERACOLORGRADING = true;
  30241. }
  30242. }
  30243. }
  30244. // Effect
  30245. if (scene.clipPlane) {
  30246. this._defines.CLIPPLANE = true;
  30247. }
  30248. if (engine.getAlphaTesting()) {
  30249. this._defines.ALPHATEST = true;
  30250. }
  30251. if (this._shouldUseAlphaFromDiffuseTexture()) {
  30252. this._defines.ALPHAFROMDIFFUSE = true;
  30253. }
  30254. if (this.useEmissiveAsIllumination) {
  30255. this._defines.EMISSIVEASILLUMINATION = true;
  30256. }
  30257. if (this.linkEmissiveWithDiffuse) {
  30258. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  30259. }
  30260. if (this.useLogarithmicDepth) {
  30261. this._defines.LOGARITHMICDEPTH = true;
  30262. }
  30263. if (this.cameraColorCurves) {
  30264. this._defines.CAMERACOLORCURVES = true;
  30265. }
  30266. // Point size
  30267. if (this.pointsCloud || scene.forcePointsCloud) {
  30268. this._defines.POINTSIZE = true;
  30269. }
  30270. // Fog
  30271. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  30272. this._defines.FOG = true;
  30273. }
  30274. if (StandardMaterial.FresnelEnabled) {
  30275. // Fresnel
  30276. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  30277. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  30278. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  30279. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  30280. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30281. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30282. this._defines.DIFFUSEFRESNEL = true;
  30283. }
  30284. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30285. this._defines.OPACITYFRESNEL = true;
  30286. }
  30287. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30288. this._defines.REFLECTIONFRESNEL = true;
  30289. if (this.useReflectionFresnelFromSpecular) {
  30290. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  30291. }
  30292. }
  30293. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30294. this._defines.REFRACTIONFRESNEL = true;
  30295. }
  30296. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30297. this._defines.EMISSIVEFRESNEL = true;
  30298. }
  30299. needNormals = true;
  30300. this._defines.FRESNEL = true;
  30301. }
  30302. }
  30303. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  30304. this._defines.SPECULAROVERALPHA = true;
  30305. }
  30306. // Attribs
  30307. if (mesh) {
  30308. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30309. this._defines.NORMAL = true;
  30310. }
  30311. if (needUVs) {
  30312. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30313. this._defines.UV1 = true;
  30314. }
  30315. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30316. this._defines.UV2 = true;
  30317. }
  30318. }
  30319. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30320. this._defines.VERTEXCOLOR = true;
  30321. if (mesh.hasVertexAlpha) {
  30322. this._defines.VERTEXALPHA = true;
  30323. }
  30324. }
  30325. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30326. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  30327. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  30328. }
  30329. // Instances
  30330. if (useInstances) {
  30331. this._defines.INSTANCES = true;
  30332. }
  30333. }
  30334. // Get correct effect
  30335. if (!this._defines.isEqual(this._cachedDefines)) {
  30336. this._defines.cloneTo(this._cachedDefines);
  30337. scene.resetCachedMaterial();
  30338. // Fallbacks
  30339. var fallbacks = new BABYLON.EffectFallbacks();
  30340. if (this._defines.REFLECTION) {
  30341. fallbacks.addFallback(0, "REFLECTION");
  30342. }
  30343. if (this._defines.SPECULAR) {
  30344. fallbacks.addFallback(0, "SPECULAR");
  30345. }
  30346. if (this._defines.BUMP) {
  30347. fallbacks.addFallback(0, "BUMP");
  30348. }
  30349. if (this._defines.PARALLAX) {
  30350. fallbacks.addFallback(1, "PARALLAX");
  30351. }
  30352. if (this._defines.PARALLAXOCCLUSION) {
  30353. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30354. }
  30355. if (this._defines.SPECULAROVERALPHA) {
  30356. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30357. }
  30358. if (this._defines.FOG) {
  30359. fallbacks.addFallback(1, "FOG");
  30360. }
  30361. if (this._defines.POINTSIZE) {
  30362. fallbacks.addFallback(0, "POINTSIZE");
  30363. }
  30364. if (this._defines.LOGARITHMICDEPTH) {
  30365. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30366. }
  30367. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  30368. if (this._defines.SPECULARTERM) {
  30369. fallbacks.addFallback(0, "SPECULARTERM");
  30370. }
  30371. if (this._defines.DIFFUSEFRESNEL) {
  30372. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  30373. }
  30374. if (this._defines.OPACITYFRESNEL) {
  30375. fallbacks.addFallback(2, "OPACITYFRESNEL");
  30376. }
  30377. if (this._defines.REFLECTIONFRESNEL) {
  30378. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  30379. }
  30380. if (this._defines.EMISSIVEFRESNEL) {
  30381. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  30382. }
  30383. if (this._defines.FRESNEL) {
  30384. fallbacks.addFallback(4, "FRESNEL");
  30385. }
  30386. //Attributes
  30387. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30388. if (this._defines.NORMAL) {
  30389. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30390. }
  30391. if (this._defines.UV1) {
  30392. attribs.push(BABYLON.VertexBuffer.UVKind);
  30393. }
  30394. if (this._defines.UV2) {
  30395. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30396. }
  30397. if (this._defines.VERTEXCOLOR) {
  30398. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30399. }
  30400. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  30401. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  30402. var shaderName = "default";
  30403. var join = this._defines.toString();
  30404. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  30405. "vFogInfos", "vFogColor", "pointSize",
  30406. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30407. "mBones",
  30408. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30409. "depthValues",
  30410. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  30411. "logarithmicDepthConstant"
  30412. ];
  30413. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30414. if (this._defines.CAMERACOLORCURVES) {
  30415. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  30416. }
  30417. if (this._defines.CAMERACOLORGRADING) {
  30418. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  30419. }
  30420. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  30421. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  30422. }
  30423. if (!this._effect.isReady()) {
  30424. return false;
  30425. }
  30426. this._renderId = scene.getRenderId();
  30427. this._wasPreviouslyReady = true;
  30428. if (mesh) {
  30429. if (!mesh._materialDefines) {
  30430. mesh._materialDefines = new StandardMaterialDefines();
  30431. }
  30432. this._defines.cloneTo(mesh._materialDefines);
  30433. }
  30434. return true;
  30435. };
  30436. StandardMaterial.prototype.unbind = function () {
  30437. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  30438. this._effect.setTexture("reflection2DSampler", null);
  30439. }
  30440. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  30441. this._effect.setTexture("refraction2DSampler", null);
  30442. }
  30443. _super.prototype.unbind.call(this);
  30444. };
  30445. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30446. this._effect.setMatrix("world", world);
  30447. };
  30448. StandardMaterial.prototype.bind = function (world, mesh) {
  30449. var scene = this.getScene();
  30450. // Matrices
  30451. this.bindOnlyWorldMatrix(world);
  30452. // Bones
  30453. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  30454. if (scene.getCachedMaterial() !== this) {
  30455. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30456. if (StandardMaterial.FresnelEnabled) {
  30457. // Fresnel
  30458. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30459. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  30460. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  30461. }
  30462. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30463. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  30464. }
  30465. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30466. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  30467. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  30468. }
  30469. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30470. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  30471. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  30472. }
  30473. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30474. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  30475. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  30476. }
  30477. }
  30478. // Textures
  30479. if (scene.texturesEnabled) {
  30480. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30481. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  30482. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  30483. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  30484. }
  30485. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30486. this._effect.setTexture("ambientSampler", this.ambientTexture);
  30487. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  30488. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  30489. }
  30490. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30491. this._effect.setTexture("opacitySampler", this.opacityTexture);
  30492. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  30493. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  30494. }
  30495. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30496. if (this.reflectionTexture.isCube) {
  30497. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  30498. }
  30499. else {
  30500. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  30501. }
  30502. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  30503. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  30504. }
  30505. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30506. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  30507. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  30508. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  30509. }
  30510. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30511. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  30512. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  30513. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  30514. }
  30515. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30516. this._effect.setTexture("specularSampler", this.specularTexture);
  30517. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  30518. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  30519. }
  30520. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30521. this._effect.setTexture("bumpSampler", this.bumpTexture);
  30522. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  30523. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  30524. }
  30525. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30526. var depth = 1.0;
  30527. if (this.refractionTexture.isCube) {
  30528. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  30529. }
  30530. else {
  30531. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  30532. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  30533. if (this.refractionTexture.depth) {
  30534. depth = this.refractionTexture.depth;
  30535. }
  30536. }
  30537. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  30538. }
  30539. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  30540. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  30541. }
  30542. }
  30543. // Clip plane
  30544. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  30545. // Point size
  30546. if (this.pointsCloud) {
  30547. this._effect.setFloat("pointSize", this.pointSize);
  30548. }
  30549. // Colors
  30550. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  30551. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  30552. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30553. if (this._defines.SPECULARTERM) {
  30554. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  30555. }
  30556. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  30557. }
  30558. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  30559. // Diffuse
  30560. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  30561. // Lights
  30562. if (scene.lightsEnabled && !this.disableLighting) {
  30563. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  30564. }
  30565. // View
  30566. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  30567. this._effect.setMatrix("view", scene.getViewMatrix());
  30568. }
  30569. // Fog
  30570. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  30571. // Log. depth
  30572. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  30573. // Color Curves
  30574. if (this.cameraColorCurves) {
  30575. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  30576. }
  30577. }
  30578. _super.prototype.bind.call(this, world, mesh);
  30579. };
  30580. StandardMaterial.prototype.getAnimatables = function () {
  30581. var results = [];
  30582. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  30583. results.push(this.diffuseTexture);
  30584. }
  30585. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  30586. results.push(this.ambientTexture);
  30587. }
  30588. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  30589. results.push(this.opacityTexture);
  30590. }
  30591. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  30592. results.push(this.reflectionTexture);
  30593. }
  30594. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  30595. results.push(this.emissiveTexture);
  30596. }
  30597. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  30598. results.push(this.specularTexture);
  30599. }
  30600. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  30601. results.push(this.bumpTexture);
  30602. }
  30603. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  30604. results.push(this.lightmapTexture);
  30605. }
  30606. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  30607. results.push(this.refractionTexture);
  30608. }
  30609. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  30610. results.push(this.cameraColorGradingTexture);
  30611. }
  30612. return results;
  30613. };
  30614. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30615. if (forceDisposeTextures) {
  30616. if (this.diffuseTexture) {
  30617. this.diffuseTexture.dispose();
  30618. }
  30619. if (this.ambientTexture) {
  30620. this.ambientTexture.dispose();
  30621. }
  30622. if (this.opacityTexture) {
  30623. this.opacityTexture.dispose();
  30624. }
  30625. if (this.reflectionTexture) {
  30626. this.reflectionTexture.dispose();
  30627. }
  30628. if (this.emissiveTexture) {
  30629. this.emissiveTexture.dispose();
  30630. }
  30631. if (this.specularTexture) {
  30632. this.specularTexture.dispose();
  30633. }
  30634. if (this.bumpTexture) {
  30635. this.bumpTexture.dispose();
  30636. }
  30637. if (this.lightmapTexture) {
  30638. this.lightmapTexture.dispose();
  30639. }
  30640. if (this.refractionTexture) {
  30641. this.refractionTexture.dispose();
  30642. }
  30643. if (this.cameraColorGradingTexture) {
  30644. this.cameraColorGradingTexture.dispose();
  30645. }
  30646. }
  30647. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30648. };
  30649. StandardMaterial.prototype.clone = function (name) {
  30650. var _this = this;
  30651. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  30652. };
  30653. StandardMaterial.prototype.serialize = function () {
  30654. return BABYLON.SerializationHelper.Serialize(this);
  30655. };
  30656. // Statics
  30657. StandardMaterial.Parse = function (source, scene, rootUrl) {
  30658. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  30659. };
  30660. return StandardMaterial;
  30661. }(BABYLON.Material));
  30662. // Flags used to enable or disable a type of texture for all Standard Materials
  30663. StandardMaterial.DiffuseTextureEnabled = true;
  30664. StandardMaterial.AmbientTextureEnabled = true;
  30665. StandardMaterial.OpacityTextureEnabled = true;
  30666. StandardMaterial.ReflectionTextureEnabled = true;
  30667. StandardMaterial.EmissiveTextureEnabled = true;
  30668. StandardMaterial.SpecularTextureEnabled = true;
  30669. StandardMaterial.BumpTextureEnabled = true;
  30670. StandardMaterial.FresnelEnabled = true;
  30671. StandardMaterial.LightmapTextureEnabled = true;
  30672. StandardMaterial.RefractionTextureEnabled = true;
  30673. StandardMaterial.ColorGradingTextureEnabled = true;
  30674. __decorate([
  30675. BABYLON.serializeAsTexture()
  30676. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  30677. __decorate([
  30678. BABYLON.serializeAsTexture()
  30679. ], StandardMaterial.prototype, "ambientTexture", void 0);
  30680. __decorate([
  30681. BABYLON.serializeAsTexture()
  30682. ], StandardMaterial.prototype, "opacityTexture", void 0);
  30683. __decorate([
  30684. BABYLON.serializeAsTexture()
  30685. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  30686. __decorate([
  30687. BABYLON.serializeAsTexture()
  30688. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  30689. __decorate([
  30690. BABYLON.serializeAsTexture()
  30691. ], StandardMaterial.prototype, "specularTexture", void 0);
  30692. __decorate([
  30693. BABYLON.serializeAsTexture()
  30694. ], StandardMaterial.prototype, "bumpTexture", void 0);
  30695. __decorate([
  30696. BABYLON.serializeAsTexture()
  30697. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  30698. __decorate([
  30699. BABYLON.serializeAsTexture()
  30700. ], StandardMaterial.prototype, "refractionTexture", void 0);
  30701. __decorate([
  30702. BABYLON.serializeAsColor3("ambient")
  30703. ], StandardMaterial.prototype, "ambientColor", void 0);
  30704. __decorate([
  30705. BABYLON.serializeAsColor3("diffuse")
  30706. ], StandardMaterial.prototype, "diffuseColor", void 0);
  30707. __decorate([
  30708. BABYLON.serializeAsColor3("specular")
  30709. ], StandardMaterial.prototype, "specularColor", void 0);
  30710. __decorate([
  30711. BABYLON.serializeAsColor3("emissive")
  30712. ], StandardMaterial.prototype, "emissiveColor", void 0);
  30713. __decorate([
  30714. BABYLON.serialize()
  30715. ], StandardMaterial.prototype, "specularPower", void 0);
  30716. __decorate([
  30717. BABYLON.serialize()
  30718. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  30719. __decorate([
  30720. BABYLON.serialize()
  30721. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  30722. __decorate([
  30723. BABYLON.serialize()
  30724. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  30725. __decorate([
  30726. BABYLON.serialize()
  30727. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  30728. __decorate([
  30729. BABYLON.serialize()
  30730. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  30731. __decorate([
  30732. BABYLON.serialize()
  30733. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  30734. __decorate([
  30735. BABYLON.serialize()
  30736. ], StandardMaterial.prototype, "disableLighting", void 0);
  30737. __decorate([
  30738. BABYLON.serialize()
  30739. ], StandardMaterial.prototype, "useParallax", void 0);
  30740. __decorate([
  30741. BABYLON.serialize()
  30742. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  30743. __decorate([
  30744. BABYLON.serialize()
  30745. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  30746. __decorate([
  30747. BABYLON.serialize()
  30748. ], StandardMaterial.prototype, "roughness", void 0);
  30749. __decorate([
  30750. BABYLON.serialize()
  30751. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  30752. __decorate([
  30753. BABYLON.serialize()
  30754. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  30755. __decorate([
  30756. BABYLON.serialize()
  30757. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  30758. __decorate([
  30759. BABYLON.serializeAsFresnelParameters()
  30760. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  30761. __decorate([
  30762. BABYLON.serializeAsFresnelParameters()
  30763. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  30764. __decorate([
  30765. BABYLON.serializeAsFresnelParameters()
  30766. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  30767. __decorate([
  30768. BABYLON.serializeAsFresnelParameters()
  30769. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  30770. __decorate([
  30771. BABYLON.serializeAsFresnelParameters()
  30772. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  30773. __decorate([
  30774. BABYLON.serialize()
  30775. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  30776. __decorate([
  30777. BABYLON.serialize()
  30778. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  30779. __decorate([
  30780. BABYLON.serialize()
  30781. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  30782. __decorate([
  30783. BABYLON.serialize()
  30784. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  30785. __decorate([
  30786. BABYLON.serializeAsTexture()
  30787. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  30788. __decorate([
  30789. BABYLON.serializeAsColorCurves()
  30790. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  30791. __decorate([
  30792. BABYLON.serialize()
  30793. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  30794. BABYLON.StandardMaterial = StandardMaterial;
  30795. })(BABYLON || (BABYLON = {}));
  30796. //# sourceMappingURL=babylon.standardMaterial.js.map
  30797. var BABYLON;
  30798. (function (BABYLON) {
  30799. var MultiMaterial = (function (_super) {
  30800. __extends(MultiMaterial, _super);
  30801. function MultiMaterial(name, scene) {
  30802. var _this = _super.call(this, name, scene, true) || this;
  30803. _this.subMaterials = new Array();
  30804. scene.multiMaterials.push(_this);
  30805. return _this;
  30806. }
  30807. // Properties
  30808. MultiMaterial.prototype.getSubMaterial = function (index) {
  30809. if (index < 0 || index >= this.subMaterials.length) {
  30810. return this.getScene().defaultMaterial;
  30811. }
  30812. return this.subMaterials[index];
  30813. };
  30814. // Methods
  30815. MultiMaterial.prototype.getClassName = function () {
  30816. return "MultiMaterial";
  30817. };
  30818. MultiMaterial.prototype.isReady = function (mesh) {
  30819. for (var index = 0; index < this.subMaterials.length; index++) {
  30820. var subMaterial = this.subMaterials[index];
  30821. if (subMaterial) {
  30822. if (!this.subMaterials[index].isReady(mesh)) {
  30823. return false;
  30824. }
  30825. }
  30826. }
  30827. return true;
  30828. };
  30829. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  30830. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  30831. for (var index = 0; index < this.subMaterials.length; index++) {
  30832. var subMaterial = null;
  30833. if (cloneChildren) {
  30834. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  30835. }
  30836. else {
  30837. subMaterial = this.subMaterials[index];
  30838. }
  30839. newMultiMaterial.subMaterials.push(subMaterial);
  30840. }
  30841. return newMultiMaterial;
  30842. };
  30843. MultiMaterial.prototype.serialize = function () {
  30844. var serializationObject = {};
  30845. serializationObject.name = this.name;
  30846. serializationObject.id = this.id;
  30847. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30848. serializationObject.materials = [];
  30849. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  30850. var subMat = this.subMaterials[matIndex];
  30851. if (subMat) {
  30852. serializationObject.materials.push(subMat.id);
  30853. }
  30854. else {
  30855. serializationObject.materials.push(null);
  30856. }
  30857. }
  30858. return serializationObject;
  30859. };
  30860. return MultiMaterial;
  30861. }(BABYLON.Material));
  30862. BABYLON.MultiMaterial = MultiMaterial;
  30863. })(BABYLON || (BABYLON = {}));
  30864. //# sourceMappingURL=babylon.multiMaterial.js.map
  30865. var BABYLON;
  30866. (function (BABYLON) {
  30867. var SceneLoader = (function () {
  30868. function SceneLoader() {
  30869. }
  30870. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  30871. get: function () {
  30872. return 0;
  30873. },
  30874. enumerable: true,
  30875. configurable: true
  30876. });
  30877. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  30878. get: function () {
  30879. return 1;
  30880. },
  30881. enumerable: true,
  30882. configurable: true
  30883. });
  30884. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  30885. get: function () {
  30886. return 2;
  30887. },
  30888. enumerable: true,
  30889. configurable: true
  30890. });
  30891. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  30892. get: function () {
  30893. return 3;
  30894. },
  30895. enumerable: true,
  30896. configurable: true
  30897. });
  30898. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  30899. get: function () {
  30900. return SceneLoader._ForceFullSceneLoadingForIncremental;
  30901. },
  30902. set: function (value) {
  30903. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  30904. },
  30905. enumerable: true,
  30906. configurable: true
  30907. });
  30908. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  30909. get: function () {
  30910. return SceneLoader._ShowLoadingScreen;
  30911. },
  30912. set: function (value) {
  30913. SceneLoader._ShowLoadingScreen = value;
  30914. },
  30915. enumerable: true,
  30916. configurable: true
  30917. });
  30918. Object.defineProperty(SceneLoader, "loggingLevel", {
  30919. get: function () {
  30920. return SceneLoader._loggingLevel;
  30921. },
  30922. set: function (value) {
  30923. SceneLoader._loggingLevel = value;
  30924. },
  30925. enumerable: true,
  30926. configurable: true
  30927. });
  30928. SceneLoader._getDefaultPlugin = function () {
  30929. return SceneLoader._registeredPlugins[".babylon"];
  30930. };
  30931. SceneLoader._getPluginForExtension = function (extension) {
  30932. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  30933. if (registeredPlugin) {
  30934. return registeredPlugin;
  30935. }
  30936. return SceneLoader._getDefaultPlugin();
  30937. };
  30938. SceneLoader._getPluginForFilename = function (sceneFilename) {
  30939. if (sceneFilename.name) {
  30940. sceneFilename = sceneFilename.name;
  30941. }
  30942. var dotPosition = sceneFilename.lastIndexOf(".");
  30943. var queryStringPosition = sceneFilename.indexOf("?");
  30944. if (queryStringPosition === -1) {
  30945. queryStringPosition = sceneFilename.length;
  30946. }
  30947. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  30948. return SceneLoader._getPluginForExtension(extension);
  30949. };
  30950. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  30951. SceneLoader._getDirectLoad = function (sceneFilename) {
  30952. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  30953. return sceneFilename.substr(5);
  30954. }
  30955. return null;
  30956. };
  30957. // Public functions
  30958. SceneLoader.GetPluginForExtension = function (extension) {
  30959. return SceneLoader._getPluginForExtension(extension).plugin;
  30960. };
  30961. SceneLoader.RegisterPlugin = function (plugin) {
  30962. if (typeof plugin.extensions === "string") {
  30963. var extension = plugin.extensions;
  30964. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  30965. plugin: plugin,
  30966. isBinary: false
  30967. };
  30968. }
  30969. else {
  30970. var extensions = plugin.extensions;
  30971. Object.keys(extensions).forEach(function (extension) {
  30972. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  30973. plugin: plugin,
  30974. isBinary: extensions[extension].isBinary
  30975. };
  30976. });
  30977. }
  30978. };
  30979. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  30980. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30981. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30982. return;
  30983. }
  30984. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30985. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30986. return;
  30987. }
  30988. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  30989. var loadingToken = {};
  30990. scene._addPendingData(loadingToken);
  30991. var manifestChecked = function (success) {
  30992. scene.database = database;
  30993. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  30994. var plugin = registeredPlugin.plugin;
  30995. var useArrayBuffer = registeredPlugin.isBinary;
  30996. var importMeshFromData = function (data) {
  30997. var meshes = [];
  30998. var particleSystems = [];
  30999. var skeletons = [];
  31000. try {
  31001. if (plugin.importMesh) {
  31002. var syncedPlugin = plugin;
  31003. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  31004. if (onerror) {
  31005. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  31006. }
  31007. scene._removePendingData(loadingToken);
  31008. return;
  31009. }
  31010. if (onsuccess) {
  31011. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  31012. onsuccess(meshes, particleSystems, skeletons);
  31013. scene._removePendingData(loadingToken);
  31014. }
  31015. }
  31016. else {
  31017. var asyncedPlugin = plugin;
  31018. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  31019. if (onsuccess) {
  31020. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  31021. onsuccess(meshes, particleSystems, skeletons);
  31022. scene._removePendingData(loadingToken);
  31023. }
  31024. }, function () {
  31025. if (onerror) {
  31026. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  31027. }
  31028. scene._removePendingData(loadingToken);
  31029. });
  31030. }
  31031. }
  31032. catch (e) {
  31033. if (onerror) {
  31034. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  31035. }
  31036. scene._removePendingData(loadingToken);
  31037. }
  31038. };
  31039. if (directLoad) {
  31040. importMeshFromData(directLoad);
  31041. return;
  31042. }
  31043. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  31044. importMeshFromData(data);
  31045. }, progressCallBack, database, useArrayBuffer, function () {
  31046. if (onerror) {
  31047. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  31048. }
  31049. });
  31050. };
  31051. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  31052. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  31053. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  31054. }
  31055. else {
  31056. // If the scene is a data stream or offline support is not enabled, it's a direct load
  31057. manifestChecked(true);
  31058. }
  31059. };
  31060. /**
  31061. * Load a scene
  31062. * @param rootUrl a string that defines the root url for scene and resources
  31063. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  31064. * @param engine is the instance of BABYLON.Engine to use to create the scene
  31065. */
  31066. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  31067. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  31068. };
  31069. /**
  31070. * Append a scene
  31071. * @param rootUrl a string that defines the root url for scene and resources
  31072. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  31073. * @param scene is the instance of BABYLON.Scene to append to
  31074. */
  31075. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  31076. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  31077. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  31078. return;
  31079. }
  31080. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  31081. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  31082. var plugin = registeredPlugin.plugin;
  31083. var useArrayBuffer = registeredPlugin.isBinary;
  31084. var database;
  31085. var loadingToken = {};
  31086. scene._addPendingData(loadingToken);
  31087. if (SceneLoader.ShowLoadingScreen) {
  31088. scene.getEngine().displayLoadingUI();
  31089. }
  31090. var loadSceneFromData = function (data) {
  31091. scene.database = database;
  31092. if (plugin.load) {
  31093. var syncedPlugin = plugin;
  31094. if (!syncedPlugin.load(scene, data, rootUrl)) {
  31095. if (onerror) {
  31096. onerror(scene);
  31097. }
  31098. scene._removePendingData(loadingToken);
  31099. scene.getEngine().hideLoadingUI();
  31100. return;
  31101. }
  31102. if (onsuccess) {
  31103. onsuccess(scene);
  31104. }
  31105. scene._removePendingData(loadingToken);
  31106. }
  31107. else {
  31108. var asyncedPlugin = plugin;
  31109. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  31110. if (onsuccess) {
  31111. onsuccess(scene);
  31112. }
  31113. scene._removePendingData(loadingToken);
  31114. }, function () {
  31115. if (onerror) {
  31116. onerror(scene);
  31117. }
  31118. scene._removePendingData(loadingToken);
  31119. scene.getEngine().hideLoadingUI();
  31120. });
  31121. }
  31122. if (SceneLoader.ShowLoadingScreen) {
  31123. scene.executeWhenReady(function () {
  31124. scene.getEngine().hideLoadingUI();
  31125. });
  31126. }
  31127. };
  31128. var manifestChecked = function (success) {
  31129. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  31130. };
  31131. if (directLoad) {
  31132. loadSceneFromData(directLoad);
  31133. return;
  31134. }
  31135. if (rootUrl.indexOf("file:") === -1) {
  31136. if (scene.getEngine().enableOfflineSupport) {
  31137. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  31138. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  31139. }
  31140. else {
  31141. manifestChecked(true);
  31142. }
  31143. }
  31144. else {
  31145. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  31146. }
  31147. };
  31148. return SceneLoader;
  31149. }());
  31150. // Flags
  31151. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  31152. SceneLoader._ShowLoadingScreen = true;
  31153. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  31154. // Members
  31155. SceneLoader._registeredPlugins = {};
  31156. BABYLON.SceneLoader = SceneLoader;
  31157. ;
  31158. })(BABYLON || (BABYLON = {}));
  31159. //# sourceMappingURL=babylon.sceneLoader.js.map
  31160. var BABYLON;
  31161. (function (BABYLON) {
  31162. var Internals;
  31163. (function (Internals) {
  31164. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  31165. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  31166. var parsedMaterial = parsedData.materials[index];
  31167. if (parsedMaterial.id === id) {
  31168. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  31169. }
  31170. }
  31171. return null;
  31172. };
  31173. var isDescendantOf = function (mesh, names, hierarchyIds) {
  31174. names = (names instanceof Array) ? names : [names];
  31175. for (var i in names) {
  31176. if (mesh.name === names[i]) {
  31177. hierarchyIds.push(mesh.id);
  31178. return true;
  31179. }
  31180. }
  31181. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  31182. hierarchyIds.push(mesh.id);
  31183. return true;
  31184. }
  31185. return false;
  31186. };
  31187. var logOperation = function (operation, producer) {
  31188. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  31189. };
  31190. BABYLON.SceneLoader.RegisterPlugin({
  31191. extensions: ".babylon",
  31192. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  31193. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  31194. // when SceneLoader.debugLogging = true (default), or exception encountered.
  31195. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  31196. // and avoid problems with multiple concurrent .babylon loads.
  31197. var log = "importMesh has failed JSON parse";
  31198. try {
  31199. var parsedData = JSON.parse(data);
  31200. log = "";
  31201. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  31202. var loadedSkeletonsIds = [];
  31203. var loadedMaterialsIds = [];
  31204. var hierarchyIds = [];
  31205. var index;
  31206. var cache;
  31207. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  31208. var parsedMesh = parsedData.meshes[index];
  31209. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  31210. if (meshesNames instanceof Array) {
  31211. // Remove found mesh name from list.
  31212. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  31213. }
  31214. //Geometry?
  31215. if (parsedMesh.geometryId) {
  31216. //does the file contain geometries?
  31217. if (parsedData.geometries) {
  31218. //find the correct geometry and add it to the scene
  31219. var found = false;
  31220. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  31221. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  31222. return;
  31223. }
  31224. else {
  31225. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  31226. if (parsedGeometryData.id === parsedMesh.geometryId) {
  31227. switch (geometryType) {
  31228. case "boxes":
  31229. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  31230. break;
  31231. case "spheres":
  31232. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  31233. break;
  31234. case "cylinders":
  31235. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  31236. break;
  31237. case "toruses":
  31238. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  31239. break;
  31240. case "grounds":
  31241. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  31242. break;
  31243. case "planes":
  31244. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  31245. break;
  31246. case "torusKnots":
  31247. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  31248. break;
  31249. case "vertexData":
  31250. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  31251. break;
  31252. }
  31253. found = true;
  31254. }
  31255. });
  31256. }
  31257. });
  31258. if (!found) {
  31259. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  31260. }
  31261. }
  31262. }
  31263. // Material ?
  31264. if (parsedMesh.materialId) {
  31265. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  31266. if (!materialFound && parsedData.multiMaterials) {
  31267. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  31268. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  31269. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  31270. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  31271. var subMatId = parsedMultiMaterial.materials[matIndex];
  31272. loadedMaterialsIds.push(subMatId);
  31273. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  31274. log += "\n\tMaterial " + mat.toString(fullDetails);
  31275. }
  31276. loadedMaterialsIds.push(parsedMultiMaterial.id);
  31277. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  31278. materialFound = true;
  31279. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  31280. break;
  31281. }
  31282. }
  31283. }
  31284. if (!materialFound) {
  31285. loadedMaterialsIds.push(parsedMesh.materialId);
  31286. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  31287. if (!mat) {
  31288. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  31289. }
  31290. else {
  31291. log += "\n\tMaterial " + mat.toString(fullDetails);
  31292. }
  31293. }
  31294. }
  31295. // Skeleton ?
  31296. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  31297. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  31298. if (!skeletonAlreadyLoaded) {
  31299. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  31300. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  31301. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  31302. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  31303. skeletons.push(skeleton);
  31304. loadedSkeletonsIds.push(parsedSkeleton.id);
  31305. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  31306. }
  31307. }
  31308. }
  31309. }
  31310. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  31311. meshes.push(mesh);
  31312. log += "\n\tMesh " + mesh.toString(fullDetails);
  31313. }
  31314. }
  31315. // Connecting parents
  31316. var currentMesh;
  31317. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31318. currentMesh = scene.meshes[index];
  31319. if (currentMesh._waitingParentId) {
  31320. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  31321. currentMesh._waitingParentId = undefined;
  31322. }
  31323. }
  31324. // freeze and compute world matrix application
  31325. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31326. currentMesh = scene.meshes[index];
  31327. if (currentMesh._waitingFreezeWorldMatrix) {
  31328. currentMesh.freezeWorldMatrix();
  31329. currentMesh._waitingFreezeWorldMatrix = undefined;
  31330. }
  31331. else {
  31332. currentMesh.computeWorldMatrix(true);
  31333. }
  31334. }
  31335. // Particles
  31336. if (parsedData.particleSystems) {
  31337. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  31338. var parsedParticleSystem = parsedData.particleSystems[index];
  31339. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  31340. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  31341. }
  31342. }
  31343. }
  31344. return true;
  31345. }
  31346. catch (err) {
  31347. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  31348. log = null;
  31349. throw err;
  31350. }
  31351. finally {
  31352. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  31353. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  31354. }
  31355. }
  31356. },
  31357. load: function (scene, data, rootUrl) {
  31358. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  31359. // when SceneLoader.debugLogging = true (default), or exception encountered.
  31360. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  31361. // and avoid problems with multiple concurrent .babylon loads.
  31362. var log = "importScene has failed JSON parse";
  31363. try {
  31364. var parsedData = JSON.parse(data);
  31365. log = "";
  31366. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  31367. // Scene
  31368. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  31369. scene.autoClear = parsedData.autoClear;
  31370. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  31371. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  31372. if (parsedData.gravity) {
  31373. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  31374. }
  31375. // Fog
  31376. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  31377. scene.fogMode = parsedData.fogMode;
  31378. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  31379. scene.fogStart = parsedData.fogStart;
  31380. scene.fogEnd = parsedData.fogEnd;
  31381. scene.fogDensity = parsedData.fogDensity;
  31382. log += "\tFog mode for scene: ";
  31383. switch (scene.fogMode) {
  31384. // getters not compiling, so using hardcoded
  31385. case 1:
  31386. log += "exp\n";
  31387. break;
  31388. case 2:
  31389. log += "exp2\n";
  31390. break;
  31391. case 3:
  31392. log += "linear\n";
  31393. break;
  31394. }
  31395. }
  31396. //Physics
  31397. if (parsedData.physicsEnabled) {
  31398. var physicsPlugin;
  31399. if (parsedData.physicsEngine === "cannon") {
  31400. physicsPlugin = new BABYLON.CannonJSPlugin();
  31401. }
  31402. else if (parsedData.physicsEngine === "oimo") {
  31403. physicsPlugin = new BABYLON.OimoJSPlugin();
  31404. }
  31405. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  31406. //else - default engine, which is currently oimo
  31407. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  31408. scene.enablePhysics(physicsGravity, physicsPlugin);
  31409. }
  31410. // Metadata
  31411. if (parsedData.metadata !== undefined) {
  31412. scene.metadata = parsedData.metadata;
  31413. }
  31414. //collisions, if defined. otherwise, default is true
  31415. if (parsedData.collisionsEnabled != undefined) {
  31416. scene.collisionsEnabled = parsedData.collisionsEnabled;
  31417. }
  31418. scene.workerCollisions = !!parsedData.workerCollisions;
  31419. var index;
  31420. var cache;
  31421. // Lights
  31422. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  31423. var parsedLight = parsedData.lights[index];
  31424. var light = BABYLON.Light.Parse(parsedLight, scene);
  31425. log += (index === 0 ? "\n\tLights:" : "");
  31426. log += "\n\t\t" + light.toString(fullDetails);
  31427. }
  31428. // Animations
  31429. if (parsedData.animations) {
  31430. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  31431. var parsedAnimation = parsedData.animations[index];
  31432. var animation = BABYLON.Animation.Parse(parsedAnimation);
  31433. scene.animations.push(animation);
  31434. log += (index === 0 ? "\n\tAnimations:" : "");
  31435. log += "\n\t\t" + animation.toString(fullDetails);
  31436. }
  31437. }
  31438. if (parsedData.autoAnimate) {
  31439. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  31440. }
  31441. // Materials
  31442. if (parsedData.materials) {
  31443. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  31444. var parsedMaterial = parsedData.materials[index];
  31445. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  31446. log += (index === 0 ? "\n\tMaterials:" : "");
  31447. log += "\n\t\t" + mat.toString(fullDetails);
  31448. }
  31449. }
  31450. if (parsedData.multiMaterials) {
  31451. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  31452. var parsedMultiMaterial = parsedData.multiMaterials[index];
  31453. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  31454. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  31455. log += "\n\t\t" + mmat.toString(fullDetails);
  31456. }
  31457. }
  31458. // Skeletons
  31459. if (parsedData.skeletons) {
  31460. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  31461. var parsedSkeleton = parsedData.skeletons[index];
  31462. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  31463. log += (index === 0 ? "\n\tSkeletons:" : "");
  31464. log += "\n\t\t" + skeleton.toString(fullDetails);
  31465. }
  31466. }
  31467. // Geometries
  31468. var geometries = parsedData.geometries;
  31469. if (geometries) {
  31470. // Boxes
  31471. var boxes = geometries.boxes;
  31472. if (boxes) {
  31473. for (index = 0, cache = boxes.length; index < cache; index++) {
  31474. var parsedBox = boxes[index];
  31475. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  31476. }
  31477. }
  31478. // Spheres
  31479. var spheres = geometries.spheres;
  31480. if (spheres) {
  31481. for (index = 0, cache = spheres.length; index < cache; index++) {
  31482. var parsedSphere = spheres[index];
  31483. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  31484. }
  31485. }
  31486. // Cylinders
  31487. var cylinders = geometries.cylinders;
  31488. if (cylinders) {
  31489. for (index = 0, cache = cylinders.length; index < cache; index++) {
  31490. var parsedCylinder = cylinders[index];
  31491. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  31492. }
  31493. }
  31494. // Toruses
  31495. var toruses = geometries.toruses;
  31496. if (toruses) {
  31497. for (index = 0, cache = toruses.length; index < cache; index++) {
  31498. var parsedTorus = toruses[index];
  31499. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  31500. }
  31501. }
  31502. // Grounds
  31503. var grounds = geometries.grounds;
  31504. if (grounds) {
  31505. for (index = 0, cache = grounds.length; index < cache; index++) {
  31506. var parsedGround = grounds[index];
  31507. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  31508. }
  31509. }
  31510. // Planes
  31511. var planes = geometries.planes;
  31512. if (planes) {
  31513. for (index = 0, cache = planes.length; index < cache; index++) {
  31514. var parsedPlane = planes[index];
  31515. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  31516. }
  31517. }
  31518. // TorusKnots
  31519. var torusKnots = geometries.torusKnots;
  31520. if (torusKnots) {
  31521. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  31522. var parsedTorusKnot = torusKnots[index];
  31523. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  31524. }
  31525. }
  31526. // VertexData
  31527. var vertexData = geometries.vertexData;
  31528. if (vertexData) {
  31529. for (index = 0, cache = vertexData.length; index < cache; index++) {
  31530. var parsedVertexData = vertexData[index];
  31531. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  31532. }
  31533. }
  31534. }
  31535. // Meshes
  31536. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  31537. var parsedMesh = parsedData.meshes[index];
  31538. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  31539. log += (index === 0 ? "\n\tMeshes:" : "");
  31540. log += "\n\t\t" + mesh.toString(fullDetails);
  31541. }
  31542. // Cameras
  31543. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  31544. var parsedCamera = parsedData.cameras[index];
  31545. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  31546. log += (index === 0 ? "\n\tCameras:" : "");
  31547. log += "\n\t\t" + camera.toString(fullDetails);
  31548. }
  31549. if (parsedData.activeCameraID) {
  31550. scene.setActiveCameraByID(parsedData.activeCameraID);
  31551. }
  31552. // Browsing all the graph to connect the dots
  31553. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  31554. var camera = scene.cameras[index];
  31555. if (camera._waitingParentId) {
  31556. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  31557. camera._waitingParentId = undefined;
  31558. }
  31559. }
  31560. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  31561. var light = scene.lights[index];
  31562. if (light._waitingParentId) {
  31563. light.parent = scene.getLastEntryByID(light._waitingParentId);
  31564. light._waitingParentId = undefined;
  31565. }
  31566. }
  31567. // Sounds
  31568. var loadedSounds = [];
  31569. var loadedSound;
  31570. if (BABYLON.AudioEngine && parsedData.sounds) {
  31571. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  31572. var parsedSound = parsedData.sounds[index];
  31573. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31574. if (!parsedSound.url)
  31575. parsedSound.url = parsedSound.name;
  31576. if (!loadedSounds[parsedSound.url]) {
  31577. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  31578. loadedSounds[parsedSound.url] = loadedSound;
  31579. }
  31580. else {
  31581. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  31582. }
  31583. }
  31584. else {
  31585. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  31586. }
  31587. }
  31588. }
  31589. loadedSounds = [];
  31590. // Connect parents & children and parse actions
  31591. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31592. var mesh = scene.meshes[index];
  31593. if (mesh._waitingParentId) {
  31594. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  31595. mesh._waitingParentId = undefined;
  31596. }
  31597. if (mesh._waitingActions) {
  31598. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  31599. mesh._waitingActions = undefined;
  31600. }
  31601. }
  31602. // freeze world matrix application
  31603. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31604. var currentMesh = scene.meshes[index];
  31605. if (currentMesh._waitingFreezeWorldMatrix) {
  31606. currentMesh.freezeWorldMatrix();
  31607. currentMesh._waitingFreezeWorldMatrix = undefined;
  31608. }
  31609. else {
  31610. currentMesh.computeWorldMatrix(true);
  31611. }
  31612. }
  31613. // Particles Systems
  31614. if (parsedData.particleSystems) {
  31615. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  31616. var parsedParticleSystem = parsedData.particleSystems[index];
  31617. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  31618. }
  31619. }
  31620. // Lens flares
  31621. if (parsedData.lensFlareSystems) {
  31622. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  31623. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  31624. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  31625. }
  31626. }
  31627. // Shadows
  31628. if (parsedData.shadowGenerators) {
  31629. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  31630. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  31631. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  31632. }
  31633. }
  31634. // Actions (scene)
  31635. if (parsedData.actions) {
  31636. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  31637. }
  31638. // Finish
  31639. return true;
  31640. }
  31641. catch (err) {
  31642. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  31643. log = null;
  31644. throw err;
  31645. }
  31646. finally {
  31647. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  31648. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  31649. }
  31650. }
  31651. }
  31652. });
  31653. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31654. })(BABYLON || (BABYLON = {}));
  31655. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  31656. var BABYLON;
  31657. (function (BABYLON) {
  31658. var SpriteManager = (function () {
  31659. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  31660. if (epsilon === void 0) { epsilon = 0.01; }
  31661. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31662. this.name = name;
  31663. this.sprites = new Array();
  31664. this.renderingGroupId = 0;
  31665. this.layerMask = 0x0FFFFFFF;
  31666. this.fogEnabled = true;
  31667. this.isPickable = false;
  31668. /**
  31669. * An event triggered when the manager is disposed.
  31670. * @type {BABYLON.Observable}
  31671. */
  31672. this.onDisposeObservable = new BABYLON.Observable();
  31673. this._vertexBuffers = {};
  31674. this._capacity = capacity;
  31675. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  31676. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31677. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31678. if (cellSize.width && cellSize.height) {
  31679. this.cellWidth = cellSize.width;
  31680. this.cellHeight = cellSize.height;
  31681. }
  31682. else if (cellSize !== undefined) {
  31683. this.cellWidth = cellSize;
  31684. this.cellHeight = cellSize;
  31685. }
  31686. else {
  31687. return;
  31688. }
  31689. this._epsilon = epsilon;
  31690. this._scene = scene;
  31691. this._scene.spriteManagers.push(this);
  31692. var indices = [];
  31693. var index = 0;
  31694. for (var count = 0; count < capacity; count++) {
  31695. indices.push(index);
  31696. indices.push(index + 1);
  31697. indices.push(index + 2);
  31698. indices.push(index);
  31699. indices.push(index + 2);
  31700. indices.push(index + 3);
  31701. index += 4;
  31702. }
  31703. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31704. // VBO
  31705. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  31706. this._vertexData = new Float32Array(capacity * 16 * 4);
  31707. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  31708. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  31709. var options = this._buffer.createVertexBuffer("options", 4, 4);
  31710. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  31711. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  31712. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  31713. this._vertexBuffers["options"] = options;
  31714. this._vertexBuffers["cellInfo"] = cellInfo;
  31715. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  31716. // Effects
  31717. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  31718. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  31719. }
  31720. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  31721. set: function (callback) {
  31722. if (this._onDisposeObserver) {
  31723. this.onDisposeObservable.remove(this._onDisposeObserver);
  31724. }
  31725. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31726. },
  31727. enumerable: true,
  31728. configurable: true
  31729. });
  31730. Object.defineProperty(SpriteManager.prototype, "texture", {
  31731. get: function () {
  31732. return this._spriteTexture;
  31733. },
  31734. set: function (value) {
  31735. this._spriteTexture = value;
  31736. },
  31737. enumerable: true,
  31738. configurable: true
  31739. });
  31740. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  31741. var arrayOffset = index * 16;
  31742. if (offsetX === 0)
  31743. offsetX = this._epsilon;
  31744. else if (offsetX === 1)
  31745. offsetX = 1 - this._epsilon;
  31746. if (offsetY === 0)
  31747. offsetY = this._epsilon;
  31748. else if (offsetY === 1)
  31749. offsetY = 1 - this._epsilon;
  31750. this._vertexData[arrayOffset] = sprite.position.x;
  31751. this._vertexData[arrayOffset + 1] = sprite.position.y;
  31752. this._vertexData[arrayOffset + 2] = sprite.position.z;
  31753. this._vertexData[arrayOffset + 3] = sprite.angle;
  31754. this._vertexData[arrayOffset + 4] = sprite.width;
  31755. this._vertexData[arrayOffset + 5] = sprite.height;
  31756. this._vertexData[arrayOffset + 6] = offsetX;
  31757. this._vertexData[arrayOffset + 7] = offsetY;
  31758. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  31759. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  31760. var offset = (sprite.cellIndex / rowSize) >> 0;
  31761. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  31762. this._vertexData[arrayOffset + 11] = offset;
  31763. // Color
  31764. this._vertexData[arrayOffset + 12] = sprite.color.r;
  31765. this._vertexData[arrayOffset + 13] = sprite.color.g;
  31766. this._vertexData[arrayOffset + 14] = sprite.color.b;
  31767. this._vertexData[arrayOffset + 15] = sprite.color.a;
  31768. };
  31769. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  31770. var count = Math.min(this._capacity, this.sprites.length);
  31771. var min = BABYLON.Vector3.Zero();
  31772. var max = BABYLON.Vector3.Zero();
  31773. var distance = Number.MAX_VALUE;
  31774. var currentSprite;
  31775. var cameraSpacePosition = BABYLON.Vector3.Zero();
  31776. var cameraView = camera.getViewMatrix();
  31777. for (var index = 0; index < count; index++) {
  31778. var sprite = this.sprites[index];
  31779. if (!sprite) {
  31780. continue;
  31781. }
  31782. if (predicate) {
  31783. if (!predicate(sprite)) {
  31784. continue;
  31785. }
  31786. }
  31787. else if (!sprite.isPickable) {
  31788. continue;
  31789. }
  31790. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  31791. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  31792. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  31793. if (ray.intersectsBoxMinMax(min, max)) {
  31794. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  31795. if (distance > currentDistance) {
  31796. distance = currentDistance;
  31797. currentSprite = sprite;
  31798. if (fastCheck) {
  31799. break;
  31800. }
  31801. }
  31802. }
  31803. }
  31804. if (currentSprite) {
  31805. var result = new BABYLON.PickingInfo();
  31806. result.hit = true;
  31807. result.pickedSprite = currentSprite;
  31808. result.distance = distance;
  31809. return result;
  31810. }
  31811. return null;
  31812. };
  31813. SpriteManager.prototype.render = function () {
  31814. // Check
  31815. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  31816. return;
  31817. var engine = this._scene.getEngine();
  31818. var baseSize = this._spriteTexture.getBaseSize();
  31819. // Sprites
  31820. var deltaTime = engine.getDeltaTime();
  31821. var max = Math.min(this._capacity, this.sprites.length);
  31822. var rowSize = baseSize.width / this.cellWidth;
  31823. var offset = 0;
  31824. for (var index = 0; index < max; index++) {
  31825. var sprite = this.sprites[index];
  31826. if (!sprite) {
  31827. continue;
  31828. }
  31829. sprite._animate(deltaTime);
  31830. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  31831. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  31832. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  31833. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  31834. }
  31835. this._buffer.update(this._vertexData);
  31836. // Render
  31837. var effect = this._effectBase;
  31838. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31839. effect = this._effectFog;
  31840. }
  31841. engine.enableEffect(effect);
  31842. var viewMatrix = this._scene.getViewMatrix();
  31843. effect.setTexture("diffuseSampler", this._spriteTexture);
  31844. effect.setMatrix("view", viewMatrix);
  31845. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31846. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  31847. // Fog
  31848. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31849. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  31850. effect.setColor3("vFogColor", this._scene.fogColor);
  31851. }
  31852. // VBOs
  31853. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31854. // Draw order
  31855. engine.setDepthFunctionToLessOrEqual();
  31856. effect.setBool("alphaTest", true);
  31857. engine.setColorWrite(false);
  31858. engine.draw(true, 0, max * 6);
  31859. engine.setColorWrite(true);
  31860. effect.setBool("alphaTest", false);
  31861. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31862. engine.draw(true, 0, max * 6);
  31863. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31864. };
  31865. SpriteManager.prototype.dispose = function () {
  31866. if (this._buffer) {
  31867. this._buffer.dispose();
  31868. this._buffer = null;
  31869. }
  31870. if (this._indexBuffer) {
  31871. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31872. this._indexBuffer = null;
  31873. }
  31874. if (this._spriteTexture) {
  31875. this._spriteTexture.dispose();
  31876. this._spriteTexture = null;
  31877. }
  31878. // Remove from scene
  31879. var index = this._scene.spriteManagers.indexOf(this);
  31880. this._scene.spriteManagers.splice(index, 1);
  31881. // Callback
  31882. this.onDisposeObservable.notifyObservers(this);
  31883. this.onDisposeObservable.clear();
  31884. };
  31885. return SpriteManager;
  31886. }());
  31887. BABYLON.SpriteManager = SpriteManager;
  31888. })(BABYLON || (BABYLON = {}));
  31889. //# sourceMappingURL=babylon.spriteManager.js.map
  31890. var BABYLON;
  31891. (function (BABYLON) {
  31892. var Sprite = (function () {
  31893. function Sprite(name, manager) {
  31894. this.name = name;
  31895. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31896. this.width = 1.0;
  31897. this.height = 1.0;
  31898. this.angle = 0;
  31899. this.cellIndex = 0;
  31900. this.invertU = 0;
  31901. this.invertV = 0;
  31902. this.animations = new Array();
  31903. this.isPickable = false;
  31904. this._animationStarted = false;
  31905. this._loopAnimation = false;
  31906. this._fromIndex = 0;
  31907. this._toIndex = 0;
  31908. this._delay = 0;
  31909. this._direction = 1;
  31910. this._frameCount = 0;
  31911. this._time = 0;
  31912. this._manager = manager;
  31913. this._manager.sprites.push(this);
  31914. this.position = BABYLON.Vector3.Zero();
  31915. }
  31916. Object.defineProperty(Sprite.prototype, "size", {
  31917. get: function () {
  31918. return this.width;
  31919. },
  31920. set: function (value) {
  31921. this.width = value;
  31922. this.height = value;
  31923. },
  31924. enumerable: true,
  31925. configurable: true
  31926. });
  31927. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  31928. this._fromIndex = from;
  31929. this._toIndex = to;
  31930. this._loopAnimation = loop;
  31931. this._delay = delay;
  31932. this._animationStarted = true;
  31933. this._direction = from < to ? 1 : -1;
  31934. this.cellIndex = from;
  31935. this._time = 0;
  31936. this._onAnimationEnd = onAnimationEnd;
  31937. };
  31938. Sprite.prototype.stopAnimation = function () {
  31939. this._animationStarted = false;
  31940. };
  31941. Sprite.prototype._animate = function (deltaTime) {
  31942. if (!this._animationStarted)
  31943. return;
  31944. this._time += deltaTime;
  31945. if (this._time > this._delay) {
  31946. this._time = this._time % this._delay;
  31947. this.cellIndex += this._direction;
  31948. if (this.cellIndex === this._toIndex) {
  31949. if (this._loopAnimation) {
  31950. this.cellIndex = this._fromIndex;
  31951. }
  31952. else {
  31953. this._animationStarted = false;
  31954. if (this._onAnimationEnd) {
  31955. this._onAnimationEnd();
  31956. }
  31957. if (this.disposeWhenFinishedAnimating) {
  31958. this.dispose();
  31959. }
  31960. }
  31961. }
  31962. }
  31963. };
  31964. Sprite.prototype.dispose = function () {
  31965. for (var i = 0; i < this._manager.sprites.length; i++) {
  31966. if (this._manager.sprites[i] == this) {
  31967. this._manager.sprites.splice(i, 1);
  31968. }
  31969. }
  31970. };
  31971. return Sprite;
  31972. }());
  31973. BABYLON.Sprite = Sprite;
  31974. })(BABYLON || (BABYLON = {}));
  31975. //# sourceMappingURL=babylon.sprite.js.map
  31976. var BABYLON;
  31977. (function (BABYLON) {
  31978. var Layer = (function () {
  31979. function Layer(name, imgUrl, scene, isBackground, color) {
  31980. this.name = name;
  31981. this.scale = new BABYLON.Vector2(1, 1);
  31982. this.offset = new BABYLON.Vector2(0, 0);
  31983. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  31984. this._vertexBuffers = {};
  31985. // Events
  31986. /**
  31987. * An event triggered when the layer is disposed.
  31988. * @type {BABYLON.Observable}
  31989. */
  31990. this.onDisposeObservable = new BABYLON.Observable();
  31991. /**
  31992. * An event triggered before rendering the scene
  31993. * @type {BABYLON.Observable}
  31994. */
  31995. this.onBeforeRenderObservable = new BABYLON.Observable();
  31996. /**
  31997. * An event triggered after rendering the scene
  31998. * @type {BABYLON.Observable}
  31999. */
  32000. this.onAfterRenderObservable = new BABYLON.Observable();
  32001. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  32002. this.isBackground = isBackground === undefined ? true : isBackground;
  32003. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  32004. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  32005. this._scene.layers.push(this);
  32006. var engine = scene.getEngine();
  32007. // VBO
  32008. var vertices = [];
  32009. vertices.push(1, 1);
  32010. vertices.push(-1, 1);
  32011. vertices.push(-1, -1);
  32012. vertices.push(1, -1);
  32013. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32014. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  32015. // Indices
  32016. var indices = [];
  32017. indices.push(0);
  32018. indices.push(1);
  32019. indices.push(2);
  32020. indices.push(0);
  32021. indices.push(2);
  32022. indices.push(3);
  32023. this._indexBuffer = engine.createIndexBuffer(indices);
  32024. // Effects
  32025. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  32026. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  32027. }
  32028. Object.defineProperty(Layer.prototype, "onDispose", {
  32029. set: function (callback) {
  32030. if (this._onDisposeObserver) {
  32031. this.onDisposeObservable.remove(this._onDisposeObserver);
  32032. }
  32033. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32034. },
  32035. enumerable: true,
  32036. configurable: true
  32037. });
  32038. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  32039. set: function (callback) {
  32040. if (this._onBeforeRenderObserver) {
  32041. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32042. }
  32043. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32044. },
  32045. enumerable: true,
  32046. configurable: true
  32047. });
  32048. Object.defineProperty(Layer.prototype, "onAfterRender", {
  32049. set: function (callback) {
  32050. if (this._onAfterRenderObserver) {
  32051. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32052. }
  32053. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32054. },
  32055. enumerable: true,
  32056. configurable: true
  32057. });
  32058. Layer.prototype.render = function () {
  32059. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  32060. // Check
  32061. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  32062. return;
  32063. var engine = this._scene.getEngine();
  32064. this.onBeforeRenderObservable.notifyObservers(this);
  32065. // Render
  32066. engine.enableEffect(currentEffect);
  32067. engine.setState(false);
  32068. // Texture
  32069. currentEffect.setTexture("textureSampler", this.texture);
  32070. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  32071. // Color
  32072. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  32073. // Scale / offset
  32074. currentEffect.setVector2("offset", this.offset);
  32075. currentEffect.setVector2("scale", this.scale);
  32076. // VBOs
  32077. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  32078. // Draw order
  32079. if (!this.alphaTest) {
  32080. engine.setAlphaMode(this.alphaBlendingMode);
  32081. engine.draw(true, 0, 6);
  32082. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32083. }
  32084. else {
  32085. engine.draw(true, 0, 6);
  32086. }
  32087. this.onAfterRenderObservable.notifyObservers(this);
  32088. };
  32089. Layer.prototype.dispose = function () {
  32090. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32091. if (vertexBuffer) {
  32092. vertexBuffer.dispose();
  32093. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32094. }
  32095. if (this._indexBuffer) {
  32096. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32097. this._indexBuffer = null;
  32098. }
  32099. if (this.texture) {
  32100. this.texture.dispose();
  32101. this.texture = null;
  32102. }
  32103. // Remove from scene
  32104. var index = this._scene.layers.indexOf(this);
  32105. this._scene.layers.splice(index, 1);
  32106. // Callback
  32107. this.onDisposeObservable.notifyObservers(this);
  32108. this.onDisposeObservable.clear();
  32109. this.onAfterRenderObservable.clear();
  32110. this.onBeforeRenderObservable.clear();
  32111. };
  32112. return Layer;
  32113. }());
  32114. BABYLON.Layer = Layer;
  32115. })(BABYLON || (BABYLON = {}));
  32116. //# sourceMappingURL=babylon.layer.js.map
  32117. var BABYLON;
  32118. (function (BABYLON) {
  32119. var Particle = (function () {
  32120. function Particle() {
  32121. this.position = BABYLON.Vector3.Zero();
  32122. this.direction = BABYLON.Vector3.Zero();
  32123. this.color = new BABYLON.Color4(0, 0, 0, 0);
  32124. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  32125. this.lifeTime = 1.0;
  32126. this.age = 0;
  32127. this.size = 0;
  32128. this.angle = 0;
  32129. this.angularSpeed = 0;
  32130. }
  32131. Particle.prototype.copyTo = function (other) {
  32132. other.position.copyFrom(this.position);
  32133. other.direction.copyFrom(this.direction);
  32134. other.color.copyFrom(this.color);
  32135. other.colorStep.copyFrom(this.colorStep);
  32136. other.lifeTime = this.lifeTime;
  32137. other.age = this.age;
  32138. other.size = this.size;
  32139. other.angle = this.angle;
  32140. other.angularSpeed = this.angularSpeed;
  32141. };
  32142. return Particle;
  32143. }());
  32144. BABYLON.Particle = Particle;
  32145. })(BABYLON || (BABYLON = {}));
  32146. //# sourceMappingURL=babylon.particle.js.map
  32147. var BABYLON;
  32148. (function (BABYLON) {
  32149. var randomNumber = function (min, max) {
  32150. if (min === max) {
  32151. return (min);
  32152. }
  32153. var random = Math.random();
  32154. return ((random * (max - min)) + min);
  32155. };
  32156. var ParticleSystem = (function () {
  32157. function ParticleSystem(name, capacity, scene, customEffect) {
  32158. var _this = this;
  32159. this.name = name;
  32160. // Members
  32161. this.animations = [];
  32162. this.renderingGroupId = 0;
  32163. this.emitter = null;
  32164. this.emitRate = 10;
  32165. this.manualEmitCount = -1;
  32166. this.updateSpeed = 0.01;
  32167. this.targetStopDuration = 0;
  32168. this.disposeOnStop = false;
  32169. this.minEmitPower = 1;
  32170. this.maxEmitPower = 1;
  32171. this.minLifeTime = 1;
  32172. this.maxLifeTime = 1;
  32173. this.minSize = 1;
  32174. this.maxSize = 1;
  32175. this.minAngularSpeed = 0;
  32176. this.maxAngularSpeed = 0;
  32177. this.layerMask = 0x0FFFFFFF;
  32178. this.customShader = null;
  32179. this.preventAutoStart = false;
  32180. /**
  32181. * An event triggered when the system is disposed.
  32182. * @type {BABYLON.Observable}
  32183. */
  32184. this.onDisposeObservable = new BABYLON.Observable();
  32185. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  32186. this.forceDepthWrite = false;
  32187. this.gravity = BABYLON.Vector3.Zero();
  32188. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  32189. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  32190. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  32191. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32192. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32193. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32194. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  32195. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32196. this.particles = new Array();
  32197. this._stockParticles = new Array();
  32198. this._newPartsExcess = 0;
  32199. this._vertexBuffers = {};
  32200. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  32201. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  32202. this._scaledDirection = BABYLON.Vector3.Zero();
  32203. this._scaledGravity = BABYLON.Vector3.Zero();
  32204. this._currentRenderId = -1;
  32205. this._started = false;
  32206. this._stopped = false;
  32207. this._actualFrame = 0;
  32208. this.id = name;
  32209. this._capacity = capacity;
  32210. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  32211. this._customEffect = customEffect;
  32212. scene.particleSystems.push(this);
  32213. var indices = [];
  32214. var index = 0;
  32215. for (var count = 0; count < capacity; count++) {
  32216. indices.push(index);
  32217. indices.push(index + 1);
  32218. indices.push(index + 2);
  32219. indices.push(index);
  32220. indices.push(index + 2);
  32221. indices.push(index + 3);
  32222. index += 4;
  32223. }
  32224. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32225. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  32226. this._vertexData = new Float32Array(capacity * 11 * 4);
  32227. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  32228. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  32229. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  32230. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  32231. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  32232. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  32233. this._vertexBuffers["options"] = options;
  32234. // Default behaviors
  32235. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  32236. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  32237. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  32238. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  32239. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  32240. };
  32241. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  32242. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  32243. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  32244. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  32245. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  32246. };
  32247. this.updateFunction = function (particles) {
  32248. for (var index = 0; index < particles.length; index++) {
  32249. var particle = particles[index];
  32250. particle.age += _this._scaledUpdateSpeed;
  32251. if (particle.age >= particle.lifeTime) {
  32252. _this.recycleParticle(particle);
  32253. index--;
  32254. continue;
  32255. }
  32256. else {
  32257. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  32258. particle.color.addInPlace(_this._scaledColorStep);
  32259. if (particle.color.a < 0)
  32260. particle.color.a = 0;
  32261. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  32262. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  32263. particle.position.addInPlace(_this._scaledDirection);
  32264. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  32265. particle.direction.addInPlace(_this._scaledGravity);
  32266. }
  32267. }
  32268. };
  32269. }
  32270. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  32271. set: function (callback) {
  32272. if (this._onDisposeObserver) {
  32273. this.onDisposeObservable.remove(this._onDisposeObserver);
  32274. }
  32275. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32276. },
  32277. enumerable: true,
  32278. configurable: true
  32279. });
  32280. ParticleSystem.prototype.recycleParticle = function (particle) {
  32281. var lastParticle = this.particles.pop();
  32282. if (lastParticle !== particle) {
  32283. lastParticle.copyTo(particle);
  32284. this._stockParticles.push(lastParticle);
  32285. }
  32286. };
  32287. ParticleSystem.prototype.getCapacity = function () {
  32288. return this._capacity;
  32289. };
  32290. ParticleSystem.prototype.isAlive = function () {
  32291. return this._alive;
  32292. };
  32293. ParticleSystem.prototype.isStarted = function () {
  32294. return this._started;
  32295. };
  32296. ParticleSystem.prototype.start = function () {
  32297. this._started = true;
  32298. this._stopped = false;
  32299. this._actualFrame = 0;
  32300. };
  32301. ParticleSystem.prototype.stop = function () {
  32302. this._stopped = true;
  32303. };
  32304. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  32305. var offset = index * 11;
  32306. this._vertexData[offset] = particle.position.x;
  32307. this._vertexData[offset + 1] = particle.position.y;
  32308. this._vertexData[offset + 2] = particle.position.z;
  32309. this._vertexData[offset + 3] = particle.color.r;
  32310. this._vertexData[offset + 4] = particle.color.g;
  32311. this._vertexData[offset + 5] = particle.color.b;
  32312. this._vertexData[offset + 6] = particle.color.a;
  32313. this._vertexData[offset + 7] = particle.angle;
  32314. this._vertexData[offset + 8] = particle.size;
  32315. this._vertexData[offset + 9] = offsetX;
  32316. this._vertexData[offset + 10] = offsetY;
  32317. };
  32318. ParticleSystem.prototype._update = function (newParticles) {
  32319. // Update current
  32320. this._alive = this.particles.length > 0;
  32321. this.updateFunction(this.particles);
  32322. // Add new ones
  32323. var worldMatrix;
  32324. if (this.emitter.position) {
  32325. worldMatrix = this.emitter.getWorldMatrix();
  32326. }
  32327. else {
  32328. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  32329. }
  32330. var particle;
  32331. for (var index = 0; index < newParticles; index++) {
  32332. if (this.particles.length === this._capacity) {
  32333. break;
  32334. }
  32335. if (this._stockParticles.length !== 0) {
  32336. particle = this._stockParticles.pop();
  32337. particle.age = 0;
  32338. }
  32339. else {
  32340. particle = new BABYLON.Particle();
  32341. }
  32342. this.particles.push(particle);
  32343. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  32344. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  32345. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  32346. particle.size = randomNumber(this.minSize, this.maxSize);
  32347. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  32348. this.startPositionFunction(worldMatrix, particle.position, particle);
  32349. var step = randomNumber(0, 1.0);
  32350. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  32351. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  32352. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  32353. }
  32354. };
  32355. ParticleSystem.prototype._getEffect = function () {
  32356. if (this._customEffect) {
  32357. return this._customEffect;
  32358. }
  32359. ;
  32360. var defines = [];
  32361. if (this._scene.clipPlane) {
  32362. defines.push("#define CLIPPLANE");
  32363. }
  32364. // Effect
  32365. var join = defines.join("\n");
  32366. if (this._cachedDefines !== join) {
  32367. this._cachedDefines = join;
  32368. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  32369. }
  32370. return this._effect;
  32371. };
  32372. ParticleSystem.prototype.animate = function () {
  32373. if (!this._started)
  32374. return;
  32375. var effect = this._getEffect();
  32376. // Check
  32377. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  32378. return;
  32379. if (this._currentRenderId === this._scene.getRenderId()) {
  32380. return;
  32381. }
  32382. this._currentRenderId = this._scene.getRenderId();
  32383. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  32384. // determine the number of particles we need to create
  32385. var newParticles;
  32386. if (this.manualEmitCount > -1) {
  32387. newParticles = this.manualEmitCount;
  32388. this._newPartsExcess = 0;
  32389. this.manualEmitCount = 0;
  32390. }
  32391. else {
  32392. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  32393. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  32394. }
  32395. if (this._newPartsExcess > 1.0) {
  32396. newParticles += this._newPartsExcess >> 0;
  32397. this._newPartsExcess -= this._newPartsExcess >> 0;
  32398. }
  32399. this._alive = false;
  32400. if (!this._stopped) {
  32401. this._actualFrame += this._scaledUpdateSpeed;
  32402. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  32403. this.stop();
  32404. }
  32405. else {
  32406. newParticles = 0;
  32407. }
  32408. this._update(newParticles);
  32409. // Stopped?
  32410. if (this._stopped) {
  32411. if (!this._alive) {
  32412. this._started = false;
  32413. if (this.disposeOnStop) {
  32414. this._scene._toBeDisposed.push(this);
  32415. }
  32416. }
  32417. }
  32418. // Update VBO
  32419. var offset = 0;
  32420. for (var index = 0; index < this.particles.length; index++) {
  32421. var particle = this.particles[index];
  32422. this._appendParticleVertex(offset++, particle, 0, 0);
  32423. this._appendParticleVertex(offset++, particle, 1, 0);
  32424. this._appendParticleVertex(offset++, particle, 1, 1);
  32425. this._appendParticleVertex(offset++, particle, 0, 1);
  32426. }
  32427. this._vertexBuffer.update(this._vertexData);
  32428. };
  32429. ParticleSystem.prototype.render = function () {
  32430. var effect = this._getEffect();
  32431. // Check
  32432. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  32433. return 0;
  32434. var engine = this._scene.getEngine();
  32435. // Render
  32436. engine.enableEffect(effect);
  32437. engine.setState(false);
  32438. var viewMatrix = this._scene.getViewMatrix();
  32439. effect.setTexture("diffuseSampler", this.particleTexture);
  32440. effect.setMatrix("view", viewMatrix);
  32441. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  32442. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  32443. if (this._scene.clipPlane) {
  32444. var clipPlane = this._scene.clipPlane;
  32445. var invView = viewMatrix.clone();
  32446. invView.invert();
  32447. effect.setMatrix("invView", invView);
  32448. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  32449. }
  32450. // VBOs
  32451. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32452. // Draw order
  32453. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  32454. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32455. }
  32456. else {
  32457. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32458. }
  32459. if (this.forceDepthWrite) {
  32460. engine.setDepthWrite(true);
  32461. }
  32462. engine.draw(true, 0, this.particles.length * 6);
  32463. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32464. return this.particles.length;
  32465. };
  32466. ParticleSystem.prototype.dispose = function () {
  32467. if (this._vertexBuffer) {
  32468. this._vertexBuffer.dispose();
  32469. this._vertexBuffer = null;
  32470. }
  32471. if (this._indexBuffer) {
  32472. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32473. this._indexBuffer = null;
  32474. }
  32475. if (this.particleTexture) {
  32476. this.particleTexture.dispose();
  32477. this.particleTexture = null;
  32478. }
  32479. // Remove from scene
  32480. var index = this._scene.particleSystems.indexOf(this);
  32481. this._scene.particleSystems.splice(index, 1);
  32482. // Callback
  32483. this.onDisposeObservable.notifyObservers(this);
  32484. this.onDisposeObservable.clear();
  32485. };
  32486. // Clone
  32487. ParticleSystem.prototype.clone = function (name, newEmitter) {
  32488. var custom = null;
  32489. var program = null;
  32490. if (this.customShader != null) {
  32491. program = this.customShader;
  32492. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  32493. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  32494. }
  32495. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  32496. result.customShader = program;
  32497. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  32498. if (newEmitter === undefined) {
  32499. newEmitter = this.emitter;
  32500. }
  32501. result.emitter = newEmitter;
  32502. if (this.particleTexture) {
  32503. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  32504. }
  32505. if (!this.preventAutoStart) {
  32506. result.start();
  32507. }
  32508. return result;
  32509. };
  32510. ParticleSystem.prototype.serialize = function () {
  32511. var serializationObject = {};
  32512. serializationObject.name = this.name;
  32513. serializationObject.id = this.id;
  32514. // Emitter
  32515. if (this.emitter.position) {
  32516. serializationObject.emitterId = this.emitter.id;
  32517. }
  32518. else {
  32519. serializationObject.emitter = this.emitter.asArray();
  32520. }
  32521. serializationObject.capacity = this.getCapacity();
  32522. if (this.particleTexture) {
  32523. serializationObject.textureName = this.particleTexture.name;
  32524. }
  32525. // Animations
  32526. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32527. // Particle system
  32528. serializationObject.minAngularSpeed = this.minAngularSpeed;
  32529. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  32530. serializationObject.minSize = this.minSize;
  32531. serializationObject.maxSize = this.maxSize;
  32532. serializationObject.minEmitPower = this.minEmitPower;
  32533. serializationObject.maxEmitPower = this.maxEmitPower;
  32534. serializationObject.minLifeTime = this.minLifeTime;
  32535. serializationObject.maxLifeTime = this.maxLifeTime;
  32536. serializationObject.emitRate = this.emitRate;
  32537. serializationObject.minEmitBox = this.minEmitBox.asArray();
  32538. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  32539. serializationObject.gravity = this.gravity.asArray();
  32540. serializationObject.direction1 = this.direction1.asArray();
  32541. serializationObject.direction2 = this.direction2.asArray();
  32542. serializationObject.color1 = this.color1.asArray();
  32543. serializationObject.color2 = this.color2.asArray();
  32544. serializationObject.colorDead = this.colorDead.asArray();
  32545. serializationObject.updateSpeed = this.updateSpeed;
  32546. serializationObject.targetStopDuration = this.targetStopDuration;
  32547. serializationObject.textureMask = this.textureMask.asArray();
  32548. serializationObject.blendMode = this.blendMode;
  32549. serializationObject.customShader = this.customShader;
  32550. serializationObject.preventAutoStart = this.preventAutoStart;
  32551. return serializationObject;
  32552. };
  32553. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  32554. var name = parsedParticleSystem.name;
  32555. var custom = null;
  32556. var program = null;
  32557. if (parsedParticleSystem.customShader) {
  32558. program = parsedParticleSystem.customShader;
  32559. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  32560. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  32561. }
  32562. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  32563. particleSystem.customShader = program;
  32564. if (parsedParticleSystem.id) {
  32565. particleSystem.id = parsedParticleSystem.id;
  32566. }
  32567. // Auto start
  32568. if (parsedParticleSystem.preventAutoStart) {
  32569. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  32570. }
  32571. // Texture
  32572. if (parsedParticleSystem.textureName) {
  32573. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  32574. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  32575. }
  32576. // Emitter
  32577. if (parsedParticleSystem.emitterId) {
  32578. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  32579. }
  32580. else {
  32581. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  32582. }
  32583. // Animations
  32584. if (parsedParticleSystem.animations) {
  32585. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  32586. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  32587. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32588. }
  32589. }
  32590. if (parsedParticleSystem.autoAnimate) {
  32591. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  32592. }
  32593. // Particle system
  32594. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  32595. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  32596. particleSystem.minSize = parsedParticleSystem.minSize;
  32597. particleSystem.maxSize = parsedParticleSystem.maxSize;
  32598. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  32599. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  32600. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  32601. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  32602. particleSystem.emitRate = parsedParticleSystem.emitRate;
  32603. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  32604. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  32605. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  32606. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  32607. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  32608. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  32609. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  32610. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  32611. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  32612. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  32613. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  32614. particleSystem.blendMode = parsedParticleSystem.blendMode;
  32615. if (!particleSystem.preventAutoStart) {
  32616. particleSystem.start();
  32617. }
  32618. return particleSystem;
  32619. };
  32620. return ParticleSystem;
  32621. }());
  32622. // Statics
  32623. ParticleSystem.BLENDMODE_ONEONE = 0;
  32624. ParticleSystem.BLENDMODE_STANDARD = 1;
  32625. BABYLON.ParticleSystem = ParticleSystem;
  32626. })(BABYLON || (BABYLON = {}));
  32627. //# sourceMappingURL=babylon.particleSystem.js.map
  32628. var BABYLON;
  32629. (function (BABYLON) {
  32630. var AnimationRange = (function () {
  32631. function AnimationRange(name, from, to) {
  32632. this.name = name;
  32633. this.from = from;
  32634. this.to = to;
  32635. }
  32636. AnimationRange.prototype.clone = function () {
  32637. return new AnimationRange(this.name, this.from, this.to);
  32638. };
  32639. return AnimationRange;
  32640. }());
  32641. BABYLON.AnimationRange = AnimationRange;
  32642. /**
  32643. * Composed of a frame, and an action function
  32644. */
  32645. var AnimationEvent = (function () {
  32646. function AnimationEvent(frame, action, onlyOnce) {
  32647. this.frame = frame;
  32648. this.action = action;
  32649. this.onlyOnce = onlyOnce;
  32650. this.isDone = false;
  32651. }
  32652. return AnimationEvent;
  32653. }());
  32654. BABYLON.AnimationEvent = AnimationEvent;
  32655. var PathCursor = (function () {
  32656. function PathCursor(path) {
  32657. this.path = path;
  32658. this._onchange = new Array();
  32659. this.value = 0;
  32660. this.animations = new Array();
  32661. }
  32662. PathCursor.prototype.getPoint = function () {
  32663. var point = this.path.getPointAtLengthPosition(this.value);
  32664. return new BABYLON.Vector3(point.x, 0, point.y);
  32665. };
  32666. PathCursor.prototype.moveAhead = function (step) {
  32667. if (step === void 0) { step = 0.002; }
  32668. this.move(step);
  32669. return this;
  32670. };
  32671. PathCursor.prototype.moveBack = function (step) {
  32672. if (step === void 0) { step = 0.002; }
  32673. this.move(-step);
  32674. return this;
  32675. };
  32676. PathCursor.prototype.move = function (step) {
  32677. if (Math.abs(step) > 1) {
  32678. throw "step size should be less than 1.";
  32679. }
  32680. this.value += step;
  32681. this.ensureLimits();
  32682. this.raiseOnChange();
  32683. return this;
  32684. };
  32685. PathCursor.prototype.ensureLimits = function () {
  32686. while (this.value > 1) {
  32687. this.value -= 1;
  32688. }
  32689. while (this.value < 0) {
  32690. this.value += 1;
  32691. }
  32692. return this;
  32693. };
  32694. // used by animation engine
  32695. PathCursor.prototype.markAsDirty = function (propertyName) {
  32696. this.ensureLimits();
  32697. this.raiseOnChange();
  32698. return this;
  32699. };
  32700. PathCursor.prototype.raiseOnChange = function () {
  32701. var _this = this;
  32702. this._onchange.forEach(function (f) { return f(_this); });
  32703. return this;
  32704. };
  32705. PathCursor.prototype.onchange = function (f) {
  32706. this._onchange.push(f);
  32707. return this;
  32708. };
  32709. return PathCursor;
  32710. }());
  32711. BABYLON.PathCursor = PathCursor;
  32712. var Animation = (function () {
  32713. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  32714. this.name = name;
  32715. this.targetProperty = targetProperty;
  32716. this.framePerSecond = framePerSecond;
  32717. this.dataType = dataType;
  32718. this.loopMode = loopMode;
  32719. this.enableBlending = enableBlending;
  32720. this._offsetsCache = {};
  32721. this._highLimitsCache = {};
  32722. this._stopped = false;
  32723. this._blendingFactor = 0;
  32724. // The set of event that will be linked to this animation
  32725. this._events = new Array();
  32726. this.allowMatricesInterpolation = false;
  32727. this.blendingSpeed = 0.01;
  32728. this._ranges = {};
  32729. this.targetPropertyPath = targetProperty.split(".");
  32730. this.dataType = dataType;
  32731. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  32732. }
  32733. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  32734. var dataType = undefined;
  32735. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  32736. dataType = Animation.ANIMATIONTYPE_FLOAT;
  32737. }
  32738. else if (from instanceof BABYLON.Quaternion) {
  32739. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  32740. }
  32741. else if (from instanceof BABYLON.Vector3) {
  32742. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  32743. }
  32744. else if (from instanceof BABYLON.Vector2) {
  32745. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32746. }
  32747. else if (from instanceof BABYLON.Color3) {
  32748. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32749. }
  32750. else if (from instanceof BABYLON.Size) {
  32751. dataType = Animation.ANIMATIONTYPE_SIZE;
  32752. }
  32753. if (dataType == undefined) {
  32754. return null;
  32755. }
  32756. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32757. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32758. animation.setKeys(keys);
  32759. if (easingFunction !== undefined) {
  32760. animation.setEasingFunction(easingFunction);
  32761. }
  32762. return animation;
  32763. };
  32764. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32765. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32766. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32767. };
  32768. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32769. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32770. node.animations.push(animation);
  32771. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32772. };
  32773. // Methods
  32774. /**
  32775. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32776. */
  32777. Animation.prototype.toString = function (fullDetails) {
  32778. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32779. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32780. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32781. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32782. if (fullDetails) {
  32783. ret += ", Ranges: {";
  32784. var first = true;
  32785. for (var name in this._ranges) {
  32786. if (first) {
  32787. ret += ", ";
  32788. first = false;
  32789. }
  32790. ret += name;
  32791. }
  32792. ret += "}";
  32793. }
  32794. return ret;
  32795. };
  32796. /**
  32797. * Add an event to this animation.
  32798. */
  32799. Animation.prototype.addEvent = function (event) {
  32800. this._events.push(event);
  32801. };
  32802. /**
  32803. * Remove all events found at the given frame
  32804. * @param frame
  32805. */
  32806. Animation.prototype.removeEvents = function (frame) {
  32807. for (var index = 0; index < this._events.length; index++) {
  32808. if (this._events[index].frame === frame) {
  32809. this._events.splice(index, 1);
  32810. index--;
  32811. }
  32812. }
  32813. };
  32814. Animation.prototype.createRange = function (name, from, to) {
  32815. // check name not already in use; could happen for bones after serialized
  32816. if (!this._ranges[name]) {
  32817. this._ranges[name] = new AnimationRange(name, from, to);
  32818. }
  32819. };
  32820. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32821. if (deleteFrames === void 0) { deleteFrames = true; }
  32822. if (this._ranges[name]) {
  32823. if (deleteFrames) {
  32824. var from = this._ranges[name].from;
  32825. var to = this._ranges[name].to;
  32826. // this loop MUST go high to low for multiple splices to work
  32827. for (var key = this._keys.length - 1; key >= 0; key--) {
  32828. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32829. this._keys.splice(key, 1);
  32830. }
  32831. }
  32832. }
  32833. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32834. }
  32835. };
  32836. Animation.prototype.getRange = function (name) {
  32837. return this._ranges[name];
  32838. };
  32839. Animation.prototype.reset = function () {
  32840. this._offsetsCache = {};
  32841. this._highLimitsCache = {};
  32842. this.currentFrame = 0;
  32843. this._blendingFactor = 0;
  32844. this._originalBlendValue = null;
  32845. };
  32846. Animation.prototype.isStopped = function () {
  32847. return this._stopped;
  32848. };
  32849. Animation.prototype.getKeys = function () {
  32850. return this._keys;
  32851. };
  32852. Animation.prototype.getHighestFrame = function () {
  32853. var ret = 0;
  32854. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32855. if (ret < this._keys[key].frame) {
  32856. ret = this._keys[key].frame;
  32857. }
  32858. }
  32859. return ret;
  32860. };
  32861. Animation.prototype.getEasingFunction = function () {
  32862. return this._easingFunction;
  32863. };
  32864. Animation.prototype.setEasingFunction = function (easingFunction) {
  32865. this._easingFunction = easingFunction;
  32866. };
  32867. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32868. return startValue + (endValue - startValue) * gradient;
  32869. };
  32870. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32871. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32872. };
  32873. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32874. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32875. };
  32876. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32877. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32878. };
  32879. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32880. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32881. };
  32882. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32883. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32884. };
  32885. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32886. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32887. };
  32888. Animation.prototype.clone = function () {
  32889. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32890. clone.enableBlending = this.enableBlending;
  32891. clone.blendingSpeed = this.blendingSpeed;
  32892. if (this._keys) {
  32893. clone.setKeys(this._keys);
  32894. }
  32895. if (this._ranges) {
  32896. clone._ranges = {};
  32897. for (var name in this._ranges) {
  32898. clone._ranges[name] = this._ranges[name].clone();
  32899. }
  32900. }
  32901. return clone;
  32902. };
  32903. Animation.prototype.setKeys = function (values) {
  32904. this._keys = values.slice(0);
  32905. this._offsetsCache = {};
  32906. this._highLimitsCache = {};
  32907. };
  32908. Animation.prototype._getKeyValue = function (value) {
  32909. if (typeof value === "function") {
  32910. return value();
  32911. }
  32912. return value;
  32913. };
  32914. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  32915. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  32916. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  32917. }
  32918. this.currentFrame = currentFrame;
  32919. // Try to get a hash to find the right key
  32920. 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));
  32921. if (this._keys[startKey].frame >= currentFrame) {
  32922. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  32923. startKey--;
  32924. }
  32925. }
  32926. for (var key = startKey; key < this._keys.length; key++) {
  32927. if (this._keys[key + 1].frame >= currentFrame) {
  32928. var startValue = this._getKeyValue(this._keys[key].value);
  32929. var endValue = this._getKeyValue(this._keys[key + 1].value);
  32930. // gradient : percent of currentFrame between the frame inf and the frame sup
  32931. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  32932. // check for easingFunction and correction of gradient
  32933. if (this._easingFunction != null) {
  32934. gradient = this._easingFunction.ease(gradient);
  32935. }
  32936. switch (this.dataType) {
  32937. // Float
  32938. case Animation.ANIMATIONTYPE_FLOAT:
  32939. switch (loopMode) {
  32940. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32941. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32942. return this.floatInterpolateFunction(startValue, endValue, gradient);
  32943. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32944. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  32945. }
  32946. break;
  32947. // Quaternion
  32948. case Animation.ANIMATIONTYPE_QUATERNION:
  32949. var quaternion = null;
  32950. switch (loopMode) {
  32951. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32952. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32953. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  32954. break;
  32955. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32956. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32957. break;
  32958. }
  32959. return quaternion;
  32960. // Vector3
  32961. case Animation.ANIMATIONTYPE_VECTOR3:
  32962. switch (loopMode) {
  32963. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32964. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32965. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  32966. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32967. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32968. }
  32969. // Vector2
  32970. case Animation.ANIMATIONTYPE_VECTOR2:
  32971. switch (loopMode) {
  32972. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32973. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32974. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  32975. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32976. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32977. }
  32978. // Size
  32979. case Animation.ANIMATIONTYPE_SIZE:
  32980. switch (loopMode) {
  32981. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32982. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32983. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  32984. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32985. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32986. }
  32987. // Color3
  32988. case Animation.ANIMATIONTYPE_COLOR3:
  32989. switch (loopMode) {
  32990. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32991. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32992. return this.color3InterpolateFunction(startValue, endValue, gradient);
  32993. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32994. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32995. }
  32996. // Matrix
  32997. case Animation.ANIMATIONTYPE_MATRIX:
  32998. switch (loopMode) {
  32999. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33000. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33001. if (this.allowMatricesInterpolation) {
  33002. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  33003. }
  33004. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33005. return startValue;
  33006. }
  33007. default:
  33008. break;
  33009. }
  33010. break;
  33011. }
  33012. }
  33013. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  33014. };
  33015. Animation.prototype.setValue = function (currentValue, blend) {
  33016. if (blend === void 0) { blend = false; }
  33017. // Set value
  33018. var path;
  33019. var destination;
  33020. if (this.targetPropertyPath.length > 1) {
  33021. var property = this._target[this.targetPropertyPath[0]];
  33022. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  33023. property = property[this.targetPropertyPath[index]];
  33024. }
  33025. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  33026. destination = property;
  33027. }
  33028. else {
  33029. path = this.targetPropertyPath[0];
  33030. destination = this._target;
  33031. }
  33032. // Blending
  33033. if (this.enableBlending && this._blendingFactor <= 1.0) {
  33034. if (!this._originalBlendValue) {
  33035. if (destination[path].clone) {
  33036. this._originalBlendValue = destination[path].clone();
  33037. }
  33038. else {
  33039. this._originalBlendValue = destination[path];
  33040. }
  33041. }
  33042. if (this._originalBlendValue.prototype) {
  33043. if (this._originalBlendValue.prototype.Lerp) {
  33044. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  33045. }
  33046. else {
  33047. destination[path] = currentValue;
  33048. }
  33049. }
  33050. else if (this._originalBlendValue.m) {
  33051. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  33052. }
  33053. else {
  33054. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  33055. }
  33056. this._blendingFactor += this.blendingSpeed;
  33057. }
  33058. else {
  33059. destination[path] = currentValue;
  33060. }
  33061. if (this._target.markAsDirty) {
  33062. this._target.markAsDirty(this.targetProperty);
  33063. }
  33064. };
  33065. Animation.prototype.goToFrame = function (frame) {
  33066. if (frame < this._keys[0].frame) {
  33067. frame = this._keys[0].frame;
  33068. }
  33069. else if (frame > this._keys[this._keys.length - 1].frame) {
  33070. frame = this._keys[this._keys.length - 1].frame;
  33071. }
  33072. var currentValue = this._interpolate(frame, 0, this.loopMode);
  33073. this.setValue(currentValue);
  33074. };
  33075. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  33076. if (blend === void 0) { blend = false; }
  33077. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  33078. this._stopped = true;
  33079. return false;
  33080. }
  33081. var returnValue = true;
  33082. // Adding a start key at frame 0 if missing
  33083. if (this._keys[0].frame !== 0) {
  33084. var newKey = { frame: 0, value: this._keys[0].value };
  33085. this._keys.splice(0, 0, newKey);
  33086. }
  33087. // Check limits
  33088. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  33089. from = this._keys[0].frame;
  33090. }
  33091. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  33092. to = this._keys[this._keys.length - 1].frame;
  33093. }
  33094. //to and from cannot be the same key
  33095. if (from === to) {
  33096. from++;
  33097. }
  33098. // Compute ratio
  33099. var range = to - from;
  33100. var offsetValue;
  33101. // ratio represents the frame delta between from and to
  33102. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  33103. var highLimitValue = 0;
  33104. if (ratio > range && !loop) {
  33105. returnValue = false;
  33106. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  33107. }
  33108. else {
  33109. // Get max value if required
  33110. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  33111. var keyOffset = to.toString() + from.toString();
  33112. if (!this._offsetsCache[keyOffset]) {
  33113. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  33114. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  33115. switch (this.dataType) {
  33116. // Float
  33117. case Animation.ANIMATIONTYPE_FLOAT:
  33118. this._offsetsCache[keyOffset] = toValue - fromValue;
  33119. break;
  33120. // Quaternion
  33121. case Animation.ANIMATIONTYPE_QUATERNION:
  33122. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33123. break;
  33124. // Vector3
  33125. case Animation.ANIMATIONTYPE_VECTOR3:
  33126. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33127. // Vector2
  33128. case Animation.ANIMATIONTYPE_VECTOR2:
  33129. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33130. // Size
  33131. case Animation.ANIMATIONTYPE_SIZE:
  33132. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33133. // Color3
  33134. case Animation.ANIMATIONTYPE_COLOR3:
  33135. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33136. default:
  33137. break;
  33138. }
  33139. this._highLimitsCache[keyOffset] = toValue;
  33140. }
  33141. highLimitValue = this._highLimitsCache[keyOffset];
  33142. offsetValue = this._offsetsCache[keyOffset];
  33143. }
  33144. }
  33145. if (offsetValue === undefined) {
  33146. switch (this.dataType) {
  33147. // Float
  33148. case Animation.ANIMATIONTYPE_FLOAT:
  33149. offsetValue = 0;
  33150. break;
  33151. // Quaternion
  33152. case Animation.ANIMATIONTYPE_QUATERNION:
  33153. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  33154. break;
  33155. // Vector3
  33156. case Animation.ANIMATIONTYPE_VECTOR3:
  33157. offsetValue = BABYLON.Vector3.Zero();
  33158. break;
  33159. // Vector2
  33160. case Animation.ANIMATIONTYPE_VECTOR2:
  33161. offsetValue = BABYLON.Vector2.Zero();
  33162. break;
  33163. // Size
  33164. case Animation.ANIMATIONTYPE_SIZE:
  33165. offsetValue = BABYLON.Size.Zero();
  33166. break;
  33167. // Color3
  33168. case Animation.ANIMATIONTYPE_COLOR3:
  33169. offsetValue = BABYLON.Color3.Black();
  33170. }
  33171. }
  33172. // Compute value
  33173. var repeatCount = (ratio / range) >> 0;
  33174. var currentFrame = returnValue ? from + ratio % range : to;
  33175. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  33176. // Set value
  33177. this.setValue(currentValue);
  33178. // Check events
  33179. for (var index = 0; index < this._events.length; index++) {
  33180. if (currentFrame >= this._events[index].frame) {
  33181. var event = this._events[index];
  33182. if (!event.isDone) {
  33183. // If event should be done only once, remove it.
  33184. if (event.onlyOnce) {
  33185. this._events.splice(index, 1);
  33186. index--;
  33187. }
  33188. event.isDone = true;
  33189. event.action();
  33190. } // Don't do anything if the event has already be done.
  33191. }
  33192. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  33193. // reset event, the animation is looping
  33194. this._events[index].isDone = false;
  33195. }
  33196. }
  33197. if (!returnValue) {
  33198. this._stopped = true;
  33199. }
  33200. return returnValue;
  33201. };
  33202. Animation.prototype.serialize = function () {
  33203. var serializationObject = {};
  33204. serializationObject.name = this.name;
  33205. serializationObject.property = this.targetProperty;
  33206. serializationObject.framePerSecond = this.framePerSecond;
  33207. serializationObject.dataType = this.dataType;
  33208. serializationObject.loopBehavior = this.loopMode;
  33209. serializationObject.enableBlending = this.enableBlending;
  33210. serializationObject.blendingSpeed = this.blendingSpeed;
  33211. var dataType = this.dataType;
  33212. serializationObject.keys = [];
  33213. var keys = this.getKeys();
  33214. for (var index = 0; index < keys.length; index++) {
  33215. var animationKey = keys[index];
  33216. var key = {};
  33217. key.frame = animationKey.frame;
  33218. switch (dataType) {
  33219. case Animation.ANIMATIONTYPE_FLOAT:
  33220. key.values = [animationKey.value];
  33221. break;
  33222. case Animation.ANIMATIONTYPE_QUATERNION:
  33223. case Animation.ANIMATIONTYPE_MATRIX:
  33224. case Animation.ANIMATIONTYPE_VECTOR3:
  33225. case Animation.ANIMATIONTYPE_COLOR3:
  33226. key.values = animationKey.value.asArray();
  33227. break;
  33228. }
  33229. serializationObject.keys.push(key);
  33230. }
  33231. serializationObject.ranges = [];
  33232. for (var name in this._ranges) {
  33233. var range = {};
  33234. range.name = name;
  33235. range.from = this._ranges[name].from;
  33236. range.to = this._ranges[name].to;
  33237. serializationObject.ranges.push(range);
  33238. }
  33239. return serializationObject;
  33240. };
  33241. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  33242. get: function () {
  33243. return Animation._ANIMATIONTYPE_FLOAT;
  33244. },
  33245. enumerable: true,
  33246. configurable: true
  33247. });
  33248. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  33249. get: function () {
  33250. return Animation._ANIMATIONTYPE_VECTOR3;
  33251. },
  33252. enumerable: true,
  33253. configurable: true
  33254. });
  33255. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  33256. get: function () {
  33257. return Animation._ANIMATIONTYPE_VECTOR2;
  33258. },
  33259. enumerable: true,
  33260. configurable: true
  33261. });
  33262. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  33263. get: function () {
  33264. return Animation._ANIMATIONTYPE_SIZE;
  33265. },
  33266. enumerable: true,
  33267. configurable: true
  33268. });
  33269. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  33270. get: function () {
  33271. return Animation._ANIMATIONTYPE_QUATERNION;
  33272. },
  33273. enumerable: true,
  33274. configurable: true
  33275. });
  33276. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  33277. get: function () {
  33278. return Animation._ANIMATIONTYPE_MATRIX;
  33279. },
  33280. enumerable: true,
  33281. configurable: true
  33282. });
  33283. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  33284. get: function () {
  33285. return Animation._ANIMATIONTYPE_COLOR3;
  33286. },
  33287. enumerable: true,
  33288. configurable: true
  33289. });
  33290. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  33291. get: function () {
  33292. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  33293. },
  33294. enumerable: true,
  33295. configurable: true
  33296. });
  33297. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  33298. get: function () {
  33299. return Animation._ANIMATIONLOOPMODE_CYCLE;
  33300. },
  33301. enumerable: true,
  33302. configurable: true
  33303. });
  33304. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  33305. get: function () {
  33306. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  33307. },
  33308. enumerable: true,
  33309. configurable: true
  33310. });
  33311. Animation.Parse = function (parsedAnimation) {
  33312. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  33313. var dataType = parsedAnimation.dataType;
  33314. var keys = [];
  33315. var data;
  33316. var index;
  33317. if (parsedAnimation.enableBlending) {
  33318. animation.enableBlending = parsedAnimation.enableBlending;
  33319. }
  33320. if (parsedAnimation.blendingSpeed) {
  33321. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  33322. }
  33323. for (index = 0; index < parsedAnimation.keys.length; index++) {
  33324. var key = parsedAnimation.keys[index];
  33325. switch (dataType) {
  33326. case Animation.ANIMATIONTYPE_FLOAT:
  33327. data = key.values[0];
  33328. break;
  33329. case Animation.ANIMATIONTYPE_QUATERNION:
  33330. data = BABYLON.Quaternion.FromArray(key.values);
  33331. break;
  33332. case Animation.ANIMATIONTYPE_MATRIX:
  33333. data = BABYLON.Matrix.FromArray(key.values);
  33334. break;
  33335. case Animation.ANIMATIONTYPE_COLOR3:
  33336. data = BABYLON.Color3.FromArray(key.values);
  33337. break;
  33338. case Animation.ANIMATIONTYPE_VECTOR3:
  33339. default:
  33340. data = BABYLON.Vector3.FromArray(key.values);
  33341. break;
  33342. }
  33343. keys.push({
  33344. frame: key.frame,
  33345. value: data
  33346. });
  33347. }
  33348. animation.setKeys(keys);
  33349. if (parsedAnimation.ranges) {
  33350. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  33351. data = parsedAnimation.ranges[index];
  33352. animation.createRange(data.name, data.from, data.to);
  33353. }
  33354. }
  33355. return animation;
  33356. };
  33357. Animation.AppendSerializedAnimations = function (source, destination) {
  33358. if (source.animations) {
  33359. destination.animations = [];
  33360. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  33361. var animation = source.animations[animationIndex];
  33362. destination.animations.push(animation.serialize());
  33363. }
  33364. }
  33365. };
  33366. return Animation;
  33367. }());
  33368. // Statics
  33369. Animation._ANIMATIONTYPE_FLOAT = 0;
  33370. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  33371. Animation._ANIMATIONTYPE_QUATERNION = 2;
  33372. Animation._ANIMATIONTYPE_MATRIX = 3;
  33373. Animation._ANIMATIONTYPE_COLOR3 = 4;
  33374. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  33375. Animation._ANIMATIONTYPE_SIZE = 6;
  33376. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  33377. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  33378. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  33379. BABYLON.Animation = Animation;
  33380. })(BABYLON || (BABYLON = {}));
  33381. //# sourceMappingURL=babylon.animation.js.map
  33382. var BABYLON;
  33383. (function (BABYLON) {
  33384. var Animatable = (function () {
  33385. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  33386. if (fromFrame === void 0) { fromFrame = 0; }
  33387. if (toFrame === void 0) { toFrame = 100; }
  33388. if (loopAnimation === void 0) { loopAnimation = false; }
  33389. if (speedRatio === void 0) { speedRatio = 1.0; }
  33390. this.target = target;
  33391. this.fromFrame = fromFrame;
  33392. this.toFrame = toFrame;
  33393. this.loopAnimation = loopAnimation;
  33394. this.speedRatio = speedRatio;
  33395. this.onAnimationEnd = onAnimationEnd;
  33396. this._animations = new Array();
  33397. this._paused = false;
  33398. this.animationStarted = false;
  33399. if (animations) {
  33400. this.appendAnimations(target, animations);
  33401. }
  33402. this._scene = scene;
  33403. scene._activeAnimatables.push(this);
  33404. }
  33405. // Methods
  33406. Animatable.prototype.getAnimations = function () {
  33407. return this._animations;
  33408. };
  33409. Animatable.prototype.appendAnimations = function (target, animations) {
  33410. for (var index = 0; index < animations.length; index++) {
  33411. var animation = animations[index];
  33412. animation._target = target;
  33413. this._animations.push(animation);
  33414. }
  33415. };
  33416. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  33417. var animations = this._animations;
  33418. for (var index = 0; index < animations.length; index++) {
  33419. if (animations[index].targetProperty === property) {
  33420. return animations[index];
  33421. }
  33422. }
  33423. return null;
  33424. };
  33425. Animatable.prototype.reset = function () {
  33426. var animations = this._animations;
  33427. for (var index = 0; index < animations.length; index++) {
  33428. animations[index].reset();
  33429. }
  33430. this._localDelayOffset = null;
  33431. this._pausedDelay = null;
  33432. };
  33433. Animatable.prototype.enableBlending = function (blendingSpeed) {
  33434. var animations = this._animations;
  33435. for (var index = 0; index < animations.length; index++) {
  33436. animations[index].enableBlending = true;
  33437. animations[index].blendingSpeed = blendingSpeed;
  33438. }
  33439. };
  33440. Animatable.prototype.disableBlending = function () {
  33441. var animations = this._animations;
  33442. for (var index = 0; index < animations.length; index++) {
  33443. animations[index].enableBlending = false;
  33444. }
  33445. };
  33446. Animatable.prototype.goToFrame = function (frame) {
  33447. var animations = this._animations;
  33448. if (animations[0]) {
  33449. var fps = animations[0].framePerSecond;
  33450. var currentFrame = animations[0].currentFrame;
  33451. var adjustTime = frame - currentFrame;
  33452. var delay = adjustTime * 1000 / fps;
  33453. this._localDelayOffset -= delay;
  33454. }
  33455. for (var index = 0; index < animations.length; index++) {
  33456. animations[index].goToFrame(frame);
  33457. }
  33458. };
  33459. Animatable.prototype.pause = function () {
  33460. if (this._paused) {
  33461. return;
  33462. }
  33463. this._paused = true;
  33464. };
  33465. Animatable.prototype.restart = function () {
  33466. this._paused = false;
  33467. };
  33468. Animatable.prototype.stop = function (animationName) {
  33469. if (animationName) {
  33470. var idx = this._scene._activeAnimatables.indexOf(this);
  33471. if (idx > -1) {
  33472. var animations = this._animations;
  33473. for (var index = animations.length - 1; index >= 0; index--) {
  33474. if (typeof animationName === "string" && animations[index].name != animationName) {
  33475. continue;
  33476. }
  33477. animations[index].reset();
  33478. animations.splice(index, 1);
  33479. }
  33480. if (animations.length == 0) {
  33481. this._scene._activeAnimatables.splice(idx, 1);
  33482. if (this.onAnimationEnd) {
  33483. this.onAnimationEnd();
  33484. }
  33485. }
  33486. }
  33487. }
  33488. else {
  33489. var index = this._scene._activeAnimatables.indexOf(this);
  33490. if (index > -1) {
  33491. this._scene._activeAnimatables.splice(index, 1);
  33492. var animations = this._animations;
  33493. for (var index = 0; index < animations.length; index++) {
  33494. animations[index].reset();
  33495. }
  33496. if (this.onAnimationEnd) {
  33497. this.onAnimationEnd();
  33498. }
  33499. }
  33500. }
  33501. };
  33502. Animatable.prototype._animate = function (delay) {
  33503. if (this._paused) {
  33504. this.animationStarted = false;
  33505. if (!this._pausedDelay) {
  33506. this._pausedDelay = delay;
  33507. }
  33508. return true;
  33509. }
  33510. if (!this._localDelayOffset) {
  33511. this._localDelayOffset = delay;
  33512. }
  33513. else if (this._pausedDelay) {
  33514. this._localDelayOffset += delay - this._pausedDelay;
  33515. this._pausedDelay = null;
  33516. }
  33517. // Animating
  33518. var running = false;
  33519. var animations = this._animations;
  33520. var index;
  33521. for (index = 0; index < animations.length; index++) {
  33522. var animation = animations[index];
  33523. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  33524. running = running || isRunning;
  33525. }
  33526. this.animationStarted = running;
  33527. if (!running) {
  33528. // Remove from active animatables
  33529. index = this._scene._activeAnimatables.indexOf(this);
  33530. this._scene._activeAnimatables.splice(index, 1);
  33531. }
  33532. if (!running && this.onAnimationEnd) {
  33533. this.onAnimationEnd();
  33534. this.onAnimationEnd = null;
  33535. }
  33536. return running;
  33537. };
  33538. return Animatable;
  33539. }());
  33540. BABYLON.Animatable = Animatable;
  33541. })(BABYLON || (BABYLON = {}));
  33542. //# sourceMappingURL=babylon.animatable.js.map
  33543. var BABYLON;
  33544. (function (BABYLON) {
  33545. var EasingFunction = (function () {
  33546. function EasingFunction() {
  33547. // Properties
  33548. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  33549. }
  33550. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  33551. get: function () {
  33552. return EasingFunction._EASINGMODE_EASEIN;
  33553. },
  33554. enumerable: true,
  33555. configurable: true
  33556. });
  33557. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  33558. get: function () {
  33559. return EasingFunction._EASINGMODE_EASEOUT;
  33560. },
  33561. enumerable: true,
  33562. configurable: true
  33563. });
  33564. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  33565. get: function () {
  33566. return EasingFunction._EASINGMODE_EASEINOUT;
  33567. },
  33568. enumerable: true,
  33569. configurable: true
  33570. });
  33571. EasingFunction.prototype.setEasingMode = function (easingMode) {
  33572. var n = Math.min(Math.max(easingMode, 0), 2);
  33573. this._easingMode = n;
  33574. };
  33575. EasingFunction.prototype.getEasingMode = function () {
  33576. return this._easingMode;
  33577. };
  33578. EasingFunction.prototype.easeInCore = function (gradient) {
  33579. throw new Error('You must implement this method');
  33580. };
  33581. EasingFunction.prototype.ease = function (gradient) {
  33582. switch (this._easingMode) {
  33583. case EasingFunction.EASINGMODE_EASEIN:
  33584. return this.easeInCore(gradient);
  33585. case EasingFunction.EASINGMODE_EASEOUT:
  33586. return (1 - this.easeInCore(1 - gradient));
  33587. }
  33588. if (gradient >= 0.5) {
  33589. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  33590. }
  33591. return (this.easeInCore(gradient * 2) * 0.5);
  33592. };
  33593. return EasingFunction;
  33594. }());
  33595. //Statics
  33596. EasingFunction._EASINGMODE_EASEIN = 0;
  33597. EasingFunction._EASINGMODE_EASEOUT = 1;
  33598. EasingFunction._EASINGMODE_EASEINOUT = 2;
  33599. BABYLON.EasingFunction = EasingFunction;
  33600. var CircleEase = (function (_super) {
  33601. __extends(CircleEase, _super);
  33602. function CircleEase() {
  33603. return _super !== null && _super.apply(this, arguments) || this;
  33604. }
  33605. CircleEase.prototype.easeInCore = function (gradient) {
  33606. gradient = Math.max(0, Math.min(1, gradient));
  33607. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  33608. };
  33609. return CircleEase;
  33610. }(EasingFunction));
  33611. BABYLON.CircleEase = CircleEase;
  33612. var BackEase = (function (_super) {
  33613. __extends(BackEase, _super);
  33614. function BackEase(amplitude) {
  33615. if (amplitude === void 0) { amplitude = 1; }
  33616. var _this = _super.call(this) || this;
  33617. _this.amplitude = amplitude;
  33618. return _this;
  33619. }
  33620. BackEase.prototype.easeInCore = function (gradient) {
  33621. var num = Math.max(0, this.amplitude);
  33622. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  33623. };
  33624. return BackEase;
  33625. }(EasingFunction));
  33626. BABYLON.BackEase = BackEase;
  33627. var BounceEase = (function (_super) {
  33628. __extends(BounceEase, _super);
  33629. function BounceEase(bounces, bounciness) {
  33630. if (bounces === void 0) { bounces = 3; }
  33631. if (bounciness === void 0) { bounciness = 2; }
  33632. var _this = _super.call(this) || this;
  33633. _this.bounces = bounces;
  33634. _this.bounciness = bounciness;
  33635. return _this;
  33636. }
  33637. BounceEase.prototype.easeInCore = function (gradient) {
  33638. var y = Math.max(0.0, this.bounces);
  33639. var bounciness = this.bounciness;
  33640. if (bounciness <= 1.0) {
  33641. bounciness = 1.001;
  33642. }
  33643. var num9 = Math.pow(bounciness, y);
  33644. var num5 = 1.0 - bounciness;
  33645. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  33646. var num15 = gradient * num4;
  33647. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  33648. var num3 = Math.floor(num65);
  33649. var num13 = num3 + 1.0;
  33650. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  33651. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  33652. var num7 = (num8 + num12) * 0.5;
  33653. var num6 = gradient - num7;
  33654. var num2 = num7 - num8;
  33655. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  33656. };
  33657. return BounceEase;
  33658. }(EasingFunction));
  33659. BABYLON.BounceEase = BounceEase;
  33660. var CubicEase = (function (_super) {
  33661. __extends(CubicEase, _super);
  33662. function CubicEase() {
  33663. return _super !== null && _super.apply(this, arguments) || this;
  33664. }
  33665. CubicEase.prototype.easeInCore = function (gradient) {
  33666. return (gradient * gradient * gradient);
  33667. };
  33668. return CubicEase;
  33669. }(EasingFunction));
  33670. BABYLON.CubicEase = CubicEase;
  33671. var ElasticEase = (function (_super) {
  33672. __extends(ElasticEase, _super);
  33673. function ElasticEase(oscillations, springiness) {
  33674. if (oscillations === void 0) { oscillations = 3; }
  33675. if (springiness === void 0) { springiness = 3; }
  33676. var _this = _super.call(this) || this;
  33677. _this.oscillations = oscillations;
  33678. _this.springiness = springiness;
  33679. return _this;
  33680. }
  33681. ElasticEase.prototype.easeInCore = function (gradient) {
  33682. var num2;
  33683. var num3 = Math.max(0.0, this.oscillations);
  33684. var num = Math.max(0.0, this.springiness);
  33685. if (num == 0) {
  33686. num2 = gradient;
  33687. }
  33688. else {
  33689. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  33690. }
  33691. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  33692. };
  33693. return ElasticEase;
  33694. }(EasingFunction));
  33695. BABYLON.ElasticEase = ElasticEase;
  33696. var ExponentialEase = (function (_super) {
  33697. __extends(ExponentialEase, _super);
  33698. function ExponentialEase(exponent) {
  33699. if (exponent === void 0) { exponent = 2; }
  33700. var _this = _super.call(this) || this;
  33701. _this.exponent = exponent;
  33702. return _this;
  33703. }
  33704. ExponentialEase.prototype.easeInCore = function (gradient) {
  33705. if (this.exponent <= 0) {
  33706. return gradient;
  33707. }
  33708. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  33709. };
  33710. return ExponentialEase;
  33711. }(EasingFunction));
  33712. BABYLON.ExponentialEase = ExponentialEase;
  33713. var PowerEase = (function (_super) {
  33714. __extends(PowerEase, _super);
  33715. function PowerEase(power) {
  33716. if (power === void 0) { power = 2; }
  33717. var _this = _super.call(this) || this;
  33718. _this.power = power;
  33719. return _this;
  33720. }
  33721. PowerEase.prototype.easeInCore = function (gradient) {
  33722. var y = Math.max(0.0, this.power);
  33723. return Math.pow(gradient, y);
  33724. };
  33725. return PowerEase;
  33726. }(EasingFunction));
  33727. BABYLON.PowerEase = PowerEase;
  33728. var QuadraticEase = (function (_super) {
  33729. __extends(QuadraticEase, _super);
  33730. function QuadraticEase() {
  33731. return _super !== null && _super.apply(this, arguments) || this;
  33732. }
  33733. QuadraticEase.prototype.easeInCore = function (gradient) {
  33734. return (gradient * gradient);
  33735. };
  33736. return QuadraticEase;
  33737. }(EasingFunction));
  33738. BABYLON.QuadraticEase = QuadraticEase;
  33739. var QuarticEase = (function (_super) {
  33740. __extends(QuarticEase, _super);
  33741. function QuarticEase() {
  33742. return _super !== null && _super.apply(this, arguments) || this;
  33743. }
  33744. QuarticEase.prototype.easeInCore = function (gradient) {
  33745. return (gradient * gradient * gradient * gradient);
  33746. };
  33747. return QuarticEase;
  33748. }(EasingFunction));
  33749. BABYLON.QuarticEase = QuarticEase;
  33750. var QuinticEase = (function (_super) {
  33751. __extends(QuinticEase, _super);
  33752. function QuinticEase() {
  33753. return _super !== null && _super.apply(this, arguments) || this;
  33754. }
  33755. QuinticEase.prototype.easeInCore = function (gradient) {
  33756. return (gradient * gradient * gradient * gradient * gradient);
  33757. };
  33758. return QuinticEase;
  33759. }(EasingFunction));
  33760. BABYLON.QuinticEase = QuinticEase;
  33761. var SineEase = (function (_super) {
  33762. __extends(SineEase, _super);
  33763. function SineEase() {
  33764. return _super !== null && _super.apply(this, arguments) || this;
  33765. }
  33766. SineEase.prototype.easeInCore = function (gradient) {
  33767. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33768. };
  33769. return SineEase;
  33770. }(EasingFunction));
  33771. BABYLON.SineEase = SineEase;
  33772. var BezierCurveEase = (function (_super) {
  33773. __extends(BezierCurveEase, _super);
  33774. function BezierCurveEase(x1, y1, x2, y2) {
  33775. if (x1 === void 0) { x1 = 0; }
  33776. if (y1 === void 0) { y1 = 0; }
  33777. if (x2 === void 0) { x2 = 1; }
  33778. if (y2 === void 0) { y2 = 1; }
  33779. var _this = _super.call(this) || this;
  33780. _this.x1 = x1;
  33781. _this.y1 = y1;
  33782. _this.x2 = x2;
  33783. _this.y2 = y2;
  33784. return _this;
  33785. }
  33786. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33787. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33788. };
  33789. return BezierCurveEase;
  33790. }(EasingFunction));
  33791. BABYLON.BezierCurveEase = BezierCurveEase;
  33792. })(BABYLON || (BABYLON = {}));
  33793. //# sourceMappingURL=babylon.easing.js.map
  33794. /// <reference path="..\babylon.node.ts" />
  33795. var BABYLON;
  33796. (function (BABYLON) {
  33797. var Bone = (function (_super) {
  33798. __extends(Bone, _super);
  33799. function Bone(name, skeleton, parentBone, matrix, restPose) {
  33800. var _this = _super.call(this, name, skeleton.getScene()) || this;
  33801. _this.name = name;
  33802. _this.children = new Array();
  33803. _this.animations = new Array();
  33804. _this._worldTransform = new BABYLON.Matrix();
  33805. _this._absoluteTransform = new BABYLON.Matrix();
  33806. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  33807. _this._scaleMatrix = BABYLON.Matrix.Identity();
  33808. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  33809. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  33810. _this._scalingDeterminant = 1;
  33811. _this._skeleton = skeleton;
  33812. _this._localMatrix = matrix;
  33813. _this._baseMatrix = matrix.clone();
  33814. _this._restPose = restPose ? restPose : matrix.clone();
  33815. skeleton.bones.push(_this);
  33816. if (parentBone) {
  33817. _this._parent = parentBone;
  33818. parentBone.children.push(_this);
  33819. }
  33820. else {
  33821. _this._parent = null;
  33822. }
  33823. _this._updateDifferenceMatrix();
  33824. if (_this.getAbsoluteTransform().determinant() < 0) {
  33825. _this._scalingDeterminant *= -1;
  33826. }
  33827. return _this;
  33828. }
  33829. Object.defineProperty(Bone.prototype, "_matrix", {
  33830. get: function () {
  33831. return this._localMatrix;
  33832. },
  33833. set: function (val) {
  33834. if (this._localMatrix) {
  33835. this._localMatrix.copyFrom(val);
  33836. }
  33837. else {
  33838. this._localMatrix = val;
  33839. }
  33840. },
  33841. enumerable: true,
  33842. configurable: true
  33843. });
  33844. // Members
  33845. Bone.prototype.getParent = function () {
  33846. return this._parent;
  33847. };
  33848. Bone.prototype.getLocalMatrix = function () {
  33849. return this._localMatrix;
  33850. };
  33851. Bone.prototype.getBaseMatrix = function () {
  33852. return this._baseMatrix;
  33853. };
  33854. Bone.prototype.getRestPose = function () {
  33855. return this._restPose;
  33856. };
  33857. Bone.prototype.returnToRest = function () {
  33858. this.updateMatrix(this._restPose.clone());
  33859. };
  33860. Bone.prototype.getWorldMatrix = function () {
  33861. return this._worldTransform;
  33862. };
  33863. Bone.prototype.getInvertedAbsoluteTransform = function () {
  33864. return this._invertedAbsoluteTransform;
  33865. };
  33866. Bone.prototype.getAbsoluteTransform = function () {
  33867. return this._absoluteTransform;
  33868. };
  33869. // Methods
  33870. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  33871. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  33872. this._baseMatrix = matrix.clone();
  33873. this._localMatrix = matrix.clone();
  33874. this._skeleton._markAsDirty();
  33875. if (updateDifferenceMatrix) {
  33876. this._updateDifferenceMatrix();
  33877. }
  33878. };
  33879. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  33880. if (!rootMatrix) {
  33881. rootMatrix = this._baseMatrix;
  33882. }
  33883. if (this._parent) {
  33884. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  33885. }
  33886. else {
  33887. this._absoluteTransform.copyFrom(rootMatrix);
  33888. }
  33889. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  33890. for (var index = 0; index < this.children.length; index++) {
  33891. this.children[index]._updateDifferenceMatrix();
  33892. }
  33893. };
  33894. Bone.prototype.markAsDirty = function () {
  33895. this._currentRenderId++;
  33896. this._skeleton._markAsDirty();
  33897. };
  33898. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  33899. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  33900. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  33901. // all animation may be coming from a library skeleton, so may need to create animation
  33902. if (this.animations.length === 0) {
  33903. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  33904. this.animations[0].setKeys([]);
  33905. }
  33906. // get animation info / verify there is such a range from the source bone
  33907. var sourceRange = source.animations[0].getRange(rangeName);
  33908. if (!sourceRange) {
  33909. return false;
  33910. }
  33911. var from = sourceRange.from;
  33912. var to = sourceRange.to;
  33913. var sourceKeys = source.animations[0].getKeys();
  33914. // rescaling prep
  33915. var sourceBoneLength = source.length;
  33916. var sourceParent = source.getParent();
  33917. var parent = this.getParent();
  33918. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  33919. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  33920. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  33921. var destKeys = this.animations[0].getKeys();
  33922. // loop vars declaration
  33923. var orig;
  33924. var origTranslation;
  33925. var mat;
  33926. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  33927. orig = sourceKeys[key];
  33928. if (orig.frame >= from && orig.frame <= to) {
  33929. if (rescaleAsRequired) {
  33930. mat = orig.value.clone();
  33931. // scale based on parent ratio, when bone has parent
  33932. if (parentScalingReqd) {
  33933. origTranslation = mat.getTranslation();
  33934. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  33935. }
  33936. else if (dimensionsScalingReqd) {
  33937. origTranslation = mat.getTranslation();
  33938. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  33939. }
  33940. else {
  33941. mat = orig.value;
  33942. }
  33943. }
  33944. else {
  33945. mat = orig.value;
  33946. }
  33947. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  33948. }
  33949. }
  33950. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  33951. return true;
  33952. };
  33953. /**
  33954. * Translate the bone in local or world space.
  33955. * @param vec The amount to translate the bone.
  33956. * @param space The space that the translation is in.
  33957. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33958. */
  33959. Bone.prototype.translate = function (vec, space, mesh) {
  33960. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33961. var lm = this.getLocalMatrix();
  33962. if (space == BABYLON.Space.LOCAL) {
  33963. lm.m[12] += vec.x;
  33964. lm.m[13] += vec.y;
  33965. lm.m[14] += vec.z;
  33966. }
  33967. else {
  33968. var wm;
  33969. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  33970. if (mesh) {
  33971. wm = mesh.getWorldMatrix();
  33972. }
  33973. this._skeleton.computeAbsoluteTransforms();
  33974. var tmat = BABYLON.Tmp.Matrix[0];
  33975. var tvec = BABYLON.Tmp.Vector3[0];
  33976. if (mesh) {
  33977. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33978. tmat.multiplyToRef(wm, tmat);
  33979. }
  33980. else {
  33981. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33982. }
  33983. tmat.m[12] = 0;
  33984. tmat.m[13] = 0;
  33985. tmat.m[14] = 0;
  33986. tmat.invert();
  33987. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  33988. lm.m[12] += tvec.x;
  33989. lm.m[13] += tvec.y;
  33990. lm.m[14] += tvec.z;
  33991. }
  33992. this.markAsDirty();
  33993. };
  33994. /**
  33995. * Set the postion of the bone in local or world space.
  33996. * @param position The position to set the bone.
  33997. * @param space The space that the position is in.
  33998. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33999. */
  34000. Bone.prototype.setPosition = function (position, space, mesh) {
  34001. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34002. var lm = this.getLocalMatrix();
  34003. if (space == BABYLON.Space.LOCAL) {
  34004. lm.m[12] = position.x;
  34005. lm.m[13] = position.y;
  34006. lm.m[14] = position.z;
  34007. }
  34008. else {
  34009. var wm;
  34010. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34011. if (mesh) {
  34012. wm = mesh.getWorldMatrix();
  34013. }
  34014. this._skeleton.computeAbsoluteTransforms();
  34015. var tmat = BABYLON.Tmp.Matrix[0];
  34016. var vec = BABYLON.Tmp.Vector3[0];
  34017. if (mesh) {
  34018. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34019. tmat.multiplyToRef(wm, tmat);
  34020. }
  34021. else {
  34022. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34023. }
  34024. tmat.invert();
  34025. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  34026. lm.m[12] = vec.x;
  34027. lm.m[13] = vec.y;
  34028. lm.m[14] = vec.z;
  34029. }
  34030. this.markAsDirty();
  34031. };
  34032. /**
  34033. * Set the absolute postion of the bone (world space).
  34034. * @param position The position to set the bone.
  34035. * @param mesh The mesh that this bone is attached to.
  34036. */
  34037. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  34038. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  34039. };
  34040. /**
  34041. * Set the scale of the bone on the x, y and z axes.
  34042. * @param x The scale of the bone on the x axis.
  34043. * @param x The scale of the bone on the y axis.
  34044. * @param z The scale of the bone on the z axis.
  34045. * @param scaleChildren Set this to true if children of the bone should be scaled.
  34046. */
  34047. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  34048. if (scaleChildren === void 0) { scaleChildren = false; }
  34049. if (this.animations[0] && !this.animations[0].isStopped()) {
  34050. if (!scaleChildren) {
  34051. this._negateScaleChildren.x = 1 / x;
  34052. this._negateScaleChildren.y = 1 / y;
  34053. this._negateScaleChildren.z = 1 / z;
  34054. }
  34055. this._syncScaleVector();
  34056. }
  34057. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  34058. };
  34059. /**
  34060. * Scale the bone on the x, y and z axes.
  34061. * @param x The amount to scale the bone on the x axis.
  34062. * @param x The amount to scale the bone on the y axis.
  34063. * @param z The amount to scale the bone on the z axis.
  34064. * @param scaleChildren Set this to true if children of the bone should be scaled.
  34065. */
  34066. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  34067. if (scaleChildren === void 0) { scaleChildren = false; }
  34068. var locMat = this.getLocalMatrix();
  34069. var origLocMat = BABYLON.Tmp.Matrix[0];
  34070. origLocMat.copyFrom(locMat);
  34071. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  34072. origLocMatInv.copyFrom(origLocMat);
  34073. origLocMatInv.invert();
  34074. var scaleMat = BABYLON.Tmp.Matrix[2];
  34075. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  34076. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  34077. this._scaleVector.x *= x;
  34078. this._scaleVector.y *= y;
  34079. this._scaleVector.z *= z;
  34080. locMat.multiplyToRef(origLocMatInv, locMat);
  34081. locMat.multiplyToRef(scaleMat, locMat);
  34082. locMat.multiplyToRef(origLocMat, locMat);
  34083. var parent = this.getParent();
  34084. if (parent) {
  34085. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  34086. }
  34087. else {
  34088. this.getAbsoluteTransform().copyFrom(locMat);
  34089. }
  34090. var len = this.children.length;
  34091. scaleMat.invert();
  34092. for (var i = 0; i < len; i++) {
  34093. var child = this.children[i];
  34094. var cm = child.getLocalMatrix();
  34095. cm.multiplyToRef(scaleMat, cm);
  34096. var lm = child.getLocalMatrix();
  34097. lm.m[12] *= x;
  34098. lm.m[13] *= y;
  34099. lm.m[14] *= z;
  34100. }
  34101. this.computeAbsoluteTransforms();
  34102. if (scaleChildren) {
  34103. for (var i = 0; i < len; i++) {
  34104. this.children[i].scale(x, y, z, scaleChildren);
  34105. }
  34106. }
  34107. this.markAsDirty();
  34108. };
  34109. /**
  34110. * Set the yaw, pitch, and roll of the bone in local or world space.
  34111. * @param yaw The rotation of the bone on the y axis.
  34112. * @param pitch The rotation of the bone on the x axis.
  34113. * @param roll The rotation of the bone on the z axis.
  34114. * @param space The space that the axes of rotation are in.
  34115. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34116. */
  34117. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  34118. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34119. var rotMat = BABYLON.Tmp.Matrix[0];
  34120. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  34121. var rotMatInv = BABYLON.Tmp.Matrix[1];
  34122. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34123. rotMatInv.multiplyToRef(rotMat, rotMat);
  34124. this._rotateWithMatrix(rotMat, space, mesh);
  34125. };
  34126. /**
  34127. * Rotate the bone on an axis in local or world space.
  34128. * @param axis The axis to rotate the bone on.
  34129. * @param amount The amount to rotate the bone.
  34130. * @param space The space that the axis is in.
  34131. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34132. */
  34133. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  34134. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34135. var rmat = BABYLON.Tmp.Matrix[0];
  34136. rmat.m[12] = 0;
  34137. rmat.m[13] = 0;
  34138. rmat.m[14] = 0;
  34139. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  34140. this._rotateWithMatrix(rmat, space, mesh);
  34141. };
  34142. /**
  34143. * Set the rotation of the bone to a particular axis angle in local or world space.
  34144. * @param axis The axis to rotate the bone on.
  34145. * @param angle The angle that the bone should be rotated to.
  34146. * @param space The space that the axis is in.
  34147. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34148. */
  34149. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  34150. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34151. var rotMat = BABYLON.Tmp.Matrix[0];
  34152. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  34153. var rotMatInv = BABYLON.Tmp.Matrix[1];
  34154. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34155. rotMatInv.multiplyToRef(rotMat, rotMat);
  34156. this._rotateWithMatrix(rotMat, space, mesh);
  34157. };
  34158. /**
  34159. * Set the euler rotation of the bone in local of world space.
  34160. * @param rotation The euler rotation that the bone should be set to.
  34161. * @param space The space that the rotation is in.
  34162. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34163. */
  34164. Bone.prototype.setRotation = function (rotation, space, mesh) {
  34165. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34166. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  34167. };
  34168. /**
  34169. * Set the quaternion rotation of the bone in local of world space.
  34170. * @param quat The quaternion rotation that the bone should be set to.
  34171. * @param space The space that the rotation is in.
  34172. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34173. */
  34174. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  34175. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34176. var rotMatInv = BABYLON.Tmp.Matrix[0];
  34177. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34178. var rotMat = BABYLON.Tmp.Matrix[1];
  34179. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  34180. rotMatInv.multiplyToRef(rotMat, rotMat);
  34181. this._rotateWithMatrix(rotMat, space, mesh);
  34182. };
  34183. /**
  34184. * Set the rotation matrix of the bone in local of world space.
  34185. * @param rotMat The rotation matrix that the bone should be set to.
  34186. * @param space The space that the rotation is in.
  34187. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34188. */
  34189. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  34190. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34191. var rotMatInv = BABYLON.Tmp.Matrix[0];
  34192. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34193. var rotMat2 = BABYLON.Tmp.Matrix[1];
  34194. rotMat2.copyFrom(rotMat);
  34195. rotMatInv.multiplyToRef(rotMat, rotMat2);
  34196. this._rotateWithMatrix(rotMat2, space, mesh);
  34197. };
  34198. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  34199. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34200. var lmat = this.getLocalMatrix();
  34201. var lx = lmat.m[12];
  34202. var ly = lmat.m[13];
  34203. var lz = lmat.m[14];
  34204. var parent = this.getParent();
  34205. var parentScale = BABYLON.Tmp.Matrix[3];
  34206. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  34207. if (parent) {
  34208. if (space == BABYLON.Space.WORLD) {
  34209. if (mesh) {
  34210. parentScale.copyFrom(mesh.getWorldMatrix());
  34211. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  34212. }
  34213. else {
  34214. parentScale.copyFrom(parent.getAbsoluteTransform());
  34215. }
  34216. }
  34217. else {
  34218. parentScale = parent._scaleMatrix;
  34219. }
  34220. parentScaleInv.copyFrom(parentScale);
  34221. parentScaleInv.invert();
  34222. lmat.multiplyToRef(parentScale, lmat);
  34223. lmat.multiplyToRef(rmat, lmat);
  34224. lmat.multiplyToRef(parentScaleInv, lmat);
  34225. }
  34226. else {
  34227. if (space == BABYLON.Space.WORLD && mesh) {
  34228. parentScale.copyFrom(mesh.getWorldMatrix());
  34229. parentScaleInv.copyFrom(parentScale);
  34230. parentScaleInv.invert();
  34231. lmat.multiplyToRef(parentScale, lmat);
  34232. lmat.multiplyToRef(rmat, lmat);
  34233. lmat.multiplyToRef(parentScaleInv, lmat);
  34234. }
  34235. else {
  34236. lmat.multiplyToRef(rmat, lmat);
  34237. }
  34238. }
  34239. lmat.m[12] = lx;
  34240. lmat.m[13] = ly;
  34241. lmat.m[14] = lz;
  34242. this.computeAbsoluteTransforms();
  34243. this.markAsDirty();
  34244. };
  34245. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  34246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34247. if (space == BABYLON.Space.WORLD) {
  34248. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  34249. scaleMatrix.copyFrom(this._scaleMatrix);
  34250. rotMatInv.copyFrom(this.getAbsoluteTransform());
  34251. if (mesh) {
  34252. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  34253. var meshScale = BABYLON.Tmp.Matrix[3];
  34254. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  34255. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  34256. }
  34257. rotMatInv.invert();
  34258. scaleMatrix.m[0] *= this._scalingDeterminant;
  34259. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  34260. }
  34261. else {
  34262. rotMatInv.copyFrom(this.getLocalMatrix());
  34263. rotMatInv.invert();
  34264. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  34265. scaleMatrix.copyFrom(this._scaleMatrix);
  34266. if (this._parent) {
  34267. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  34268. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  34269. pscaleMatrix.invert();
  34270. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  34271. }
  34272. else {
  34273. scaleMatrix.m[0] *= this._scalingDeterminant;
  34274. }
  34275. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  34276. }
  34277. };
  34278. /**
  34279. * Get the scale of the bone
  34280. * @returns the scale of the bone
  34281. */
  34282. Bone.prototype.getScale = function () {
  34283. return this._scaleVector.clone();
  34284. };
  34285. /**
  34286. * Copy the scale of the bone to a vector3.
  34287. * @param result The vector3 to copy the scale to
  34288. */
  34289. Bone.prototype.getScaleToRef = function (result) {
  34290. result.copyFrom(this._scaleVector);
  34291. };
  34292. /**
  34293. * Get the position of the bone in local or world space.
  34294. * @param space The space that the returned position is in.
  34295. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34296. * @returns The position of the bone
  34297. */
  34298. Bone.prototype.getPosition = function (space, mesh) {
  34299. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34300. var pos = BABYLON.Vector3.Zero();
  34301. this.getPositionToRef(space, mesh, pos);
  34302. return pos;
  34303. };
  34304. /**
  34305. * Copy the position of the bone to a vector3 in local or world space.
  34306. * @param space The space that the returned position is in.
  34307. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34308. * @param result The vector3 to copy the position to.
  34309. */
  34310. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  34311. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34312. if (space == BABYLON.Space.LOCAL) {
  34313. var lm = this.getLocalMatrix();
  34314. result.x = lm.m[12];
  34315. result.y = lm.m[13];
  34316. result.z = lm.m[14];
  34317. }
  34318. else {
  34319. var wm;
  34320. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34321. if (mesh) {
  34322. wm = mesh.getWorldMatrix();
  34323. }
  34324. this._skeleton.computeAbsoluteTransforms();
  34325. var tmat = BABYLON.Tmp.Matrix[0];
  34326. if (mesh) {
  34327. tmat.copyFrom(this.getAbsoluteTransform());
  34328. tmat.multiplyToRef(wm, tmat);
  34329. }
  34330. else {
  34331. tmat = this.getAbsoluteTransform();
  34332. }
  34333. result.x = tmat.m[12];
  34334. result.y = tmat.m[13];
  34335. result.z = tmat.m[14];
  34336. }
  34337. };
  34338. /**
  34339. * Get the absolute position of the bone (world space).
  34340. * @param mesh The mesh that this bone is attached to.
  34341. * @returns The absolute position of the bone
  34342. */
  34343. Bone.prototype.getAbsolutePosition = function (mesh) {
  34344. var pos = BABYLON.Vector3.Zero();
  34345. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  34346. return pos;
  34347. };
  34348. /**
  34349. * Copy the absolute position of the bone (world space) to the result param.
  34350. * @param mesh The mesh that this bone is attached to.
  34351. * @param result The vector3 to copy the absolute position to.
  34352. */
  34353. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  34354. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  34355. };
  34356. /**
  34357. * Compute the absolute transforms of this bone and its children.
  34358. */
  34359. Bone.prototype.computeAbsoluteTransforms = function () {
  34360. if (this._parent) {
  34361. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  34362. }
  34363. else {
  34364. this._absoluteTransform.copyFrom(this._localMatrix);
  34365. var poseMatrix = this._skeleton.getPoseMatrix();
  34366. if (poseMatrix) {
  34367. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  34368. }
  34369. }
  34370. var children = this.children;
  34371. var len = children.length;
  34372. for (var i = 0; i < len; i++) {
  34373. children[i].computeAbsoluteTransforms();
  34374. }
  34375. };
  34376. Bone.prototype._syncScaleVector = function () {
  34377. var lm = this.getLocalMatrix();
  34378. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  34379. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  34380. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  34381. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  34382. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  34383. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  34384. this._scaleVector.x = xs * Math.sqrt(xsq);
  34385. this._scaleVector.y = ys * Math.sqrt(ysq);
  34386. this._scaleVector.z = zs * Math.sqrt(zsq);
  34387. if (this._parent) {
  34388. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  34389. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  34390. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  34391. }
  34392. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  34393. };
  34394. /**
  34395. * Get the world direction from an axis that is in the local space of the bone.
  34396. * @param localAxis The local direction that is used to compute the world direction.
  34397. * @param mesh The mesh that this bone is attached to.
  34398. * @returns The world direction
  34399. */
  34400. Bone.prototype.getDirection = function (localAxis, mesh) {
  34401. var result = BABYLON.Vector3.Zero();
  34402. this.getDirectionToRef(localAxis, mesh, result);
  34403. return result;
  34404. };
  34405. /**
  34406. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  34407. * @param localAxis The local direction that is used to compute the world direction.
  34408. * @param mesh The mesh that this bone is attached to.
  34409. * @param result The vector3 that the world direction will be copied to.
  34410. */
  34411. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  34412. var wm;
  34413. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34414. if (mesh) {
  34415. wm = mesh.getWorldMatrix();
  34416. }
  34417. this._skeleton.computeAbsoluteTransforms();
  34418. var mat = BABYLON.Tmp.Matrix[0];
  34419. mat.copyFrom(this.getAbsoluteTransform());
  34420. if (mesh) {
  34421. mat.multiplyToRef(wm, mat);
  34422. }
  34423. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  34424. result.normalize();
  34425. };
  34426. /**
  34427. * Get the euler rotation of the bone in local or world space.
  34428. * @param space The space that the rotation should be in.
  34429. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34430. * @returns The euler rotation
  34431. */
  34432. Bone.prototype.getRotation = function (space, mesh) {
  34433. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34434. var result = BABYLON.Vector3.Zero();
  34435. this.getRotationToRef(space, mesh, result);
  34436. return result;
  34437. };
  34438. /**
  34439. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  34440. * @param space The space that the rotation should be in.
  34441. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34442. * @param result The vector3 that the rotation should be copied to.
  34443. */
  34444. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  34445. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34446. var quat = BABYLON.Tmp.Quaternion[0];
  34447. this.getRotationQuaternionToRef(space, mesh, quat);
  34448. quat.toEulerAnglesToRef(result);
  34449. };
  34450. /**
  34451. * Get the quaternion rotation of the bone in either local or world space.
  34452. * @param space The space that the rotation should be in.
  34453. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34454. * @returns The quaternion rotation
  34455. */
  34456. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  34457. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34458. var result = BABYLON.Quaternion.Identity();
  34459. this.getRotationQuaternionToRef(space, mesh, result);
  34460. return result;
  34461. };
  34462. /**
  34463. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  34464. * @param space The space that the rotation should be in.
  34465. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34466. * @param result The quaternion that the rotation should be copied to.
  34467. */
  34468. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  34469. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34470. if (space == BABYLON.Space.LOCAL) {
  34471. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  34472. }
  34473. else {
  34474. var mat = BABYLON.Tmp.Matrix[0];
  34475. var amat = this.getAbsoluteTransform();
  34476. if (mesh) {
  34477. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  34478. }
  34479. else {
  34480. mat.copyFrom(amat);
  34481. }
  34482. mat.m[0] *= this._scalingDeterminant;
  34483. mat.m[1] *= this._scalingDeterminant;
  34484. mat.m[2] *= this._scalingDeterminant;
  34485. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  34486. }
  34487. };
  34488. /**
  34489. * Get the rotation matrix of the bone in local or world space.
  34490. * @param space The space that the rotation should be in.
  34491. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34492. * @returns The rotation matrix
  34493. */
  34494. Bone.prototype.getRotationMatrix = function (space, mesh) {
  34495. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34496. var result = BABYLON.Matrix.Identity();
  34497. this.getRotationMatrixToRef(space, mesh, result);
  34498. return result;
  34499. };
  34500. /**
  34501. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  34502. * @param space The space that the rotation should be in.
  34503. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34504. * @param result The quaternion that the rotation should be copied to.
  34505. */
  34506. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  34507. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34508. if (space == BABYLON.Space.LOCAL) {
  34509. this.getLocalMatrix().getRotationMatrixToRef(result);
  34510. }
  34511. else {
  34512. var mat = BABYLON.Tmp.Matrix[0];
  34513. var amat = this.getAbsoluteTransform();
  34514. if (mesh) {
  34515. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  34516. }
  34517. else {
  34518. mat.copyFrom(amat);
  34519. }
  34520. mat.m[0] *= this._scalingDeterminant;
  34521. mat.m[1] *= this._scalingDeterminant;
  34522. mat.m[2] *= this._scalingDeterminant;
  34523. mat.getRotationMatrixToRef(result);
  34524. }
  34525. };
  34526. /**
  34527. * Get the world position of a point that is in the local space of the bone.
  34528. * @param position The local position
  34529. * @param mesh The mesh that this bone is attached to.
  34530. * @returns The world position
  34531. */
  34532. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  34533. var result = BABYLON.Vector3.Zero();
  34534. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  34535. return result;
  34536. };
  34537. /**
  34538. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  34539. * @param position The local position
  34540. * @param mesh The mesh that this bone is attached to.
  34541. * @param result The vector3 that the world position should be copied to.
  34542. */
  34543. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  34544. var wm;
  34545. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34546. if (mesh) {
  34547. wm = mesh.getWorldMatrix();
  34548. }
  34549. this._skeleton.computeAbsoluteTransforms();
  34550. var tmat = BABYLON.Tmp.Matrix[0];
  34551. if (mesh) {
  34552. tmat.copyFrom(this.getAbsoluteTransform());
  34553. tmat.multiplyToRef(wm, tmat);
  34554. }
  34555. else {
  34556. tmat = this.getAbsoluteTransform();
  34557. }
  34558. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  34559. };
  34560. /**
  34561. * Get the local position of a point that is in world space.
  34562. * @param position The world position
  34563. * @param mesh The mesh that this bone is attached to.
  34564. * @returns The local position
  34565. */
  34566. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  34567. var result = BABYLON.Vector3.Zero();
  34568. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  34569. return result;
  34570. };
  34571. /**
  34572. * Get the local position of a point that is in world space and copy it to the result param.
  34573. * @param position The world position
  34574. * @param mesh The mesh that this bone is attached to.
  34575. * @param result The vector3 that the local position should be copied to.
  34576. */
  34577. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  34578. var wm;
  34579. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34580. if (mesh) {
  34581. wm = mesh.getWorldMatrix();
  34582. }
  34583. this._skeleton.computeAbsoluteTransforms();
  34584. var tmat = BABYLON.Tmp.Matrix[0];
  34585. tmat.copyFrom(this.getAbsoluteTransform());
  34586. if (mesh) {
  34587. tmat.multiplyToRef(wm, tmat);
  34588. }
  34589. tmat.invert();
  34590. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  34591. };
  34592. return Bone;
  34593. }(BABYLON.Node));
  34594. BABYLON.Bone = Bone;
  34595. })(BABYLON || (BABYLON = {}));
  34596. //# sourceMappingURL=babylon.bone.js.map
  34597. var BABYLON;
  34598. (function (BABYLON) {
  34599. var BoneIKController = (function () {
  34600. function BoneIKController(mesh, bone, options) {
  34601. this.targetPosition = BABYLON.Vector3.Zero();
  34602. this.poleTargetPosition = BABYLON.Vector3.Zero();
  34603. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  34604. this.poleAngle = 0;
  34605. this.slerpAmount = 1;
  34606. this._bone1Quat = BABYLON.Quaternion.Identity();
  34607. this._bone1Mat = BABYLON.Matrix.Identity();
  34608. this._bone2Ang = Math.PI;
  34609. this._maxAngle = Math.PI;
  34610. this._rightHandedSystem = false;
  34611. this._bendAxis = BABYLON.Vector3.Right();
  34612. this._slerping = false;
  34613. this._adjustRoll = 0;
  34614. this._bone2 = bone;
  34615. this._bone1 = bone.getParent();
  34616. this.mesh = mesh;
  34617. var bonePos = bone.getPosition();
  34618. if (bone.getAbsoluteTransform().determinant() > 0) {
  34619. this._rightHandedSystem = true;
  34620. this._bendAxis.x = 0;
  34621. this._bendAxis.y = 0;
  34622. this._bendAxis.z = -1;
  34623. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  34624. this._adjustRoll = Math.PI * .5;
  34625. this._bendAxis.z = 1;
  34626. }
  34627. }
  34628. if (this._bone1.length) {
  34629. var boneScale1 = this._bone1.getScale();
  34630. var boneScale2 = this._bone2.getScale();
  34631. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  34632. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  34633. }
  34634. else if (this._bone1.children[0]) {
  34635. mesh.computeWorldMatrix(true);
  34636. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  34637. var pos2 = this._bone2.getAbsolutePosition(mesh);
  34638. var pos3 = this._bone1.getAbsolutePosition(mesh);
  34639. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  34640. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  34641. }
  34642. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  34643. this.maxAngle = Math.PI;
  34644. if (options) {
  34645. if (options.targetMesh) {
  34646. this.targetMesh = options.targetMesh;
  34647. this.targetMesh.computeWorldMatrix(true);
  34648. }
  34649. if (options.poleTargetMesh) {
  34650. this.poleTargetMesh = options.poleTargetMesh;
  34651. this.poleTargetMesh.computeWorldMatrix(true);
  34652. }
  34653. else if (options.poleTargetBone) {
  34654. this.poleTargetBone = options.poleTargetBone;
  34655. }
  34656. else if (this._bone1.getParent()) {
  34657. this.poleTargetBone = this._bone1.getParent();
  34658. }
  34659. if (options.poleTargetLocalOffset) {
  34660. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  34661. }
  34662. if (options.poleAngle) {
  34663. this.poleAngle = options.poleAngle;
  34664. }
  34665. if (options.bendAxis) {
  34666. this._bendAxis.copyFrom(options.bendAxis);
  34667. }
  34668. if (options.maxAngle) {
  34669. this.maxAngle = options.maxAngle;
  34670. }
  34671. if (options.slerpAmount) {
  34672. this.slerpAmount = options.slerpAmount;
  34673. }
  34674. }
  34675. }
  34676. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  34677. get: function () {
  34678. return this._maxAngle;
  34679. },
  34680. set: function (value) {
  34681. this._setMaxAngle(value);
  34682. },
  34683. enumerable: true,
  34684. configurable: true
  34685. });
  34686. BoneIKController.prototype._setMaxAngle = function (ang) {
  34687. if (ang < 0) {
  34688. ang = 0;
  34689. }
  34690. if (ang > Math.PI || ang == undefined) {
  34691. ang = Math.PI;
  34692. }
  34693. this._maxAngle = ang;
  34694. var a = this._bone1Length;
  34695. var b = this._bone2Length;
  34696. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  34697. };
  34698. BoneIKController.prototype.update = function () {
  34699. var bone1 = this._bone1;
  34700. var target = this.targetPosition;
  34701. var poleTarget = this.poleTargetPosition;
  34702. var mat1 = BoneIKController._tmpMats[0];
  34703. var mat2 = BoneIKController._tmpMats[1];
  34704. if (this.targetMesh) {
  34705. target.copyFrom(this.targetMesh.getAbsolutePosition());
  34706. }
  34707. if (this.poleTargetBone) {
  34708. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  34709. }
  34710. else if (this.poleTargetMesh) {
  34711. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  34712. }
  34713. var bonePos = BoneIKController._tmpVecs[0];
  34714. var zaxis = BoneIKController._tmpVecs[1];
  34715. var xaxis = BoneIKController._tmpVecs[2];
  34716. var yaxis = BoneIKController._tmpVecs[3];
  34717. var upAxis = BoneIKController._tmpVecs[4];
  34718. var _tmpQuat = BoneIKController._tmpQuat;
  34719. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  34720. poleTarget.subtractToRef(bonePos, upAxis);
  34721. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  34722. upAxis.y = 1;
  34723. }
  34724. else {
  34725. upAxis.normalize();
  34726. }
  34727. target.subtractToRef(bonePos, yaxis);
  34728. yaxis.normalize();
  34729. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  34730. zaxis.normalize();
  34731. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  34732. xaxis.normalize();
  34733. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  34734. var a = this._bone1Length;
  34735. var b = this._bone2Length;
  34736. var c = BABYLON.Vector3.Distance(bonePos, target);
  34737. if (this._maxReach > 0) {
  34738. c = Math.min(this._maxReach, c);
  34739. }
  34740. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  34741. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  34742. if (acosa > 1) {
  34743. acosa = 1;
  34744. }
  34745. if (acosb > 1) {
  34746. acosb = 1;
  34747. }
  34748. if (acosa < -1) {
  34749. acosa = -1;
  34750. }
  34751. if (acosb < -1) {
  34752. acosb = -1;
  34753. }
  34754. var angA = Math.acos(acosa);
  34755. var angB = Math.acos(acosb);
  34756. var angC = -angA - angB;
  34757. if (this._rightHandedSystem) {
  34758. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  34759. mat2.multiplyToRef(mat1, mat1);
  34760. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  34761. mat2.multiplyToRef(mat1, mat1);
  34762. }
  34763. else {
  34764. var _tmpVec = BoneIKController._tmpVecs[5];
  34765. _tmpVec.copyFrom(this._bendAxis);
  34766. _tmpVec.x *= -1;
  34767. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  34768. mat2.multiplyToRef(mat1, mat1);
  34769. }
  34770. if (this.poleAngle) {
  34771. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  34772. mat1.multiplyToRef(mat2, mat1);
  34773. }
  34774. if (this.slerpAmount < 1) {
  34775. if (!this._slerping) {
  34776. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  34777. }
  34778. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  34779. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  34780. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  34781. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  34782. this._slerping = true;
  34783. }
  34784. else {
  34785. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  34786. this._bone1Mat.copyFrom(mat1);
  34787. this._slerping = false;
  34788. }
  34789. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  34790. this._bone2Ang = angC;
  34791. };
  34792. return BoneIKController;
  34793. }());
  34794. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  34795. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  34796. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  34797. BABYLON.BoneIKController = BoneIKController;
  34798. })(BABYLON || (BABYLON = {}));
  34799. //# sourceMappingURL=babylon.boneIKController.js.map
  34800. var BABYLON;
  34801. (function (BABYLON) {
  34802. var BoneLookController = (function () {
  34803. /**
  34804. * Create a BoneLookController
  34805. * @param mesh the mesh that the bone belongs to
  34806. * @param bone the bone that will be looking to the target
  34807. * @param target the target Vector3 to look at
  34808. * @param settings optional settings:
  34809. * - maxYaw: the maximum angle the bone will yaw to
  34810. * - minYaw: the minimum angle the bone will yaw to
  34811. * - maxPitch: the maximum angle the bone will pitch to
  34812. * - minPitch: the minimum angle the bone will yaw to
  34813. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  34814. * - upAxis: the up axis of the coordinate system
  34815. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  34816. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  34817. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  34818. * - adjustYaw: used to make an adjustment to the yaw of the bone
  34819. * - adjustPitch: used to make an adjustment to the pitch of the bone
  34820. * - adjustRoll: used to make an adjustment to the roll of the bone
  34821. **/
  34822. function BoneLookController(mesh, bone, target, options) {
  34823. /**
  34824. * The up axis of the coordinate system that is used when the bone is rotated.
  34825. */
  34826. this.upAxis = BABYLON.Vector3.Up();
  34827. /**
  34828. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  34829. */
  34830. this.upAxisSpace = BABYLON.Space.LOCAL;
  34831. /**
  34832. * Used to make an adjustment to the yaw of the bone.
  34833. */
  34834. this.adjustYaw = 0;
  34835. /**
  34836. * Used to make an adjustment to the pitch of the bone.
  34837. */
  34838. this.adjustPitch = 0;
  34839. /**
  34840. * Used to make an adjustment to the roll of the bone.
  34841. */
  34842. this.adjustRoll = 0;
  34843. /**
  34844. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp).
  34845. */
  34846. this.slerpAmount = 1;
  34847. this._boneQuat = BABYLON.Quaternion.Identity();
  34848. this._slerping = false;
  34849. this._firstFrameSkipped = false;
  34850. this._fowardAxis = BABYLON.Vector3.Forward();
  34851. this.mesh = mesh;
  34852. this.bone = bone;
  34853. this.target = target;
  34854. if (options) {
  34855. if (options.adjustYaw) {
  34856. this.adjustYaw = options.adjustYaw;
  34857. }
  34858. if (options.adjustPitch) {
  34859. this.adjustPitch = options.adjustPitch;
  34860. }
  34861. if (options.adjustRoll) {
  34862. this.adjustRoll = options.adjustRoll;
  34863. }
  34864. if (options.maxYaw != null) {
  34865. this.maxYaw = options.maxYaw;
  34866. }
  34867. else {
  34868. this.maxYaw = Math.PI;
  34869. }
  34870. if (options.minYaw != null) {
  34871. this.minYaw = options.minYaw;
  34872. }
  34873. else {
  34874. this.minYaw = -Math.PI;
  34875. }
  34876. if (options.maxPitch != null) {
  34877. this.maxPitch = options.maxPitch;
  34878. }
  34879. else {
  34880. this.maxPitch = Math.PI;
  34881. }
  34882. if (options.minPitch != null) {
  34883. this.minPitch = options.minPitch;
  34884. }
  34885. else {
  34886. this.minPitch = -Math.PI;
  34887. }
  34888. if (options.slerpAmount != null) {
  34889. this.slerpAmount = options.slerpAmount;
  34890. }
  34891. if (options.upAxis != null) {
  34892. this.upAxis = options.upAxis;
  34893. }
  34894. if (options.upAxisSpace != null) {
  34895. this.upAxisSpace = options.upAxisSpace;
  34896. }
  34897. if (options.yawAxis != null || options.pitchAxis != null) {
  34898. var newYawAxis = BABYLON.Axis.Y;
  34899. var newPitchAxis = BABYLON.Axis.X;
  34900. if (options.yawAxis != null) {
  34901. newYawAxis = options.yawAxis.clone();
  34902. newYawAxis.normalize();
  34903. }
  34904. if (options.pitchAxis != null) {
  34905. newPitchAxis = options.pitchAxis.clone();
  34906. newPitchAxis.normalize();
  34907. }
  34908. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  34909. this._transformYawPitch = BABYLON.Matrix.Identity();
  34910. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  34911. this._transformYawPitchInv = this._transformYawPitch.clone();
  34912. this._transformYawPitch.invert();
  34913. }
  34914. }
  34915. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  34916. this.upAxisSpace = BABYLON.Space.LOCAL;
  34917. }
  34918. }
  34919. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  34920. /**
  34921. * Get/set the minimum yaw angle that the bone can look to.
  34922. */
  34923. get: function () {
  34924. return this._minYaw;
  34925. },
  34926. set: function (value) {
  34927. this._minYaw = value;
  34928. this._minYawSin = Math.sin(value);
  34929. this._minYawCos = Math.cos(value);
  34930. if (this._maxYaw != null) {
  34931. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  34932. this._yawRange = this._maxYaw - this._minYaw;
  34933. }
  34934. },
  34935. enumerable: true,
  34936. configurable: true
  34937. });
  34938. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  34939. /**
  34940. * Get/set the maximum yaw angle that the bone can look to.
  34941. */
  34942. get: function () {
  34943. return this._maxYaw;
  34944. },
  34945. set: function (value) {
  34946. this._maxYaw = value;
  34947. this._maxYawSin = Math.sin(value);
  34948. this._maxYawCos = Math.cos(value);
  34949. if (this._minYaw != null) {
  34950. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  34951. this._yawRange = this._maxYaw - this._minYaw;
  34952. }
  34953. },
  34954. enumerable: true,
  34955. configurable: true
  34956. });
  34957. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  34958. /**
  34959. * Get/set the minimum pitch angle that the bone can look to.
  34960. */
  34961. get: function () {
  34962. return this._minPitch;
  34963. },
  34964. set: function (value) {
  34965. this._minPitch = value;
  34966. this._minPitchTan = Math.tan(value);
  34967. },
  34968. enumerable: true,
  34969. configurable: true
  34970. });
  34971. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  34972. /**
  34973. * Get/set the maximum pitch angle that the bone can look to.
  34974. */
  34975. get: function () {
  34976. return this._maxPitch;
  34977. },
  34978. set: function (value) {
  34979. this._maxPitch = value;
  34980. this._maxPitchTan = Math.tan(value);
  34981. },
  34982. enumerable: true,
  34983. configurable: true
  34984. });
  34985. /**
  34986. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  34987. */
  34988. BoneLookController.prototype.update = function () {
  34989. //skip the first frame when slerping so that the mesh rotation is correct
  34990. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  34991. this._firstFrameSkipped = true;
  34992. return;
  34993. }
  34994. var bone = this.bone;
  34995. var bonePos = BoneLookController._tmpVecs[0];
  34996. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  34997. var target = this.target;
  34998. var _tmpMat1 = BoneLookController._tmpMats[0];
  34999. var _tmpMat2 = BoneLookController._tmpMats[1];
  35000. var mesh = this.mesh;
  35001. var parentBone = bone.getParent();
  35002. var upAxis = BoneLookController._tmpVecs[1];
  35003. upAxis.copyFrom(this.upAxis);
  35004. if (this.upAxisSpace == BABYLON.Space.BONE) {
  35005. if (this._transformYawPitch) {
  35006. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  35007. }
  35008. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  35009. }
  35010. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  35011. mesh.getDirectionToRef(upAxis, upAxis);
  35012. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  35013. upAxis.normalize();
  35014. }
  35015. }
  35016. var checkYaw = false;
  35017. var checkPitch = false;
  35018. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  35019. checkYaw = true;
  35020. }
  35021. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  35022. checkPitch = true;
  35023. }
  35024. if (checkYaw || checkPitch) {
  35025. var spaceMat = BoneLookController._tmpMats[2];
  35026. var spaceMatInv = BoneLookController._tmpMats[3];
  35027. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  35028. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  35029. }
  35030. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  35031. spaceMat.copyFrom(mesh.getWorldMatrix());
  35032. }
  35033. else {
  35034. var forwardAxis = BoneLookController._tmpVecs[2];
  35035. forwardAxis.copyFrom(this._fowardAxis);
  35036. if (this._transformYawPitch) {
  35037. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  35038. }
  35039. if (parentBone) {
  35040. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  35041. }
  35042. else {
  35043. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  35044. }
  35045. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  35046. rightAxis.normalize();
  35047. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  35048. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  35049. }
  35050. spaceMat.invertToRef(spaceMatInv);
  35051. var xzlen;
  35052. if (checkPitch) {
  35053. var localTarget = BoneLookController._tmpVecs[3];
  35054. target.subtractToRef(bonePos, localTarget);
  35055. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  35056. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35057. var pitch = Math.atan2(localTarget.y, xzlen);
  35058. var newPitch = pitch;
  35059. if (pitch > this._maxPitch) {
  35060. localTarget.y = this._maxPitchTan * xzlen;
  35061. newPitch = this._maxPitch;
  35062. }
  35063. else if (pitch < this._minPitch) {
  35064. localTarget.y = this._minPitchTan * xzlen;
  35065. newPitch = this._minPitch;
  35066. }
  35067. if (pitch != newPitch) {
  35068. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  35069. localTarget.addInPlace(bonePos);
  35070. target = localTarget;
  35071. }
  35072. }
  35073. if (checkYaw) {
  35074. var localTarget = BoneLookController._tmpVecs[4];
  35075. target.subtractToRef(bonePos, localTarget);
  35076. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  35077. var yaw = Math.atan2(localTarget.x, localTarget.z);
  35078. var newYaw = yaw;
  35079. if (yaw > this._maxYaw || yaw < this._minYaw) {
  35080. if (xzlen == null) {
  35081. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35082. }
  35083. if (this._yawRange > Math.PI) {
  35084. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  35085. localTarget.z = this._maxYawCos * xzlen;
  35086. localTarget.x = this._maxYawSin * xzlen;
  35087. newYaw = this._maxYaw;
  35088. }
  35089. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  35090. localTarget.z = this._minYawCos * xzlen;
  35091. localTarget.x = this._minYawSin * xzlen;
  35092. newYaw = this._minYaw;
  35093. }
  35094. }
  35095. else {
  35096. if (yaw > this._maxYaw) {
  35097. localTarget.z = this._maxYawCos * xzlen;
  35098. localTarget.x = this._maxYawSin * xzlen;
  35099. newYaw = this._maxYaw;
  35100. }
  35101. else if (yaw < this._minYaw) {
  35102. localTarget.z = this._minYawCos * xzlen;
  35103. localTarget.x = this._minYawSin * xzlen;
  35104. newYaw = this._minYaw;
  35105. }
  35106. }
  35107. }
  35108. if (this._slerping && this._yawRange > Math.PI) {
  35109. //are we going to be crossing into the min/max region?
  35110. var boneFwd = BoneLookController._tmpVecs[8];
  35111. boneFwd.copyFrom(BABYLON.Axis.Z);
  35112. if (this._transformYawPitch) {
  35113. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  35114. }
  35115. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  35116. this._boneQuat.toRotationMatrix(boneRotMat);
  35117. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  35118. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  35119. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  35120. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  35121. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  35122. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  35123. if (angBtwTar > angBtwMidYaw) {
  35124. if (xzlen == null) {
  35125. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35126. }
  35127. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  35128. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  35129. if (angBtwMin < angBtwMax) {
  35130. newYaw = boneYaw + Math.PI * .75;
  35131. localTarget.z = Math.cos(newYaw) * xzlen;
  35132. localTarget.x = Math.sin(newYaw) * xzlen;
  35133. }
  35134. else {
  35135. newYaw = boneYaw - Math.PI * .75;
  35136. localTarget.z = Math.cos(newYaw) * xzlen;
  35137. localTarget.x = Math.sin(newYaw) * xzlen;
  35138. }
  35139. }
  35140. }
  35141. if (yaw != newYaw) {
  35142. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  35143. localTarget.addInPlace(bonePos);
  35144. target = localTarget;
  35145. }
  35146. }
  35147. }
  35148. var zaxis = BoneLookController._tmpVecs[5];
  35149. var xaxis = BoneLookController._tmpVecs[6];
  35150. var yaxis = BoneLookController._tmpVecs[7];
  35151. var _tmpQuat = BoneLookController._tmpQuat;
  35152. target.subtractToRef(bonePos, zaxis);
  35153. zaxis.normalize();
  35154. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  35155. xaxis.normalize();
  35156. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  35157. yaxis.normalize();
  35158. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  35159. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  35160. return;
  35161. }
  35162. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  35163. return;
  35164. }
  35165. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  35166. return;
  35167. }
  35168. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  35169. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  35170. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  35171. }
  35172. if (this.slerpAmount < 1) {
  35173. if (!this._slerping) {
  35174. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  35175. }
  35176. if (this._transformYawPitch) {
  35177. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  35178. }
  35179. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  35180. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  35181. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  35182. this._slerping = true;
  35183. }
  35184. else {
  35185. if (this._transformYawPitch) {
  35186. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  35187. }
  35188. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  35189. this._slerping = false;
  35190. }
  35191. };
  35192. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  35193. var angDiff = ang2 - ang1;
  35194. angDiff %= Math.PI * 2;
  35195. if (angDiff > Math.PI) {
  35196. angDiff -= Math.PI * 2;
  35197. }
  35198. else if (angDiff < -Math.PI) {
  35199. angDiff += Math.PI * 2;
  35200. }
  35201. return angDiff;
  35202. };
  35203. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  35204. ang1 %= (2 * Math.PI);
  35205. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  35206. ang2 %= (2 * Math.PI);
  35207. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  35208. var ab = 0;
  35209. if (ang1 < ang2) {
  35210. ab = ang2 - ang1;
  35211. }
  35212. else {
  35213. ab = ang1 - ang2;
  35214. }
  35215. if (ab > Math.PI) {
  35216. ab = Math.PI * 2 - ab;
  35217. }
  35218. return ab;
  35219. };
  35220. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  35221. ang %= (2 * Math.PI);
  35222. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  35223. ang1 %= (2 * Math.PI);
  35224. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  35225. ang2 %= (2 * Math.PI);
  35226. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  35227. if (ang1 < ang2) {
  35228. if (ang > ang1 && ang < ang2) {
  35229. return true;
  35230. }
  35231. }
  35232. else {
  35233. if (ang > ang2 && ang < ang1) {
  35234. return true;
  35235. }
  35236. }
  35237. return false;
  35238. };
  35239. return BoneLookController;
  35240. }());
  35241. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  35242. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  35243. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  35244. BABYLON.BoneLookController = BoneLookController;
  35245. })(BABYLON || (BABYLON = {}));
  35246. //# sourceMappingURL=babylon.boneLookController.js.map
  35247. var BABYLON;
  35248. (function (BABYLON) {
  35249. var Skeleton = (function () {
  35250. function Skeleton(name, id, scene) {
  35251. this.name = name;
  35252. this.id = id;
  35253. this.bones = new Array();
  35254. this.needInitialSkinMatrix = false;
  35255. this._isDirty = true;
  35256. this._meshesWithPoseMatrix = new Array();
  35257. this._identity = BABYLON.Matrix.Identity();
  35258. this._ranges = {};
  35259. this._lastAbsoluteTransformsUpdateId = -1;
  35260. // Events
  35261. /**
  35262. * An event triggered before computing the skeleton's matrices
  35263. * @type {BABYLON.Observable}
  35264. */
  35265. this.onBeforeComputeObservable = new BABYLON.Observable();
  35266. this.bones = [];
  35267. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35268. scene.skeletons.push(this);
  35269. //make sure it will recalculate the matrix next time prepare is called.
  35270. this._isDirty = true;
  35271. }
  35272. // Members
  35273. Skeleton.prototype.getTransformMatrices = function (mesh) {
  35274. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  35275. return mesh._bonesTransformMatrices;
  35276. }
  35277. if (!this._transformMatrices) {
  35278. this.prepare();
  35279. }
  35280. return this._transformMatrices;
  35281. };
  35282. Skeleton.prototype.getScene = function () {
  35283. return this._scene;
  35284. };
  35285. // Methods
  35286. /**
  35287. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  35288. */
  35289. Skeleton.prototype.toString = function (fullDetails) {
  35290. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  35291. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  35292. if (fullDetails) {
  35293. ret += ", Ranges: {";
  35294. var first = true;
  35295. for (var name_1 in this._ranges) {
  35296. if (first) {
  35297. ret += ", ";
  35298. first = false;
  35299. }
  35300. ret += name_1;
  35301. }
  35302. ret += "}";
  35303. }
  35304. return ret;
  35305. };
  35306. /**
  35307. * Get bone's index searching by name
  35308. * @param {string} name is bone's name to search for
  35309. * @return {number} Indice of the bone. Returns -1 if not found
  35310. */
  35311. Skeleton.prototype.getBoneIndexByName = function (name) {
  35312. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  35313. if (this.bones[boneIndex].name === name) {
  35314. return boneIndex;
  35315. }
  35316. }
  35317. return -1;
  35318. };
  35319. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  35320. // check name not already in use
  35321. if (!this._ranges[name]) {
  35322. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  35323. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35324. if (this.bones[i].animations[0]) {
  35325. this.bones[i].animations[0].createRange(name, from, to);
  35326. }
  35327. }
  35328. }
  35329. };
  35330. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  35331. if (deleteFrames === void 0) { deleteFrames = true; }
  35332. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35333. if (this.bones[i].animations[0]) {
  35334. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  35335. }
  35336. }
  35337. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  35338. };
  35339. Skeleton.prototype.getAnimationRange = function (name) {
  35340. return this._ranges[name];
  35341. };
  35342. /**
  35343. * Returns as an Array, all AnimationRanges defined on this skeleton
  35344. */
  35345. Skeleton.prototype.getAnimationRanges = function () {
  35346. var animationRanges = [];
  35347. var name;
  35348. var i = 0;
  35349. for (name in this._ranges) {
  35350. animationRanges[i] = this._ranges[name];
  35351. i++;
  35352. }
  35353. return animationRanges;
  35354. };
  35355. /**
  35356. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  35357. */
  35358. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  35359. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  35360. if (this._ranges[name] || !source.getAnimationRange(name)) {
  35361. return false;
  35362. }
  35363. var ret = true;
  35364. var frameOffset = this._getHighestAnimationFrame() + 1;
  35365. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  35366. var boneDict = {};
  35367. var sourceBones = source.bones;
  35368. var nBones;
  35369. var i;
  35370. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  35371. boneDict[sourceBones[i].name] = sourceBones[i];
  35372. }
  35373. if (this.bones.length !== sourceBones.length) {
  35374. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  35375. ret = false;
  35376. }
  35377. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  35378. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  35379. var boneName = this.bones[i].name;
  35380. var sourceBone = boneDict[boneName];
  35381. if (sourceBone) {
  35382. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  35383. }
  35384. else {
  35385. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  35386. ret = false;
  35387. }
  35388. }
  35389. // do not call createAnimationRange(), since it also is done to bones, which was already done
  35390. var range = source.getAnimationRange(name);
  35391. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  35392. return ret;
  35393. };
  35394. Skeleton.prototype.returnToRest = function () {
  35395. for (var index = 0; index < this.bones.length; index++) {
  35396. this.bones[index].returnToRest();
  35397. }
  35398. };
  35399. Skeleton.prototype._getHighestAnimationFrame = function () {
  35400. var ret = 0;
  35401. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35402. if (this.bones[i].animations[0]) {
  35403. var highest = this.bones[i].animations[0].getHighestFrame();
  35404. if (ret < highest) {
  35405. ret = highest;
  35406. }
  35407. }
  35408. }
  35409. return ret;
  35410. };
  35411. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  35412. var range = this.getAnimationRange(name);
  35413. if (!range) {
  35414. return null;
  35415. }
  35416. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  35417. };
  35418. Skeleton.prototype._markAsDirty = function () {
  35419. this._isDirty = true;
  35420. };
  35421. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  35422. this._meshesWithPoseMatrix.push(mesh);
  35423. };
  35424. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  35425. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  35426. if (index > -1) {
  35427. this._meshesWithPoseMatrix.splice(index, 1);
  35428. }
  35429. };
  35430. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  35431. this.onBeforeComputeObservable.notifyObservers(this);
  35432. for (var index = 0; index < this.bones.length; index++) {
  35433. var bone = this.bones[index];
  35434. var parentBone = bone.getParent();
  35435. if (parentBone) {
  35436. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  35437. }
  35438. else {
  35439. if (initialSkinMatrix) {
  35440. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  35441. }
  35442. else {
  35443. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  35444. }
  35445. }
  35446. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  35447. }
  35448. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  35449. };
  35450. Skeleton.prototype.prepare = function () {
  35451. if (!this._isDirty) {
  35452. return;
  35453. }
  35454. if (this.needInitialSkinMatrix) {
  35455. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  35456. var mesh = this._meshesWithPoseMatrix[index];
  35457. var poseMatrix = mesh.getPoseMatrix();
  35458. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  35459. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  35460. }
  35461. if (this._synchronizedWithMesh !== mesh) {
  35462. this._synchronizedWithMesh = mesh;
  35463. // Prepare bones
  35464. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  35465. var bone = this.bones[boneIndex];
  35466. if (!bone.getParent()) {
  35467. var matrix = bone.getBaseMatrix();
  35468. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  35469. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  35470. }
  35471. }
  35472. }
  35473. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  35474. }
  35475. }
  35476. else {
  35477. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  35478. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  35479. }
  35480. this._computeTransformMatrices(this._transformMatrices, null);
  35481. }
  35482. this._isDirty = false;
  35483. this._scene._activeBones.addCount(this.bones.length, false);
  35484. };
  35485. Skeleton.prototype.getAnimatables = function () {
  35486. if (!this._animatables || this._animatables.length !== this.bones.length) {
  35487. this._animatables = [];
  35488. for (var index = 0; index < this.bones.length; index++) {
  35489. this._animatables.push(this.bones[index]);
  35490. }
  35491. }
  35492. return this._animatables;
  35493. };
  35494. Skeleton.prototype.clone = function (name, id) {
  35495. var result = new Skeleton(name, id || name, this._scene);
  35496. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  35497. for (var index = 0; index < this.bones.length; index++) {
  35498. var source = this.bones[index];
  35499. var parentBone = null;
  35500. if (source.getParent()) {
  35501. var parentIndex = this.bones.indexOf(source.getParent());
  35502. parentBone = result.bones[parentIndex];
  35503. }
  35504. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  35505. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  35506. }
  35507. if (this._ranges) {
  35508. result._ranges = {};
  35509. for (var rangeName in this._ranges) {
  35510. result._ranges[rangeName] = this._ranges[rangeName].clone();
  35511. }
  35512. }
  35513. this._isDirty = true;
  35514. return result;
  35515. };
  35516. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  35517. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  35518. this.bones.forEach(function (bone) {
  35519. bone.animations.forEach(function (animation) {
  35520. animation.enableBlending = true;
  35521. animation.blendingSpeed = blendingSpeed;
  35522. });
  35523. });
  35524. };
  35525. Skeleton.prototype.dispose = function () {
  35526. this._meshesWithPoseMatrix = [];
  35527. // Animations
  35528. this.getScene().stopAnimation(this);
  35529. // Remove from scene
  35530. this.getScene().removeSkeleton(this);
  35531. };
  35532. Skeleton.prototype.serialize = function () {
  35533. var serializationObject = {};
  35534. serializationObject.name = this.name;
  35535. serializationObject.id = this.id;
  35536. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  35537. serializationObject.bones = [];
  35538. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  35539. for (var index = 0; index < this.bones.length; index++) {
  35540. var bone = this.bones[index];
  35541. var serializedBone = {
  35542. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  35543. name: bone.name,
  35544. matrix: bone.getBaseMatrix().toArray(),
  35545. rest: bone.getRestPose().toArray()
  35546. };
  35547. serializationObject.bones.push(serializedBone);
  35548. if (bone.length) {
  35549. serializedBone.length = bone.length;
  35550. }
  35551. if (bone.animations && bone.animations.length > 0) {
  35552. serializedBone.animation = bone.animations[0].serialize();
  35553. }
  35554. serializationObject.ranges = [];
  35555. for (var name in this._ranges) {
  35556. var range = {};
  35557. range.name = name;
  35558. range.from = this._ranges[name].from;
  35559. range.to = this._ranges[name].to;
  35560. serializationObject.ranges.push(range);
  35561. }
  35562. }
  35563. return serializationObject;
  35564. };
  35565. Skeleton.Parse = function (parsedSkeleton, scene) {
  35566. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  35567. if (parsedSkeleton.dimensionsAtRest) {
  35568. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  35569. }
  35570. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  35571. var index;
  35572. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  35573. var parsedBone = parsedSkeleton.bones[index];
  35574. var parentBone = null;
  35575. if (parsedBone.parentBoneIndex > -1) {
  35576. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  35577. }
  35578. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  35579. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  35580. if (parsedBone.length) {
  35581. bone.length = parsedBone.length;
  35582. }
  35583. if (parsedBone.animation) {
  35584. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  35585. }
  35586. }
  35587. // placed after bones, so createAnimationRange can cascade down
  35588. if (parsedSkeleton.ranges) {
  35589. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  35590. var data = parsedSkeleton.ranges[index];
  35591. skeleton.createAnimationRange(data.name, data.from, data.to);
  35592. }
  35593. }
  35594. return skeleton;
  35595. };
  35596. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  35597. if (forceUpdate === void 0) { forceUpdate = false; }
  35598. var renderId = this._scene.getRenderId();
  35599. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  35600. this.bones[0].computeAbsoluteTransforms();
  35601. this._lastAbsoluteTransformsUpdateId = renderId;
  35602. }
  35603. };
  35604. Skeleton.prototype.getPoseMatrix = function () {
  35605. var poseMatrix;
  35606. if (this._meshesWithPoseMatrix.length > 0) {
  35607. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  35608. }
  35609. return poseMatrix;
  35610. };
  35611. return Skeleton;
  35612. }());
  35613. BABYLON.Skeleton = Skeleton;
  35614. })(BABYLON || (BABYLON = {}));
  35615. //# sourceMappingURL=babylon.skeleton.js.map
  35616. var BABYLON;
  35617. (function (BABYLON) {
  35618. var PostProcess = (function () {
  35619. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  35620. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  35621. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35622. this.name = name;
  35623. this.width = -1;
  35624. this.height = -1;
  35625. /*
  35626. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  35627. Can only be used on a single postprocess or on the last one of a chain.
  35628. */
  35629. this.enablePixelPerfectMode = false;
  35630. this.samples = 1;
  35631. this._reusable = false;
  35632. this._textures = new BABYLON.SmartArray(2);
  35633. this._currentRenderTextureInd = 0;
  35634. this._scaleRatio = new BABYLON.Vector2(1, 1);
  35635. // Events
  35636. /**
  35637. * An event triggered when the postprocess is activated.
  35638. * @type {BABYLON.Observable}
  35639. */
  35640. this.onActivateObservable = new BABYLON.Observable();
  35641. /**
  35642. * An event triggered when the postprocess changes its size.
  35643. * @type {BABYLON.Observable}
  35644. */
  35645. this.onSizeChangedObservable = new BABYLON.Observable();
  35646. /**
  35647. * An event triggered when the postprocess applies its effect.
  35648. * @type {BABYLON.Observable}
  35649. */
  35650. this.onApplyObservable = new BABYLON.Observable();
  35651. /**
  35652. * An event triggered before rendering the postprocess
  35653. * @type {BABYLON.Observable}
  35654. */
  35655. this.onBeforeRenderObservable = new BABYLON.Observable();
  35656. /**
  35657. * An event triggered after rendering the postprocess
  35658. * @type {BABYLON.Observable}
  35659. */
  35660. this.onAfterRenderObservable = new BABYLON.Observable();
  35661. if (camera != null) {
  35662. this._camera = camera;
  35663. this._scene = camera.getScene();
  35664. camera.attachPostProcess(this);
  35665. this._engine = this._scene.getEngine();
  35666. }
  35667. else {
  35668. this._engine = engine;
  35669. }
  35670. this._options = options;
  35671. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  35672. this._reusable = reusable || false;
  35673. this._textureType = textureType;
  35674. this._samplers = samplers || [];
  35675. this._samplers.push("textureSampler");
  35676. this._fragmentUrl = fragmentUrl;
  35677. this._parameters = parameters || [];
  35678. this._parameters.push("scale");
  35679. this.updateEffect(defines);
  35680. }
  35681. Object.defineProperty(PostProcess.prototype, "onActivate", {
  35682. set: function (callback) {
  35683. if (this._onActivateObserver) {
  35684. this.onActivateObservable.remove(this._onActivateObserver);
  35685. }
  35686. this._onActivateObserver = this.onActivateObservable.add(callback);
  35687. },
  35688. enumerable: true,
  35689. configurable: true
  35690. });
  35691. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  35692. set: function (callback) {
  35693. if (this._onSizeChangedObserver) {
  35694. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  35695. }
  35696. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  35697. },
  35698. enumerable: true,
  35699. configurable: true
  35700. });
  35701. Object.defineProperty(PostProcess.prototype, "onApply", {
  35702. set: function (callback) {
  35703. if (this._onApplyObserver) {
  35704. this.onApplyObservable.remove(this._onApplyObserver);
  35705. }
  35706. this._onApplyObserver = this.onApplyObservable.add(callback);
  35707. },
  35708. enumerable: true,
  35709. configurable: true
  35710. });
  35711. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  35712. set: function (callback) {
  35713. if (this._onBeforeRenderObserver) {
  35714. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  35715. }
  35716. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  35717. },
  35718. enumerable: true,
  35719. configurable: true
  35720. });
  35721. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  35722. set: function (callback) {
  35723. if (this._onAfterRenderObserver) {
  35724. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  35725. }
  35726. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  35727. },
  35728. enumerable: true,
  35729. configurable: true
  35730. });
  35731. PostProcess.prototype.updateEffect = function (defines) {
  35732. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  35733. };
  35734. PostProcess.prototype.isReusable = function () {
  35735. return this._reusable;
  35736. };
  35737. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  35738. PostProcess.prototype.markTextureDirty = function () {
  35739. this.width = -1;
  35740. };
  35741. PostProcess.prototype.activate = function (camera, sourceTexture) {
  35742. var _this = this;
  35743. camera = camera || this._camera;
  35744. var scene = camera.getScene();
  35745. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  35746. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  35747. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  35748. var desiredWidth = this._options.width || requiredWidth;
  35749. var desiredHeight = this._options.height || requiredHeight;
  35750. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  35751. if (!this._options.width) {
  35752. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  35753. }
  35754. if (!this._options.height) {
  35755. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  35756. }
  35757. }
  35758. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  35759. if (this._textures.length > 0) {
  35760. for (var i = 0; i < this._textures.length; i++) {
  35761. this._engine._releaseTexture(this._textures.data[i]);
  35762. }
  35763. this._textures.reset();
  35764. }
  35765. this.width = desiredWidth;
  35766. this.height = desiredHeight;
  35767. var textureSize = { width: this.width, height: this.height };
  35768. var textureOptions = {
  35769. generateMipMaps: false,
  35770. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  35771. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  35772. samplingMode: this.renderTargetSamplingMode,
  35773. type: this._textureType
  35774. };
  35775. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35776. if (this._reusable) {
  35777. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35778. }
  35779. this.onSizeChangedObservable.notifyObservers(this);
  35780. }
  35781. this._textures.forEach(function (texture) {
  35782. if (texture.samples !== _this.samples) {
  35783. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  35784. }
  35785. });
  35786. if (this.enablePixelPerfectMode) {
  35787. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  35788. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  35789. }
  35790. else {
  35791. this._scaleRatio.copyFromFloats(1, 1);
  35792. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  35793. }
  35794. this.onActivateObservable.notifyObservers(camera);
  35795. // Clear
  35796. if (this.clearColor) {
  35797. this._engine.clear(this.clearColor, true, true, true);
  35798. }
  35799. else {
  35800. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  35801. }
  35802. if (this._reusable) {
  35803. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  35804. }
  35805. };
  35806. Object.defineProperty(PostProcess.prototype, "isSupported", {
  35807. get: function () {
  35808. return this._effect.isSupported;
  35809. },
  35810. enumerable: true,
  35811. configurable: true
  35812. });
  35813. PostProcess.prototype.apply = function () {
  35814. // Check
  35815. if (!this._effect.isReady())
  35816. return null;
  35817. // States
  35818. this._engine.enableEffect(this._effect);
  35819. this._engine.setState(false);
  35820. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35821. this._engine.setDepthBuffer(false);
  35822. this._engine.setDepthWrite(false);
  35823. // Texture
  35824. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  35825. // Parameters
  35826. this._effect.setVector2("scale", this._scaleRatio);
  35827. this.onApplyObservable.notifyObservers(this._effect);
  35828. return this._effect;
  35829. };
  35830. PostProcess.prototype.dispose = function (camera) {
  35831. camera = camera || this._camera;
  35832. if (this._textures.length > 0) {
  35833. for (var i = 0; i < this._textures.length; i++) {
  35834. this._engine._releaseTexture(this._textures.data[i]);
  35835. }
  35836. }
  35837. this._textures.dispose();
  35838. if (!camera) {
  35839. return;
  35840. }
  35841. camera.detachPostProcess(this);
  35842. var index = camera._postProcesses.indexOf(this);
  35843. if (index === 0 && camera._postProcesses.length > 0) {
  35844. this._camera._postProcesses[0].markTextureDirty();
  35845. }
  35846. this.onActivateObservable.clear();
  35847. this.onAfterRenderObservable.clear();
  35848. this.onApplyObservable.clear();
  35849. this.onBeforeRenderObservable.clear();
  35850. this.onSizeChangedObservable.clear();
  35851. };
  35852. return PostProcess;
  35853. }());
  35854. BABYLON.PostProcess = PostProcess;
  35855. })(BABYLON || (BABYLON = {}));
  35856. //# sourceMappingURL=babylon.postProcess.js.map
  35857. var BABYLON;
  35858. (function (BABYLON) {
  35859. var PostProcessManager = (function () {
  35860. function PostProcessManager(scene) {
  35861. this._vertexBuffers = {};
  35862. this._scene = scene;
  35863. }
  35864. PostProcessManager.prototype._prepareBuffers = function () {
  35865. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35866. return;
  35867. }
  35868. // VBO
  35869. var vertices = [];
  35870. vertices.push(1, 1);
  35871. vertices.push(-1, 1);
  35872. vertices.push(-1, -1);
  35873. vertices.push(1, -1);
  35874. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35875. // Indices
  35876. var indices = [];
  35877. indices.push(0);
  35878. indices.push(1);
  35879. indices.push(2);
  35880. indices.push(0);
  35881. indices.push(2);
  35882. indices.push(3);
  35883. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35884. };
  35885. // Methods
  35886. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  35887. var postProcesses = this._scene.activeCamera._postProcesses;
  35888. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35889. return false;
  35890. }
  35891. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  35892. return true;
  35893. };
  35894. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  35895. var engine = this._scene.getEngine();
  35896. for (var index = 0; index < postProcesses.length; index++) {
  35897. if (index < postProcesses.length - 1) {
  35898. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35899. }
  35900. else {
  35901. if (targetTexture) {
  35902. engine.bindFramebuffer(targetTexture);
  35903. }
  35904. else {
  35905. engine.restoreDefaultFramebuffer();
  35906. }
  35907. }
  35908. var pp = postProcesses[index];
  35909. var effect = pp.apply();
  35910. if (effect) {
  35911. pp.onBeforeRenderObservable.notifyObservers(effect);
  35912. // VBOs
  35913. this._prepareBuffers();
  35914. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35915. // Draw order
  35916. engine.draw(true, 0, 6);
  35917. pp.onAfterRenderObservable.notifyObservers(effect);
  35918. }
  35919. }
  35920. // Restore depth buffer
  35921. engine.setDepthBuffer(true);
  35922. engine.setDepthWrite(true);
  35923. };
  35924. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  35925. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  35926. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35927. return;
  35928. }
  35929. var engine = this._scene.getEngine();
  35930. for (var index = 0, len = postProcesses.length; index < len; index++) {
  35931. if (index < len - 1) {
  35932. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35933. }
  35934. else {
  35935. if (targetTexture) {
  35936. engine.bindFramebuffer(targetTexture, faceIndex);
  35937. }
  35938. else {
  35939. engine.restoreDefaultFramebuffer();
  35940. }
  35941. }
  35942. if (doNotPresent) {
  35943. break;
  35944. }
  35945. var pp = postProcesses[index];
  35946. var effect = pp.apply();
  35947. if (effect) {
  35948. pp.onBeforeRenderObservable.notifyObservers(effect);
  35949. // VBOs
  35950. this._prepareBuffers();
  35951. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35952. // Draw order
  35953. engine.draw(true, 0, 6);
  35954. pp.onAfterRenderObservable.notifyObservers(effect);
  35955. }
  35956. }
  35957. // Restore depth buffer
  35958. engine.setDepthBuffer(true);
  35959. engine.setDepthWrite(true);
  35960. };
  35961. PostProcessManager.prototype.dispose = function () {
  35962. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35963. if (buffer) {
  35964. buffer.dispose();
  35965. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35966. }
  35967. if (this._indexBuffer) {
  35968. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35969. this._indexBuffer = null;
  35970. }
  35971. };
  35972. return PostProcessManager;
  35973. }());
  35974. BABYLON.PostProcessManager = PostProcessManager;
  35975. })(BABYLON || (BABYLON = {}));
  35976. //# sourceMappingURL=babylon.postProcessManager.js.map
  35977. var BABYLON;
  35978. (function (BABYLON) {
  35979. var PassPostProcess = (function (_super) {
  35980. __extends(PassPostProcess, _super);
  35981. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  35982. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  35983. }
  35984. return PassPostProcess;
  35985. }(BABYLON.PostProcess));
  35986. BABYLON.PassPostProcess = PassPostProcess;
  35987. })(BABYLON || (BABYLON = {}));
  35988. //# sourceMappingURL=babylon.passPostProcess.js.map
  35989. var BABYLON;
  35990. (function (BABYLON) {
  35991. /**
  35992. * This is a holder class for the physics joint created by the physics plugin.
  35993. * It holds a set of functions to control the underlying joint.
  35994. */
  35995. var PhysicsJoint = (function () {
  35996. function PhysicsJoint(type, jointData) {
  35997. this.type = type;
  35998. this.jointData = jointData;
  35999. jointData.nativeParams = jointData.nativeParams || {};
  36000. }
  36001. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  36002. get: function () {
  36003. return this._physicsJoint;
  36004. },
  36005. set: function (newJoint) {
  36006. if (this._physicsJoint) {
  36007. }
  36008. this._physicsJoint = newJoint;
  36009. },
  36010. enumerable: true,
  36011. configurable: true
  36012. });
  36013. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  36014. set: function (physicsPlugin) {
  36015. this._physicsPlugin = physicsPlugin;
  36016. },
  36017. enumerable: true,
  36018. configurable: true
  36019. });
  36020. /**
  36021. * Execute a function that is physics-plugin specific.
  36022. * @param {Function} func the function that will be executed.
  36023. * It accepts two parameters: the physics world and the physics joint.
  36024. */
  36025. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  36026. func(this._physicsPlugin.world, this._physicsJoint);
  36027. };
  36028. return PhysicsJoint;
  36029. }());
  36030. //TODO check if the native joints are the same
  36031. //Joint Types
  36032. PhysicsJoint.DistanceJoint = 0;
  36033. PhysicsJoint.HingeJoint = 1;
  36034. PhysicsJoint.BallAndSocketJoint = 2;
  36035. PhysicsJoint.WheelJoint = 3;
  36036. PhysicsJoint.SliderJoint = 4;
  36037. //OIMO
  36038. PhysicsJoint.PrismaticJoint = 5;
  36039. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  36040. PhysicsJoint.UniversalJoint = 6;
  36041. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  36042. //Cannon
  36043. //Similar to a Ball-Joint. Different in params
  36044. PhysicsJoint.PointToPointJoint = 8;
  36045. //Cannon only at the moment
  36046. PhysicsJoint.SpringJoint = 9;
  36047. PhysicsJoint.LockJoint = 10;
  36048. BABYLON.PhysicsJoint = PhysicsJoint;
  36049. /**
  36050. * A class representing a physics distance joint.
  36051. */
  36052. var DistanceJoint = (function (_super) {
  36053. __extends(DistanceJoint, _super);
  36054. function DistanceJoint(jointData) {
  36055. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  36056. }
  36057. /**
  36058. * Update the predefined distance.
  36059. */
  36060. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  36061. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  36062. };
  36063. return DistanceJoint;
  36064. }(PhysicsJoint));
  36065. BABYLON.DistanceJoint = DistanceJoint;
  36066. var MotorEnabledJoint = (function (_super) {
  36067. __extends(MotorEnabledJoint, _super);
  36068. function MotorEnabledJoint(type, jointData) {
  36069. return _super.call(this, type, jointData) || this;
  36070. }
  36071. /**
  36072. * Set the motor values.
  36073. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36074. * @param {number} force the force to apply
  36075. * @param {number} maxForce max force for this motor.
  36076. */
  36077. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  36078. this._physicsPlugin.setMotor(this, force, maxForce);
  36079. };
  36080. /**
  36081. * Set the motor's limits.
  36082. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36083. */
  36084. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  36085. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  36086. };
  36087. return MotorEnabledJoint;
  36088. }(PhysicsJoint));
  36089. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  36090. /**
  36091. * This class represents a single hinge physics joint
  36092. */
  36093. var HingeJoint = (function (_super) {
  36094. __extends(HingeJoint, _super);
  36095. function HingeJoint(jointData) {
  36096. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  36097. }
  36098. /**
  36099. * Set the motor values.
  36100. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36101. * @param {number} force the force to apply
  36102. * @param {number} maxForce max force for this motor.
  36103. */
  36104. HingeJoint.prototype.setMotor = function (force, maxForce) {
  36105. this._physicsPlugin.setMotor(this, force, maxForce);
  36106. };
  36107. /**
  36108. * Set the motor's limits.
  36109. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36110. */
  36111. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  36112. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  36113. };
  36114. return HingeJoint;
  36115. }(MotorEnabledJoint));
  36116. BABYLON.HingeJoint = HingeJoint;
  36117. /**
  36118. * This class represents a dual hinge physics joint (same as wheel joint)
  36119. */
  36120. var Hinge2Joint = (function (_super) {
  36121. __extends(Hinge2Joint, _super);
  36122. function Hinge2Joint(jointData) {
  36123. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  36124. }
  36125. /**
  36126. * Set the motor values.
  36127. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36128. * @param {number} force the force to apply
  36129. * @param {number} maxForce max force for this motor.
  36130. * @param {motorIndex} the motor's index, 0 or 1.
  36131. */
  36132. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  36133. if (motorIndex === void 0) { motorIndex = 0; }
  36134. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  36135. };
  36136. /**
  36137. * Set the motor limits.
  36138. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36139. * @param {number} upperLimit the upper limit
  36140. * @param {number} lowerLimit lower limit
  36141. * @param {motorIndex} the motor's index, 0 or 1.
  36142. */
  36143. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  36144. if (motorIndex === void 0) { motorIndex = 0; }
  36145. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  36146. };
  36147. return Hinge2Joint;
  36148. }(MotorEnabledJoint));
  36149. BABYLON.Hinge2Joint = Hinge2Joint;
  36150. })(BABYLON || (BABYLON = {}));
  36151. //# sourceMappingURL=babylon.physicsJoint.js.map
  36152. var BABYLON;
  36153. (function (BABYLON) {
  36154. var PhysicsImpostor = (function () {
  36155. function PhysicsImpostor(object, type, _options, _scene) {
  36156. if (_options === void 0) { _options = { mass: 0 }; }
  36157. var _this = this;
  36158. this.object = object;
  36159. this.type = type;
  36160. this._options = _options;
  36161. this._scene = _scene;
  36162. this._bodyUpdateRequired = false;
  36163. this._onBeforePhysicsStepCallbacks = new Array();
  36164. this._onAfterPhysicsStepCallbacks = new Array();
  36165. this._onPhysicsCollideCallbacks = [];
  36166. this._deltaPosition = BABYLON.Vector3.Zero();
  36167. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  36168. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  36169. /**
  36170. * this function is executed by the physics engine.
  36171. */
  36172. this.beforeStep = function () {
  36173. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  36174. //conjugate deltaRotation
  36175. if (_this._deltaRotationConjugated) {
  36176. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  36177. }
  36178. else {
  36179. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  36180. }
  36181. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  36182. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  36183. func(_this);
  36184. });
  36185. };
  36186. /**
  36187. * this function is executed by the physics engine.
  36188. */
  36189. this.afterStep = function () {
  36190. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  36191. func(_this);
  36192. });
  36193. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  36194. _this.object.position.addInPlace(_this._deltaPosition);
  36195. if (_this._deltaRotation) {
  36196. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  36197. }
  36198. };
  36199. /**
  36200. * Legacy collision detection event support
  36201. */
  36202. this.onCollideEvent = null;
  36203. //event and body object due to cannon's event-based architecture.
  36204. this.onCollide = function (e) {
  36205. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  36206. return;
  36207. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  36208. if (otherImpostor) {
  36209. // Legacy collision detection event support
  36210. if (_this.onCollideEvent) {
  36211. _this.onCollideEvent(_this, otherImpostor);
  36212. }
  36213. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  36214. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  36215. }).forEach(function (obj) {
  36216. obj.callback(_this, otherImpostor);
  36217. });
  36218. }
  36219. };
  36220. //sanity check!
  36221. if (!this.object) {
  36222. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  36223. return;
  36224. }
  36225. //legacy support for old syntax.
  36226. if (!this._scene && object.getScene) {
  36227. this._scene = object.getScene();
  36228. }
  36229. this._physicsEngine = this._scene.getPhysicsEngine();
  36230. if (!this._physicsEngine) {
  36231. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  36232. }
  36233. else {
  36234. //set the object's quaternion, if not set
  36235. if (!this.object.rotationQuaternion) {
  36236. if (this.object.rotation) {
  36237. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  36238. }
  36239. else {
  36240. this.object.rotationQuaternion = new BABYLON.Quaternion();
  36241. }
  36242. }
  36243. //default options params
  36244. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  36245. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  36246. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  36247. this._joints = [];
  36248. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  36249. if (!this.object.parent) {
  36250. this._init();
  36251. }
  36252. }
  36253. }
  36254. /**
  36255. * This function will completly initialize this impostor.
  36256. * It will create a new body - but only if this mesh has no parent.
  36257. * If it has, this impostor will not be used other than to define the impostor
  36258. * of the child mesh.
  36259. */
  36260. PhysicsImpostor.prototype._init = function () {
  36261. this._physicsEngine.removeImpostor(this);
  36262. this.physicsBody = null;
  36263. this._parent = this._parent || this._getPhysicsParent();
  36264. if (!this.parent) {
  36265. this._physicsEngine.addImpostor(this);
  36266. }
  36267. };
  36268. PhysicsImpostor.prototype._getPhysicsParent = function () {
  36269. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  36270. var parentMesh = this.object.parent;
  36271. return parentMesh.physicsImpostor;
  36272. }
  36273. return;
  36274. };
  36275. /**
  36276. * Should a new body be generated.
  36277. */
  36278. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  36279. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  36280. };
  36281. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  36282. this.forceUpdate();
  36283. };
  36284. /**
  36285. * Force a regeneration of this or the parent's impostor's body.
  36286. * Use under cautious - This will remove all joints already implemented.
  36287. */
  36288. PhysicsImpostor.prototype.forceUpdate = function () {
  36289. this._init();
  36290. if (this.parent) {
  36291. this.parent.forceUpdate();
  36292. }
  36293. };
  36294. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  36295. /*public get mesh(): AbstractMesh {
  36296. return this._mesh;
  36297. }*/
  36298. /**
  36299. * Gets the body that holds this impostor. Either its own, or its parent.
  36300. */
  36301. get: function () {
  36302. return this._parent ? this._parent.physicsBody : this._physicsBody;
  36303. },
  36304. /**
  36305. * Set the physics body. Used mainly by the physics engine/plugin
  36306. */
  36307. set: function (physicsBody) {
  36308. if (this._physicsBody) {
  36309. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  36310. }
  36311. this._physicsBody = physicsBody;
  36312. this.resetUpdateFlags();
  36313. },
  36314. enumerable: true,
  36315. configurable: true
  36316. });
  36317. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  36318. get: function () {
  36319. return this._parent;
  36320. },
  36321. set: function (value) {
  36322. this._parent = value;
  36323. },
  36324. enumerable: true,
  36325. configurable: true
  36326. });
  36327. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  36328. this._bodyUpdateRequired = false;
  36329. };
  36330. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  36331. if (this.object.getBoundingInfo) {
  36332. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  36333. return this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2).multiply(this.object.scaling);
  36334. }
  36335. else {
  36336. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  36337. }
  36338. };
  36339. PhysicsImpostor.prototype.getObjectCenter = function () {
  36340. if (this.object.getBoundingInfo) {
  36341. return this.object.getBoundingInfo().boundingBox.centerWorld;
  36342. }
  36343. else {
  36344. return this.object.position;
  36345. }
  36346. };
  36347. /**
  36348. * Get a specific parametes from the options parameter.
  36349. */
  36350. PhysicsImpostor.prototype.getParam = function (paramName) {
  36351. return this._options[paramName];
  36352. };
  36353. /**
  36354. * Sets a specific parameter in the options given to the physics plugin
  36355. */
  36356. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  36357. this._options[paramName] = value;
  36358. this._bodyUpdateRequired = true;
  36359. };
  36360. /**
  36361. * Specifically change the body's mass option. Won't recreate the physics body object
  36362. */
  36363. PhysicsImpostor.prototype.setMass = function (mass) {
  36364. if (this.getParam("mass") !== mass) {
  36365. this.setParam("mass", mass);
  36366. }
  36367. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  36368. };
  36369. PhysicsImpostor.prototype.getLinearVelocity = function () {
  36370. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  36371. };
  36372. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  36373. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  36374. };
  36375. PhysicsImpostor.prototype.getAngularVelocity = function () {
  36376. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  36377. };
  36378. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  36379. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  36380. };
  36381. /**
  36382. * Execute a function with the physics plugin native code.
  36383. * Provide a function the will have two variables - the world object and the physics body object.
  36384. */
  36385. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  36386. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  36387. };
  36388. /**
  36389. * Register a function that will be executed before the physics world is stepping forward.
  36390. */
  36391. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  36392. this._onBeforePhysicsStepCallbacks.push(func);
  36393. };
  36394. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  36395. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  36396. if (index > -1) {
  36397. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  36398. }
  36399. else {
  36400. BABYLON.Tools.Warn("Function to remove was not found");
  36401. }
  36402. };
  36403. /**
  36404. * Register a function that will be executed after the physics step
  36405. */
  36406. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  36407. this._onAfterPhysicsStepCallbacks.push(func);
  36408. };
  36409. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  36410. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  36411. if (index > -1) {
  36412. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  36413. }
  36414. else {
  36415. BABYLON.Tools.Warn("Function to remove was not found");
  36416. }
  36417. };
  36418. /**
  36419. * register a function that will be executed when this impostor collides against a different body.
  36420. */
  36421. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  36422. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  36423. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  36424. };
  36425. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  36426. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  36427. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  36428. if (index > -1) {
  36429. this._onPhysicsCollideCallbacks.splice(index, 1);
  36430. }
  36431. else {
  36432. BABYLON.Tools.Warn("Function to remove was not found");
  36433. }
  36434. };
  36435. /**
  36436. * Apply a force
  36437. */
  36438. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  36439. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  36440. };
  36441. /**
  36442. * Apply an impulse
  36443. */
  36444. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  36445. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  36446. };
  36447. /**
  36448. * A help function to create a joint.
  36449. */
  36450. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  36451. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  36452. this.addJoint(otherImpostor, joint);
  36453. };
  36454. /**
  36455. * Add a joint to this impostor with a different impostor.
  36456. */
  36457. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  36458. this._joints.push({
  36459. otherImpostor: otherImpostor,
  36460. joint: joint
  36461. });
  36462. this._physicsEngine.addJoint(this, otherImpostor, joint);
  36463. };
  36464. /**
  36465. * Will keep this body still, in a sleep mode.
  36466. */
  36467. PhysicsImpostor.prototype.sleep = function () {
  36468. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  36469. };
  36470. /**
  36471. * Wake the body up.
  36472. */
  36473. PhysicsImpostor.prototype.wakeUp = function () {
  36474. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  36475. };
  36476. PhysicsImpostor.prototype.clone = function (newObject) {
  36477. if (!newObject)
  36478. return null;
  36479. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  36480. };
  36481. PhysicsImpostor.prototype.dispose = function () {
  36482. var _this = this;
  36483. //no dispose if no physics engine is available.
  36484. if (!this._physicsEngine) {
  36485. return;
  36486. }
  36487. this._joints.forEach(function (j) {
  36488. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  36489. });
  36490. //dispose the physics body
  36491. this._physicsEngine.removeImpostor(this);
  36492. if (this.parent) {
  36493. this.parent.forceUpdate();
  36494. }
  36495. else {
  36496. }
  36497. };
  36498. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  36499. this._deltaPosition.copyFrom(position);
  36500. };
  36501. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  36502. if (!this._deltaRotation) {
  36503. this._deltaRotation = new BABYLON.Quaternion();
  36504. }
  36505. this._deltaRotation.copyFrom(rotation);
  36506. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  36507. };
  36508. return PhysicsImpostor;
  36509. }());
  36510. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  36511. //Impostor types
  36512. PhysicsImpostor.NoImpostor = 0;
  36513. PhysicsImpostor.SphereImpostor = 1;
  36514. PhysicsImpostor.BoxImpostor = 2;
  36515. PhysicsImpostor.PlaneImpostor = 3;
  36516. PhysicsImpostor.MeshImpostor = 4;
  36517. PhysicsImpostor.CylinderImpostor = 7;
  36518. PhysicsImpostor.ParticleImpostor = 8;
  36519. PhysicsImpostor.HeightmapImpostor = 9;
  36520. BABYLON.PhysicsImpostor = PhysicsImpostor;
  36521. })(BABYLON || (BABYLON = {}));
  36522. //# sourceMappingURL=babylon.physicsImpostor.js.map
  36523. var BABYLON;
  36524. (function (BABYLON) {
  36525. var PhysicsEngine = (function () {
  36526. function PhysicsEngine(gravity, _physicsPlugin) {
  36527. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  36528. this._physicsPlugin = _physicsPlugin;
  36529. //new methods and parameters
  36530. this._impostors = [];
  36531. this._joints = [];
  36532. if (!this._physicsPlugin.isSupported()) {
  36533. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  36534. + "Please make sure it is included.");
  36535. }
  36536. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  36537. this.setGravity(gravity);
  36538. this.setTimeStep();
  36539. }
  36540. PhysicsEngine.prototype.setGravity = function (gravity) {
  36541. this.gravity = gravity;
  36542. this._physicsPlugin.setGravity(this.gravity);
  36543. };
  36544. /**
  36545. * Set the time step of the physics engine.
  36546. * default is 1/60.
  36547. * To slow it down, enter 1/600 for example.
  36548. * To speed it up, 1/30
  36549. * @param {number} newTimeStep the new timestep to apply to this world.
  36550. */
  36551. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  36552. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  36553. this._physicsPlugin.setTimeStep(newTimeStep);
  36554. };
  36555. PhysicsEngine.prototype.dispose = function () {
  36556. this._impostors.forEach(function (impostor) {
  36557. impostor.dispose();
  36558. });
  36559. this._physicsPlugin.dispose();
  36560. };
  36561. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  36562. return this._physicsPlugin.name;
  36563. };
  36564. /**
  36565. * Adding a new impostor for the impostor tracking.
  36566. * This will be done by the impostor itself.
  36567. * @param {PhysicsImpostor} impostor the impostor to add
  36568. */
  36569. PhysicsEngine.prototype.addImpostor = function (impostor) {
  36570. impostor.uniqueId = this._impostors.push(impostor);
  36571. //if no parent, generate the body
  36572. if (!impostor.parent) {
  36573. this._physicsPlugin.generatePhysicsBody(impostor);
  36574. }
  36575. };
  36576. /**
  36577. * Remove an impostor from the engine.
  36578. * This impostor and its mesh will not longer be updated by the physics engine.
  36579. * @param {PhysicsImpostor} impostor the impostor to remove
  36580. */
  36581. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  36582. var index = this._impostors.indexOf(impostor);
  36583. if (index > -1) {
  36584. var removed = this._impostors.splice(index, 1);
  36585. //Is it needed?
  36586. if (removed.length) {
  36587. //this will also remove it from the world.
  36588. removed[0].physicsBody = null;
  36589. }
  36590. }
  36591. };
  36592. /**
  36593. * Add a joint to the physics engine
  36594. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  36595. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  36596. * @param {PhysicsJoint} the joint that will connect both impostors.
  36597. */
  36598. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  36599. var impostorJoint = {
  36600. mainImpostor: mainImpostor,
  36601. connectedImpostor: connectedImpostor,
  36602. joint: joint
  36603. };
  36604. joint.physicsPlugin = this._physicsPlugin;
  36605. this._joints.push(impostorJoint);
  36606. this._physicsPlugin.generateJoint(impostorJoint);
  36607. };
  36608. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  36609. var matchingJoints = this._joints.filter(function (impostorJoint) {
  36610. return (impostorJoint.connectedImpostor === connectedImpostor
  36611. && impostorJoint.joint === joint
  36612. && impostorJoint.mainImpostor === mainImpostor);
  36613. });
  36614. if (matchingJoints.length) {
  36615. this._physicsPlugin.removeJoint(matchingJoints[0]);
  36616. }
  36617. };
  36618. /**
  36619. * Called by the scene. no need to call it.
  36620. */
  36621. PhysicsEngine.prototype._step = function (delta) {
  36622. var _this = this;
  36623. //check if any mesh has no body / requires an update
  36624. this._impostors.forEach(function (impostor) {
  36625. if (impostor.isBodyInitRequired()) {
  36626. _this._physicsPlugin.generatePhysicsBody(impostor);
  36627. }
  36628. });
  36629. if (delta > 0.1) {
  36630. delta = 0.1;
  36631. }
  36632. else if (delta <= 0) {
  36633. delta = 1.0 / 60.0;
  36634. }
  36635. this._physicsPlugin.executeStep(delta, this._impostors);
  36636. };
  36637. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  36638. return this._physicsPlugin;
  36639. };
  36640. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  36641. for (var i = 0; i < this._impostors.length; ++i) {
  36642. if (this._impostors[i].object === object) {
  36643. return this._impostors[i];
  36644. }
  36645. }
  36646. };
  36647. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  36648. for (var i = 0; i < this._impostors.length; ++i) {
  36649. if (this._impostors[i].physicsBody === body) {
  36650. return this._impostors[i];
  36651. }
  36652. }
  36653. };
  36654. return PhysicsEngine;
  36655. }());
  36656. // Statics
  36657. PhysicsEngine.Epsilon = 0.001;
  36658. BABYLON.PhysicsEngine = PhysicsEngine;
  36659. })(BABYLON || (BABYLON = {}));
  36660. //# sourceMappingURL=babylon.physicsEngine.js.map
  36661. var BABYLON;
  36662. (function (BABYLON) {
  36663. var VertexData = (function () {
  36664. function VertexData() {
  36665. }
  36666. VertexData.prototype.set = function (data, kind) {
  36667. switch (kind) {
  36668. case BABYLON.VertexBuffer.PositionKind:
  36669. this.positions = data;
  36670. break;
  36671. case BABYLON.VertexBuffer.NormalKind:
  36672. this.normals = data;
  36673. break;
  36674. case BABYLON.VertexBuffer.TangentKind:
  36675. this.tangents = data;
  36676. break;
  36677. case BABYLON.VertexBuffer.UVKind:
  36678. this.uvs = data;
  36679. break;
  36680. case BABYLON.VertexBuffer.UV2Kind:
  36681. this.uvs2 = data;
  36682. break;
  36683. case BABYLON.VertexBuffer.UV3Kind:
  36684. this.uvs3 = data;
  36685. break;
  36686. case BABYLON.VertexBuffer.UV4Kind:
  36687. this.uvs4 = data;
  36688. break;
  36689. case BABYLON.VertexBuffer.UV5Kind:
  36690. this.uvs5 = data;
  36691. break;
  36692. case BABYLON.VertexBuffer.UV6Kind:
  36693. this.uvs6 = data;
  36694. break;
  36695. case BABYLON.VertexBuffer.ColorKind:
  36696. this.colors = data;
  36697. break;
  36698. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36699. this.matricesIndices = data;
  36700. break;
  36701. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36702. this.matricesWeights = data;
  36703. break;
  36704. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36705. this.matricesIndicesExtra = data;
  36706. break;
  36707. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36708. this.matricesWeightsExtra = data;
  36709. break;
  36710. }
  36711. };
  36712. /**
  36713. * Associates the vertexData to the passed Mesh.
  36714. * Sets it as updatable or not (default `false`).
  36715. * Returns the VertexData.
  36716. */
  36717. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36718. this._applyTo(mesh, updatable);
  36719. return this;
  36720. };
  36721. /**
  36722. * Associates the vertexData to the passed Geometry.
  36723. * Sets it as updatable or not (default `false`).
  36724. * Returns the VertexData.
  36725. */
  36726. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36727. this._applyTo(geometry, updatable);
  36728. return this;
  36729. };
  36730. /**
  36731. * Updates the associated mesh.
  36732. * Returns the VertexData.
  36733. */
  36734. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36735. this._update(mesh);
  36736. return this;
  36737. };
  36738. /**
  36739. * Updates the associated geometry.
  36740. * Returns the VertexData.
  36741. */
  36742. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36743. this._update(geometry);
  36744. return this;
  36745. };
  36746. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36747. if (this.positions) {
  36748. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36749. }
  36750. if (this.normals) {
  36751. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36752. }
  36753. if (this.tangents) {
  36754. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36755. }
  36756. if (this.uvs) {
  36757. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36758. }
  36759. if (this.uvs2) {
  36760. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36761. }
  36762. if (this.uvs3) {
  36763. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36764. }
  36765. if (this.uvs4) {
  36766. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36767. }
  36768. if (this.uvs5) {
  36769. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36770. }
  36771. if (this.uvs6) {
  36772. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36773. }
  36774. if (this.colors) {
  36775. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36776. }
  36777. if (this.matricesIndices) {
  36778. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36779. }
  36780. if (this.matricesWeights) {
  36781. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36782. }
  36783. if (this.matricesIndicesExtra) {
  36784. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36785. }
  36786. if (this.matricesWeightsExtra) {
  36787. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36788. }
  36789. if (this.indices) {
  36790. meshOrGeometry.setIndices(this.indices);
  36791. }
  36792. return this;
  36793. };
  36794. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36795. if (this.positions) {
  36796. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36797. }
  36798. if (this.normals) {
  36799. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36800. }
  36801. if (this.tangents) {
  36802. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36803. }
  36804. if (this.uvs) {
  36805. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36806. }
  36807. if (this.uvs2) {
  36808. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36809. }
  36810. if (this.uvs3) {
  36811. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36812. }
  36813. if (this.uvs4) {
  36814. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36815. }
  36816. if (this.uvs5) {
  36817. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36818. }
  36819. if (this.uvs6) {
  36820. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36821. }
  36822. if (this.colors) {
  36823. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36824. }
  36825. if (this.matricesIndices) {
  36826. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36827. }
  36828. if (this.matricesWeights) {
  36829. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36830. }
  36831. if (this.matricesIndicesExtra) {
  36832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36833. }
  36834. if (this.matricesWeightsExtra) {
  36835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36836. }
  36837. if (this.indices) {
  36838. meshOrGeometry.setIndices(this.indices);
  36839. }
  36840. return this;
  36841. };
  36842. /**
  36843. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  36844. * Returns the VertexData.
  36845. */
  36846. VertexData.prototype.transform = function (matrix) {
  36847. var transformed = BABYLON.Vector3.Zero();
  36848. var index;
  36849. if (this.positions) {
  36850. var position = BABYLON.Vector3.Zero();
  36851. for (index = 0; index < this.positions.length; index += 3) {
  36852. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36853. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36854. this.positions[index] = transformed.x;
  36855. this.positions[index + 1] = transformed.y;
  36856. this.positions[index + 2] = transformed.z;
  36857. }
  36858. }
  36859. if (this.normals) {
  36860. var normal = BABYLON.Vector3.Zero();
  36861. for (index = 0; index < this.normals.length; index += 3) {
  36862. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36863. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36864. this.normals[index] = transformed.x;
  36865. this.normals[index + 1] = transformed.y;
  36866. this.normals[index + 2] = transformed.z;
  36867. }
  36868. }
  36869. if (this.tangents) {
  36870. var tangent = BABYLON.Vector4.Zero();
  36871. var tangentTransformed = BABYLON.Vector4.Zero();
  36872. for (index = 0; index < this.tangents.length; index += 4) {
  36873. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36874. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36875. this.tangents[index] = tangentTransformed.x;
  36876. this.tangents[index + 1] = tangentTransformed.y;
  36877. this.tangents[index + 2] = tangentTransformed.z;
  36878. this.tangents[index + 3] = tangentTransformed.w;
  36879. }
  36880. }
  36881. return this;
  36882. };
  36883. /**
  36884. * Merges the passed VertexData into the current one.
  36885. * Returns the modified VertexData.
  36886. */
  36887. VertexData.prototype.merge = function (other) {
  36888. if (other.indices) {
  36889. if (!this.indices) {
  36890. this.indices = [];
  36891. }
  36892. var offset = this.positions ? this.positions.length / 3 : 0;
  36893. for (var index = 0; index < other.indices.length; index++) {
  36894. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36895. this.indices.push(other.indices[index] + offset);
  36896. }
  36897. }
  36898. this.positions = this._mergeElement(this.positions, other.positions);
  36899. this.normals = this._mergeElement(this.normals, other.normals);
  36900. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36901. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36902. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36903. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36904. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36905. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36906. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36907. this.colors = this._mergeElement(this.colors, other.colors);
  36908. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36909. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36910. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36911. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36912. return this;
  36913. };
  36914. VertexData.prototype._mergeElement = function (source, other) {
  36915. if (!other)
  36916. return source;
  36917. if (!source)
  36918. return other;
  36919. var len = other.length + source.length;
  36920. var isSrcTypedArray = source instanceof Float32Array;
  36921. var isOthTypedArray = other instanceof Float32Array;
  36922. // use non-loop method when the source is Float32Array
  36923. if (isSrcTypedArray) {
  36924. var ret32 = new Float32Array(len);
  36925. ret32.set(source);
  36926. ret32.set(other, source.length);
  36927. return ret32;
  36928. }
  36929. else if (!isOthTypedArray) {
  36930. return source.concat(other);
  36931. }
  36932. else {
  36933. var ret = source.slice(0); // copy source to a separate array
  36934. for (var i = 0, len = other.length; i < len; i++) {
  36935. ret.push(other[i]);
  36936. }
  36937. return ret;
  36938. }
  36939. };
  36940. /**
  36941. * Serializes the VertexData.
  36942. * Returns a serialized object.
  36943. */
  36944. VertexData.prototype.serialize = function () {
  36945. var serializationObject = this.serialize();
  36946. if (this.positions) {
  36947. serializationObject.positions = this.positions;
  36948. }
  36949. if (this.normals) {
  36950. serializationObject.normals = this.normals;
  36951. }
  36952. if (this.tangents) {
  36953. serializationObject.tangents = this.tangents;
  36954. }
  36955. if (this.uvs) {
  36956. serializationObject.uvs = this.uvs;
  36957. }
  36958. if (this.uvs2) {
  36959. serializationObject.uvs2 = this.uvs2;
  36960. }
  36961. if (this.uvs3) {
  36962. serializationObject.uvs3 = this.uvs3;
  36963. }
  36964. if (this.uvs4) {
  36965. serializationObject.uvs4 = this.uvs4;
  36966. }
  36967. if (this.uvs5) {
  36968. serializationObject.uvs5 = this.uvs5;
  36969. }
  36970. if (this.uvs6) {
  36971. serializationObject.uvs6 = this.uvs6;
  36972. }
  36973. if (this.colors) {
  36974. serializationObject.colors = this.colors;
  36975. }
  36976. if (this.matricesIndices) {
  36977. serializationObject.matricesIndices = this.matricesIndices;
  36978. serializationObject.matricesIndices._isExpanded = true;
  36979. }
  36980. if (this.matricesWeights) {
  36981. serializationObject.matricesWeights = this.matricesWeights;
  36982. }
  36983. if (this.matricesIndicesExtra) {
  36984. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36985. serializationObject.matricesIndicesExtra._isExpanded = true;
  36986. }
  36987. if (this.matricesWeightsExtra) {
  36988. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36989. }
  36990. serializationObject.indices = this.indices;
  36991. return serializationObject;
  36992. };
  36993. // Statics
  36994. /**
  36995. * Returns the object VertexData associated to the passed mesh.
  36996. */
  36997. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  36998. return VertexData._ExtractFrom(mesh, copyWhenShared);
  36999. };
  37000. /**
  37001. * Returns the object VertexData associated to the passed geometry.
  37002. */
  37003. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  37004. return VertexData._ExtractFrom(geometry, copyWhenShared);
  37005. };
  37006. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  37007. var result = new VertexData();
  37008. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37009. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  37010. }
  37011. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37012. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  37013. }
  37014. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37015. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  37016. }
  37017. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37018. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  37019. }
  37020. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37021. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  37022. }
  37023. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37024. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  37025. }
  37026. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37027. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  37028. }
  37029. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37030. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  37031. }
  37032. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37033. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  37034. }
  37035. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37036. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  37037. }
  37038. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37039. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  37040. }
  37041. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37042. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  37043. }
  37044. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37045. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  37046. }
  37047. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37048. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  37049. }
  37050. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37051. return result;
  37052. };
  37053. /**
  37054. * Creates the vertexData of the Ribbon.
  37055. */
  37056. VertexData.CreateRibbon = function (options) {
  37057. var pathArray = options.pathArray;
  37058. var closeArray = options.closeArray || false;
  37059. var closePath = options.closePath || false;
  37060. var invertUV = options.invertUV || false;
  37061. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37062. var offset = options.offset || defaultOffset;
  37063. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37064. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37065. var customUV = options.uvs;
  37066. var customColors = options.colors;
  37067. var positions = [];
  37068. var indices = [];
  37069. var normals = [];
  37070. var uvs = [];
  37071. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37072. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37073. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37074. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37075. var minlg; // minimal length among all paths from pathArray
  37076. var lg = []; // array of path lengths : nb of vertex per path
  37077. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37078. var p; // path iterator
  37079. var i; // point iterator
  37080. var j; // point iterator
  37081. // if single path in pathArray
  37082. if (pathArray.length < 2) {
  37083. var ar1 = [];
  37084. var ar2 = [];
  37085. for (i = 0; i < pathArray[0].length - offset; i++) {
  37086. ar1.push(pathArray[0][i]);
  37087. ar2.push(pathArray[0][i + offset]);
  37088. }
  37089. pathArray = [ar1, ar2];
  37090. }
  37091. // positions and horizontal distances (u)
  37092. var idc = 0;
  37093. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37094. var path;
  37095. var l;
  37096. minlg = pathArray[0].length;
  37097. var vectlg;
  37098. var dist;
  37099. for (p = 0; p < pathArray.length; p++) {
  37100. uTotalDistance[p] = 0;
  37101. us[p] = [0];
  37102. path = pathArray[p];
  37103. l = path.length;
  37104. minlg = (minlg < l) ? minlg : l;
  37105. j = 0;
  37106. while (j < l) {
  37107. positions.push(path[j].x, path[j].y, path[j].z);
  37108. if (j > 0) {
  37109. vectlg = path[j].subtract(path[j - 1]).length();
  37110. dist = vectlg + uTotalDistance[p];
  37111. us[p].push(dist);
  37112. uTotalDistance[p] = dist;
  37113. }
  37114. j++;
  37115. }
  37116. if (closePath) {
  37117. j--;
  37118. positions.push(path[0].x, path[0].y, path[0].z);
  37119. vectlg = path[j].subtract(path[0]).length();
  37120. dist = vectlg + uTotalDistance[p];
  37121. us[p].push(dist);
  37122. uTotalDistance[p] = dist;
  37123. }
  37124. lg[p] = l + closePathCorr;
  37125. idx[p] = idc;
  37126. idc += (l + closePathCorr);
  37127. }
  37128. // vertical distances (v)
  37129. var path1;
  37130. var path2;
  37131. var vertex1;
  37132. var vertex2;
  37133. for (i = 0; i < minlg + closePathCorr; i++) {
  37134. vTotalDistance[i] = 0;
  37135. vs[i] = [0];
  37136. for (p = 0; p < pathArray.length - 1; p++) {
  37137. path1 = pathArray[p];
  37138. path2 = pathArray[p + 1];
  37139. if (i === minlg) {
  37140. vertex1 = path1[0];
  37141. vertex2 = path2[0];
  37142. }
  37143. else {
  37144. vertex1 = path1[i];
  37145. vertex2 = path2[i];
  37146. }
  37147. vectlg = vertex2.subtract(vertex1).length();
  37148. dist = vectlg + vTotalDistance[i];
  37149. vs[i].push(dist);
  37150. vTotalDistance[i] = dist;
  37151. }
  37152. if (closeArray) {
  37153. path1 = pathArray[p];
  37154. path2 = pathArray[0];
  37155. if (i === minlg) {
  37156. vertex2 = path2[0];
  37157. }
  37158. vectlg = vertex2.subtract(vertex1).length();
  37159. dist = vectlg + vTotalDistance[i];
  37160. vTotalDistance[i] = dist;
  37161. }
  37162. }
  37163. // uvs
  37164. var u;
  37165. var v;
  37166. if (customUV) {
  37167. for (p = 0; p < customUV.length; p++) {
  37168. uvs.push(customUV[p].x, customUV[p].y);
  37169. }
  37170. }
  37171. else {
  37172. for (p = 0; p < pathArray.length; p++) {
  37173. for (i = 0; i < minlg + closePathCorr; i++) {
  37174. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37175. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37176. if (invertUV) {
  37177. uvs.push(v, u);
  37178. }
  37179. else {
  37180. uvs.push(u, v);
  37181. }
  37182. }
  37183. }
  37184. }
  37185. // indices
  37186. p = 0; // path index
  37187. var pi = 0; // positions array index
  37188. var l1 = lg[p] - 1; // path1 length
  37189. var l2 = lg[p + 1] - 1; // path2 length
  37190. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37191. var shft = idx[1] - idx[0]; // shift
  37192. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37193. while (pi <= min && p < path1nb) {
  37194. // 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
  37195. indices.push(pi, pi + shft, pi + 1);
  37196. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37197. pi += 1;
  37198. if (pi === min) {
  37199. p++;
  37200. if (p === lg.length - 1) {
  37201. shft = idx[0] - idx[p];
  37202. l1 = lg[p] - 1;
  37203. l2 = lg[0] - 1;
  37204. }
  37205. else {
  37206. shft = idx[p + 1] - idx[p];
  37207. l1 = lg[p] - 1;
  37208. l2 = lg[p + 1] - 1;
  37209. }
  37210. pi = idx[p];
  37211. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37212. }
  37213. }
  37214. // normals
  37215. VertexData.ComputeNormals(positions, indices, normals);
  37216. if (closePath) {
  37217. var indexFirst = 0;
  37218. var indexLast = 0;
  37219. for (p = 0; p < pathArray.length; p++) {
  37220. indexFirst = idx[p] * 3;
  37221. if (p + 1 < pathArray.length) {
  37222. indexLast = (idx[p + 1] - 1) * 3;
  37223. }
  37224. else {
  37225. indexLast = normals.length - 3;
  37226. }
  37227. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37228. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37229. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37230. normals[indexLast] = normals[indexFirst];
  37231. normals[indexLast + 1] = normals[indexFirst + 1];
  37232. normals[indexLast + 2] = normals[indexFirst + 2];
  37233. }
  37234. }
  37235. // sides
  37236. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37237. // Colors
  37238. if (customColors) {
  37239. var colors = new Float32Array(customColors.length * 4);
  37240. for (var c = 0; c < customColors.length; c++) {
  37241. colors[c * 4] = customColors[c].r;
  37242. colors[c * 4 + 1] = customColors[c].g;
  37243. colors[c * 4 + 2] = customColors[c].b;
  37244. colors[c * 4 + 3] = customColors[c].a;
  37245. }
  37246. }
  37247. // Result
  37248. var vertexData = new VertexData();
  37249. vertexData.indices = indices;
  37250. vertexData.positions = positions;
  37251. vertexData.normals = normals;
  37252. vertexData.uvs = uvs;
  37253. if (customColors) {
  37254. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37255. }
  37256. if (closePath) {
  37257. vertexData._idx = idx;
  37258. }
  37259. return vertexData;
  37260. };
  37261. /**
  37262. * Creates the VertexData of the Box.
  37263. */
  37264. VertexData.CreateBox = function (options) {
  37265. var normalsSource = [
  37266. new BABYLON.Vector3(0, 0, 1),
  37267. new BABYLON.Vector3(0, 0, -1),
  37268. new BABYLON.Vector3(1, 0, 0),
  37269. new BABYLON.Vector3(-1, 0, 0),
  37270. new BABYLON.Vector3(0, 1, 0),
  37271. new BABYLON.Vector3(0, -1, 0)
  37272. ];
  37273. var indices = [];
  37274. var positions = [];
  37275. var normals = [];
  37276. var uvs = [];
  37277. var width = options.width || options.size || 1;
  37278. var height = options.height || options.size || 1;
  37279. var depth = options.depth || options.size || 1;
  37280. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37281. var faceUV = options.faceUV || new Array(6);
  37282. var faceColors = options.faceColors;
  37283. var colors = [];
  37284. // default face colors and UV if undefined
  37285. for (var f = 0; f < 6; f++) {
  37286. if (faceUV[f] === undefined) {
  37287. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37288. }
  37289. if (faceColors && faceColors[f] === undefined) {
  37290. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37291. }
  37292. }
  37293. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37294. // Create each face in turn.
  37295. for (var index = 0; index < normalsSource.length; index++) {
  37296. var normal = normalsSource[index];
  37297. // Get two vectors perpendicular to the face normal and to each other.
  37298. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37299. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37300. // Six indices (two triangles) per face.
  37301. var verticesLength = positions.length / 3;
  37302. indices.push(verticesLength);
  37303. indices.push(verticesLength + 1);
  37304. indices.push(verticesLength + 2);
  37305. indices.push(verticesLength);
  37306. indices.push(verticesLength + 2);
  37307. indices.push(verticesLength + 3);
  37308. // Four vertices per face.
  37309. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37310. positions.push(vertex.x, vertex.y, vertex.z);
  37311. normals.push(normal.x, normal.y, normal.z);
  37312. uvs.push(faceUV[index].z, faceUV[index].w);
  37313. if (faceColors) {
  37314. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37315. }
  37316. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37317. positions.push(vertex.x, vertex.y, vertex.z);
  37318. normals.push(normal.x, normal.y, normal.z);
  37319. uvs.push(faceUV[index].x, faceUV[index].w);
  37320. if (faceColors) {
  37321. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37322. }
  37323. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37324. positions.push(vertex.x, vertex.y, vertex.z);
  37325. normals.push(normal.x, normal.y, normal.z);
  37326. uvs.push(faceUV[index].x, faceUV[index].y);
  37327. if (faceColors) {
  37328. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37329. }
  37330. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37331. positions.push(vertex.x, vertex.y, vertex.z);
  37332. normals.push(normal.x, normal.y, normal.z);
  37333. uvs.push(faceUV[index].z, faceUV[index].y);
  37334. if (faceColors) {
  37335. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37336. }
  37337. }
  37338. // sides
  37339. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37340. // Result
  37341. var vertexData = new VertexData();
  37342. vertexData.indices = indices;
  37343. vertexData.positions = positions;
  37344. vertexData.normals = normals;
  37345. vertexData.uvs = uvs;
  37346. if (faceColors) {
  37347. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37348. vertexData.colors = totalColors;
  37349. }
  37350. return vertexData;
  37351. };
  37352. /**
  37353. * Creates the VertexData of the Sphere.
  37354. */
  37355. VertexData.CreateSphere = function (options) {
  37356. var segments = options.segments || 32;
  37357. var diameterX = options.diameterX || options.diameter || 1;
  37358. var diameterY = options.diameterY || options.diameter || 1;
  37359. var diameterZ = options.diameterZ || options.diameter || 1;
  37360. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37361. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37362. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37363. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37364. var totalZRotationSteps = 2 + segments;
  37365. var totalYRotationSteps = 2 * totalZRotationSteps;
  37366. var indices = [];
  37367. var positions = [];
  37368. var normals = [];
  37369. var uvs = [];
  37370. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37371. var normalizedZ = zRotationStep / totalZRotationSteps;
  37372. var angleZ = normalizedZ * Math.PI * slice;
  37373. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37374. var normalizedY = yRotationStep / totalYRotationSteps;
  37375. var angleY = normalizedY * Math.PI * 2 * arc;
  37376. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37377. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37378. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37379. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37380. var vertex = complete.multiply(radius);
  37381. var normal = complete.divide(radius).normalize();
  37382. positions.push(vertex.x, vertex.y, vertex.z);
  37383. normals.push(normal.x, normal.y, normal.z);
  37384. uvs.push(normalizedY, normalizedZ);
  37385. }
  37386. if (zRotationStep > 0) {
  37387. var verticesCount = positions.length / 3;
  37388. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37389. indices.push((firstIndex));
  37390. indices.push((firstIndex + 1));
  37391. indices.push(firstIndex + totalYRotationSteps + 1);
  37392. indices.push((firstIndex + totalYRotationSteps + 1));
  37393. indices.push((firstIndex + 1));
  37394. indices.push((firstIndex + totalYRotationSteps + 2));
  37395. }
  37396. }
  37397. }
  37398. // Sides
  37399. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37400. // Result
  37401. var vertexData = new VertexData();
  37402. vertexData.indices = indices;
  37403. vertexData.positions = positions;
  37404. vertexData.normals = normals;
  37405. vertexData.uvs = uvs;
  37406. return vertexData;
  37407. };
  37408. /**
  37409. * Creates the VertexData of the Cylinder or Cone.
  37410. */
  37411. VertexData.CreateCylinder = function (options) {
  37412. var height = options.height || 2;
  37413. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37414. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37415. var tessellation = options.tessellation || 24;
  37416. var subdivisions = options.subdivisions || 1;
  37417. var hasRings = options.hasRings;
  37418. var enclose = options.enclose;
  37419. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37420. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37421. var faceUV = options.faceUV || new Array(3);
  37422. var faceColors = options.faceColors;
  37423. // default face colors and UV if undefined
  37424. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37425. var ringNb = (hasRings) ? subdivisions : 1;
  37426. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37427. var f;
  37428. for (f = 0; f < surfaceNb; f++) {
  37429. if (faceColors && faceColors[f] === undefined) {
  37430. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37431. }
  37432. }
  37433. for (f = 0; f < surfaceNb; f++) {
  37434. if (faceUV && faceUV[f] === undefined) {
  37435. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37436. }
  37437. }
  37438. var indices = [];
  37439. var positions = [];
  37440. var normals = [];
  37441. var uvs = [];
  37442. var colors = [];
  37443. var angle_step = Math.PI * 2 * arc / tessellation;
  37444. var angle;
  37445. var h;
  37446. var radius;
  37447. var tan = (diameterBottom - diameterTop) / 2 / height;
  37448. var ringVertex = BABYLON.Vector3.Zero();
  37449. var ringNormal = BABYLON.Vector3.Zero();
  37450. var ringFirstVertex = BABYLON.Vector3.Zero();
  37451. var ringFirstNormal = BABYLON.Vector3.Zero();
  37452. var quadNormal = BABYLON.Vector3.Zero();
  37453. var Y = BABYLON.Axis.Y;
  37454. // positions, normals, uvs
  37455. var i;
  37456. var j;
  37457. var r;
  37458. var ringIdx = 1;
  37459. var s = 1; // surface index
  37460. var cs = 0;
  37461. var v = 0;
  37462. for (i = 0; i <= subdivisions; i++) {
  37463. h = i / subdivisions;
  37464. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37465. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37466. for (r = 0; r < ringIdx; r++) {
  37467. if (hasRings) {
  37468. s += r;
  37469. }
  37470. if (enclose) {
  37471. s += 2 * r;
  37472. }
  37473. for (j = 0; j <= tessellation; j++) {
  37474. angle = j * angle_step;
  37475. // position
  37476. ringVertex.x = Math.cos(-angle) * radius;
  37477. ringVertex.y = -height / 2 + h * height;
  37478. ringVertex.z = Math.sin(-angle) * radius;
  37479. // normal
  37480. if (diameterTop === 0 && i === subdivisions) {
  37481. // if no top cap, reuse former normals
  37482. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37483. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37484. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37485. }
  37486. else {
  37487. ringNormal.x = ringVertex.x;
  37488. ringNormal.z = ringVertex.z;
  37489. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37490. ringNormal.normalize();
  37491. }
  37492. // keep first ring vertex values for enclose
  37493. if (j === 0) {
  37494. ringFirstVertex.copyFrom(ringVertex);
  37495. ringFirstNormal.copyFrom(ringNormal);
  37496. }
  37497. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37498. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37499. if (hasRings) {
  37500. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37501. }
  37502. else {
  37503. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37504. }
  37505. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37506. if (faceColors) {
  37507. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37508. }
  37509. }
  37510. // if enclose, add four vertices and their dedicated normals
  37511. if (arc !== 1 && enclose) {
  37512. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37513. positions.push(0, ringVertex.y, 0);
  37514. positions.push(0, ringVertex.y, 0);
  37515. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37516. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37517. quadNormal.normalize();
  37518. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37519. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37520. quadNormal.normalize();
  37521. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37522. if (hasRings) {
  37523. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37524. }
  37525. else {
  37526. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37527. }
  37528. uvs.push(faceUV[s + 1].x, v);
  37529. uvs.push(faceUV[s + 1].z, v);
  37530. if (hasRings) {
  37531. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37532. }
  37533. else {
  37534. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37535. }
  37536. uvs.push(faceUV[s + 2].x, v);
  37537. uvs.push(faceUV[s + 2].z, v);
  37538. if (faceColors) {
  37539. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37540. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37541. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37542. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37543. }
  37544. }
  37545. if (cs !== s) {
  37546. cs = s;
  37547. }
  37548. }
  37549. }
  37550. // indices
  37551. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37552. var s;
  37553. i = 0;
  37554. for (s = 0; s < subdivisions; s++) {
  37555. for (j = 0; j < tessellation; j++) {
  37556. var i0 = i * (e + 1) + j;
  37557. var i1 = (i + 1) * (e + 1) + j;
  37558. var i2 = i * (e + 1) + (j + 1);
  37559. var i3 = (i + 1) * (e + 1) + (j + 1);
  37560. indices.push(i0, i1, i2);
  37561. indices.push(i3, i2, i1);
  37562. }
  37563. if (arc !== 1 && enclose) {
  37564. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37565. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37566. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37567. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37568. }
  37569. i = (hasRings) ? (i + 2) : (i + 1);
  37570. }
  37571. // Caps
  37572. var createCylinderCap = function (isTop) {
  37573. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37574. if (radius === 0) {
  37575. return;
  37576. }
  37577. // Cap positions, normals & uvs
  37578. var angle;
  37579. var circleVector;
  37580. var i;
  37581. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37582. var c;
  37583. if (faceColors) {
  37584. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37585. }
  37586. // cap center
  37587. var vbase = positions.length / 3;
  37588. var offset = isTop ? height / 2 : -height / 2;
  37589. var center = new BABYLON.Vector3(0, offset, 0);
  37590. positions.push(center.x, center.y, center.z);
  37591. normals.push(0, isTop ? 1 : -1, 0);
  37592. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37593. if (faceColors) {
  37594. colors.push(c.r, c.g, c.b, c.a);
  37595. }
  37596. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37597. for (i = 0; i <= tessellation; i++) {
  37598. angle = Math.PI * 2 * i * arc / tessellation;
  37599. var cos = Math.cos(-angle);
  37600. var sin = Math.sin(-angle);
  37601. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37602. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37603. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37604. normals.push(0, isTop ? 1 : -1, 0);
  37605. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37606. if (faceColors) {
  37607. colors.push(c.r, c.g, c.b, c.a);
  37608. }
  37609. }
  37610. // Cap indices
  37611. for (i = 0; i < tessellation; i++) {
  37612. if (!isTop) {
  37613. indices.push(vbase);
  37614. indices.push(vbase + (i + 1));
  37615. indices.push(vbase + (i + 2));
  37616. }
  37617. else {
  37618. indices.push(vbase);
  37619. indices.push(vbase + (i + 2));
  37620. indices.push(vbase + (i + 1));
  37621. }
  37622. }
  37623. };
  37624. // add caps to geometry
  37625. createCylinderCap(false);
  37626. createCylinderCap(true);
  37627. // Sides
  37628. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37629. var vertexData = new VertexData();
  37630. vertexData.indices = indices;
  37631. vertexData.positions = positions;
  37632. vertexData.normals = normals;
  37633. vertexData.uvs = uvs;
  37634. if (faceColors) {
  37635. vertexData.colors = colors;
  37636. }
  37637. return vertexData;
  37638. };
  37639. /**
  37640. * Creates the VertexData of the Torus.
  37641. */
  37642. VertexData.CreateTorus = function (options) {
  37643. var indices = [];
  37644. var positions = [];
  37645. var normals = [];
  37646. var uvs = [];
  37647. var diameter = options.diameter || 1;
  37648. var thickness = options.thickness || 0.5;
  37649. var tessellation = options.tessellation || 16;
  37650. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37651. var stride = tessellation + 1;
  37652. for (var i = 0; i <= tessellation; i++) {
  37653. var u = i / tessellation;
  37654. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37655. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37656. for (var j = 0; j <= tessellation; j++) {
  37657. var v = 1 - j / tessellation;
  37658. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37659. var dx = Math.cos(innerAngle);
  37660. var dy = Math.sin(innerAngle);
  37661. // Create a vertex.
  37662. var normal = new BABYLON.Vector3(dx, dy, 0);
  37663. var position = normal.scale(thickness / 2);
  37664. var textureCoordinate = new BABYLON.Vector2(u, v);
  37665. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37666. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37667. positions.push(position.x, position.y, position.z);
  37668. normals.push(normal.x, normal.y, normal.z);
  37669. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37670. // And create indices for two triangles.
  37671. var nextI = (i + 1) % stride;
  37672. var nextJ = (j + 1) % stride;
  37673. indices.push(i * stride + j);
  37674. indices.push(i * stride + nextJ);
  37675. indices.push(nextI * stride + j);
  37676. indices.push(i * stride + nextJ);
  37677. indices.push(nextI * stride + nextJ);
  37678. indices.push(nextI * stride + j);
  37679. }
  37680. }
  37681. // Sides
  37682. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37683. // Result
  37684. var vertexData = new VertexData();
  37685. vertexData.indices = indices;
  37686. vertexData.positions = positions;
  37687. vertexData.normals = normals;
  37688. vertexData.uvs = uvs;
  37689. return vertexData;
  37690. };
  37691. /**
  37692. * Creates the VertexData of the LineSystem.
  37693. */
  37694. VertexData.CreateLineSystem = function (options) {
  37695. var indices = [];
  37696. var positions = [];
  37697. var lines = options.lines;
  37698. var idx = 0;
  37699. for (var l = 0; l < lines.length; l++) {
  37700. var points = lines[l];
  37701. for (var index = 0; index < points.length; index++) {
  37702. positions.push(points[index].x, points[index].y, points[index].z);
  37703. if (index > 0) {
  37704. indices.push(idx - 1);
  37705. indices.push(idx);
  37706. }
  37707. idx++;
  37708. }
  37709. }
  37710. var vertexData = new VertexData();
  37711. vertexData.indices = indices;
  37712. vertexData.positions = positions;
  37713. return vertexData;
  37714. };
  37715. /**
  37716. * Create the VertexData of the DashedLines.
  37717. */
  37718. VertexData.CreateDashedLines = function (options) {
  37719. var dashSize = options.dashSize || 3;
  37720. var gapSize = options.gapSize || 1;
  37721. var dashNb = options.dashNb || 200;
  37722. var points = options.points;
  37723. var positions = new Array();
  37724. var indices = new Array();
  37725. var curvect = BABYLON.Vector3.Zero();
  37726. var lg = 0;
  37727. var nb = 0;
  37728. var shft = 0;
  37729. var dashshft = 0;
  37730. var curshft = 0;
  37731. var idx = 0;
  37732. var i = 0;
  37733. for (i = 0; i < points.length - 1; i++) {
  37734. points[i + 1].subtractToRef(points[i], curvect);
  37735. lg += curvect.length();
  37736. }
  37737. shft = lg / dashNb;
  37738. dashshft = dashSize * shft / (dashSize + gapSize);
  37739. for (i = 0; i < points.length - 1; i++) {
  37740. points[i + 1].subtractToRef(points[i], curvect);
  37741. nb = Math.floor(curvect.length() / shft);
  37742. curvect.normalize();
  37743. for (var j = 0; j < nb; j++) {
  37744. curshft = shft * j;
  37745. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37746. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37747. indices.push(idx, idx + 1);
  37748. idx += 2;
  37749. }
  37750. }
  37751. // Result
  37752. var vertexData = new VertexData();
  37753. vertexData.positions = positions;
  37754. vertexData.indices = indices;
  37755. return vertexData;
  37756. };
  37757. /**
  37758. * Creates the VertexData of the Ground.
  37759. */
  37760. VertexData.CreateGround = function (options) {
  37761. var indices = [];
  37762. var positions = [];
  37763. var normals = [];
  37764. var uvs = [];
  37765. var row, col;
  37766. var width = options.width || 1;
  37767. var height = options.height || 1;
  37768. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37769. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37770. for (row = 0; row <= subdivisionsY; row++) {
  37771. for (col = 0; col <= subdivisionsX; col++) {
  37772. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37773. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37774. positions.push(position.x, position.y, position.z);
  37775. normals.push(normal.x, normal.y, normal.z);
  37776. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37777. }
  37778. }
  37779. for (row = 0; row < subdivisionsY; row++) {
  37780. for (col = 0; col < subdivisionsX; col++) {
  37781. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37782. indices.push(col + 1 + row * (subdivisionsX + 1));
  37783. indices.push(col + row * (subdivisionsX + 1));
  37784. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37785. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37786. indices.push(col + row * (subdivisionsX + 1));
  37787. }
  37788. }
  37789. // Result
  37790. var vertexData = new VertexData();
  37791. vertexData.indices = indices;
  37792. vertexData.positions = positions;
  37793. vertexData.normals = normals;
  37794. vertexData.uvs = uvs;
  37795. return vertexData;
  37796. };
  37797. /**
  37798. * Creates the VertexData of the TiledGround.
  37799. */
  37800. VertexData.CreateTiledGround = function (options) {
  37801. var xmin = options.xmin || -1.0;
  37802. var zmin = options.zmin || -1.0;
  37803. var xmax = options.xmax || 1.0;
  37804. var zmax = options.zmax || 1.0;
  37805. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37806. var precision = options.precision || { w: 1, h: 1 };
  37807. var indices = [];
  37808. var positions = [];
  37809. var normals = [];
  37810. var uvs = [];
  37811. var row, col, tileRow, tileCol;
  37812. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37813. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37814. precision.w = (precision.w < 1) ? 1 : precision.w;
  37815. precision.h = (precision.h < 1) ? 1 : precision.h;
  37816. var tileSize = {
  37817. 'w': (xmax - xmin) / subdivisions.w,
  37818. 'h': (zmax - zmin) / subdivisions.h
  37819. };
  37820. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37821. // Indices
  37822. var base = positions.length / 3;
  37823. var rowLength = precision.w + 1;
  37824. for (row = 0; row < precision.h; row++) {
  37825. for (col = 0; col < precision.w; col++) {
  37826. var square = [
  37827. base + col + row * rowLength,
  37828. base + (col + 1) + row * rowLength,
  37829. base + (col + 1) + (row + 1) * rowLength,
  37830. base + col + (row + 1) * rowLength
  37831. ];
  37832. indices.push(square[1]);
  37833. indices.push(square[2]);
  37834. indices.push(square[3]);
  37835. indices.push(square[0]);
  37836. indices.push(square[1]);
  37837. indices.push(square[3]);
  37838. }
  37839. }
  37840. // Position, normals and uvs
  37841. var position = BABYLON.Vector3.Zero();
  37842. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37843. for (row = 0; row <= precision.h; row++) {
  37844. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37845. for (col = 0; col <= precision.w; col++) {
  37846. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37847. position.y = 0;
  37848. positions.push(position.x, position.y, position.z);
  37849. normals.push(normal.x, normal.y, normal.z);
  37850. uvs.push(col / precision.w, row / precision.h);
  37851. }
  37852. }
  37853. }
  37854. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37855. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37856. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37857. }
  37858. }
  37859. // Result
  37860. var vertexData = new VertexData();
  37861. vertexData.indices = indices;
  37862. vertexData.positions = positions;
  37863. vertexData.normals = normals;
  37864. vertexData.uvs = uvs;
  37865. return vertexData;
  37866. };
  37867. /**
  37868. * Creates the VertexData of the Ground designed from a heightmap.
  37869. */
  37870. VertexData.CreateGroundFromHeightMap = function (options) {
  37871. var indices = [];
  37872. var positions = [];
  37873. var normals = [];
  37874. var uvs = [];
  37875. var row, col;
  37876. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37877. // Vertices
  37878. for (row = 0; row <= options.subdivisions; row++) {
  37879. for (col = 0; col <= options.subdivisions; col++) {
  37880. 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));
  37881. // Compute height
  37882. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37883. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37884. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37885. var r = options.buffer[pos] / 255.0;
  37886. var g = options.buffer[pos + 1] / 255.0;
  37887. var b = options.buffer[pos + 2] / 255.0;
  37888. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37889. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37890. // Add vertex
  37891. positions.push(position.x, position.y, position.z);
  37892. normals.push(0, 0, 0);
  37893. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37894. }
  37895. }
  37896. // Indices
  37897. for (row = 0; row < options.subdivisions; row++) {
  37898. for (col = 0; col < options.subdivisions; col++) {
  37899. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37900. indices.push(col + 1 + row * (options.subdivisions + 1));
  37901. indices.push(col + row * (options.subdivisions + 1));
  37902. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37903. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37904. indices.push(col + row * (options.subdivisions + 1));
  37905. }
  37906. }
  37907. // Normals
  37908. VertexData.ComputeNormals(positions, indices, normals);
  37909. // Result
  37910. var vertexData = new VertexData();
  37911. vertexData.indices = indices;
  37912. vertexData.positions = positions;
  37913. vertexData.normals = normals;
  37914. vertexData.uvs = uvs;
  37915. return vertexData;
  37916. };
  37917. /**
  37918. * Creates the VertexData of the Plane.
  37919. */
  37920. VertexData.CreatePlane = function (options) {
  37921. var indices = [];
  37922. var positions = [];
  37923. var normals = [];
  37924. var uvs = [];
  37925. var width = options.width || options.size || 1;
  37926. var height = options.height || options.size || 1;
  37927. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37928. // Vertices
  37929. var halfWidth = width / 2.0;
  37930. var halfHeight = height / 2.0;
  37931. positions.push(-halfWidth, -halfHeight, 0);
  37932. normals.push(0, 0, -1.0);
  37933. uvs.push(0.0, 0.0);
  37934. positions.push(halfWidth, -halfHeight, 0);
  37935. normals.push(0, 0, -1.0);
  37936. uvs.push(1.0, 0.0);
  37937. positions.push(halfWidth, halfHeight, 0);
  37938. normals.push(0, 0, -1.0);
  37939. uvs.push(1.0, 1.0);
  37940. positions.push(-halfWidth, halfHeight, 0);
  37941. normals.push(0, 0, -1.0);
  37942. uvs.push(0.0, 1.0);
  37943. // Indices
  37944. indices.push(0);
  37945. indices.push(1);
  37946. indices.push(2);
  37947. indices.push(0);
  37948. indices.push(2);
  37949. indices.push(3);
  37950. // Sides
  37951. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37952. // Result
  37953. var vertexData = new VertexData();
  37954. vertexData.indices = indices;
  37955. vertexData.positions = positions;
  37956. vertexData.normals = normals;
  37957. vertexData.uvs = uvs;
  37958. return vertexData;
  37959. };
  37960. /**
  37961. * Creates the VertexData of the Disc or regular Polygon.
  37962. */
  37963. VertexData.CreateDisc = function (options) {
  37964. var positions = [];
  37965. var indices = [];
  37966. var normals = [];
  37967. var uvs = [];
  37968. var radius = options.radius || 0.5;
  37969. var tessellation = options.tessellation || 64;
  37970. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37971. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37972. // positions and uvs
  37973. positions.push(0, 0, 0); // disc center first
  37974. uvs.push(0.5, 0.5);
  37975. var theta = Math.PI * 2 * arc;
  37976. var step = theta / tessellation;
  37977. for (var a = 0; a < theta; a += step) {
  37978. var x = Math.cos(a);
  37979. var y = Math.sin(a);
  37980. var u = (x + 1) / 2;
  37981. var v = (1 - y) / 2;
  37982. positions.push(radius * x, radius * y, 0);
  37983. uvs.push(u, v);
  37984. }
  37985. if (arc === 1) {
  37986. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37987. uvs.push(uvs[2], uvs[3]);
  37988. }
  37989. //indices
  37990. var vertexNb = positions.length / 3;
  37991. for (var i = 1; i < vertexNb - 1; i++) {
  37992. indices.push(i + 1, 0, i);
  37993. }
  37994. // result
  37995. VertexData.ComputeNormals(positions, indices, normals);
  37996. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37997. var vertexData = new VertexData();
  37998. vertexData.indices = indices;
  37999. vertexData.positions = positions;
  38000. vertexData.normals = normals;
  38001. vertexData.uvs = uvs;
  38002. return vertexData;
  38003. };
  38004. /**
  38005. * Creates the VertexData of the IcoSphere.
  38006. */
  38007. VertexData.CreateIcoSphere = function (options) {
  38008. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38009. var radius = options.radius || 1;
  38010. var flat = (options.flat === undefined) ? true : options.flat;
  38011. var subdivisions = options.subdivisions || 4;
  38012. var radiusX = options.radiusX || radius;
  38013. var radiusY = options.radiusY || radius;
  38014. var radiusZ = options.radiusZ || radius;
  38015. var t = (1 + Math.sqrt(5)) / 2;
  38016. // 12 vertex x,y,z
  38017. var ico_vertices = [
  38018. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38019. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38020. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38021. ];
  38022. // index of 3 vertex makes a face of icopshere
  38023. var ico_indices = [
  38024. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38025. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38026. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38027. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38028. ];
  38029. // vertex for uv have aliased position, not for UV
  38030. var vertices_unalias_id = [
  38031. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38032. // vertex alias
  38033. 0,
  38034. 2,
  38035. 3,
  38036. 3,
  38037. 3,
  38038. 4,
  38039. 7,
  38040. 8,
  38041. 9,
  38042. 9,
  38043. 10,
  38044. 11 // 23: B + 12
  38045. ];
  38046. // uv as integer step (not pixels !)
  38047. var ico_vertexuv = [
  38048. 5, 1, 3, 1, 6, 4, 0, 0,
  38049. 5, 3, 4, 2, 2, 2, 4, 0,
  38050. 2, 0, 1, 1, 6, 0, 6, 2,
  38051. // vertex alias (for same vertex on different faces)
  38052. 0, 4,
  38053. 3, 3,
  38054. 4, 4,
  38055. 3, 1,
  38056. 4, 2,
  38057. 4, 4,
  38058. 0, 2,
  38059. 1, 1,
  38060. 2, 2,
  38061. 3, 3,
  38062. 1, 3,
  38063. 2, 4 // 23: B + 12
  38064. ];
  38065. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38066. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38067. // First island of uv mapping
  38068. // v = 4h 3+ 2
  38069. // v = 3h 9+ 4
  38070. // v = 2h 9+ 5 B
  38071. // v = 1h 9 1 0
  38072. // v = 0h 3 8 7 A
  38073. // u = 0 1 2 3 4 5 6 *a
  38074. // Second island of uv mapping
  38075. // v = 4h 0+ B+ 4+
  38076. // v = 3h A+ 2+
  38077. // v = 2h 7+ 6 3+
  38078. // v = 1h 8+ 3+
  38079. // v = 0h
  38080. // u = 0 1 2 3 4 5 6 *a
  38081. // Face layout on texture UV mapping
  38082. // ============
  38083. // \ 4 /\ 16 / ======
  38084. // \ / \ / /\ 11 /
  38085. // \/ 7 \/ / \ /
  38086. // ======= / 10 \/
  38087. // /\ 17 /\ =======
  38088. // / \ / \ \ 15 /\
  38089. // / 8 \/ 12 \ \ / \
  38090. // ============ \/ 6 \
  38091. // \ 18 /\ ============
  38092. // \ / \ \ 5 /\ 0 /
  38093. // \/ 13 \ \ / \ /
  38094. // ======= \/ 1 \/
  38095. // =============
  38096. // /\ 19 /\ 2 /\
  38097. // / \ / \ / \
  38098. // / 14 \/ 9 \/ 3 \
  38099. // ===================
  38100. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38101. var ustep = 138 / 1024;
  38102. var vstep = 239 / 1024;
  38103. var uoffset = 60 / 1024;
  38104. var voffset = 26 / 1024;
  38105. // Second island should have margin, not to touch the first island
  38106. // avoid any borderline artefact in pixel rounding
  38107. var island_u_offset = -40 / 1024;
  38108. var island_v_offset = +20 / 1024;
  38109. // face is either island 0 or 1 :
  38110. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38111. var island = [
  38112. 0, 0, 0, 0, 1,
  38113. 0, 0, 1, 1, 0,
  38114. 0, 0, 1, 1, 0,
  38115. 0, 1, 1, 1, 0 // 15 - 19
  38116. ];
  38117. var indices = [];
  38118. var positions = [];
  38119. var normals = [];
  38120. var uvs = [];
  38121. var current_indice = 0;
  38122. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38123. var face_vertex_pos = new Array(3);
  38124. var face_vertex_uv = new Array(3);
  38125. var v012;
  38126. for (v012 = 0; v012 < 3; v012++) {
  38127. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38128. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38129. }
  38130. // create all with normals
  38131. for (var face = 0; face < 20; face++) {
  38132. // 3 vertex per face
  38133. for (v012 = 0; v012 < 3; v012++) {
  38134. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38135. var v_id = ico_indices[3 * face + v012];
  38136. // vertex have 3D position (x,y,z)
  38137. 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]);
  38138. // Normalize to get normal, then scale to radius
  38139. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38140. // uv Coordinates from vertex ID
  38141. 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);
  38142. }
  38143. // Subdivide the face (interpolate pos, norm, uv)
  38144. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38145. // - norm is linear interpolation of vertex corner normal
  38146. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38147. // - uv is linear interpolation
  38148. //
  38149. // Topology is as below for sub-divide by 2
  38150. // vertex shown as v0,v1,v2
  38151. // interp index is i1 to progress in range [v0,v1[
  38152. // interp index is i2 to progress in range [v0,v2[
  38153. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38154. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38155. //
  38156. //
  38157. // i2 v2
  38158. // ^ ^
  38159. // / / \
  38160. // / / \
  38161. // / / \
  38162. // / / (0,1) \
  38163. // / #---------\
  38164. // / / \ (0,0)'/ \
  38165. // / / \ / \
  38166. // / / \ / \
  38167. // / / (0,0) \ / (1,0) \
  38168. // / #---------#---------\
  38169. // v0 v1
  38170. //
  38171. // --------------------> i1
  38172. //
  38173. // interp of (i1,i2):
  38174. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38175. // along i1 : lerp(x0,x1, i1/(S-i2))
  38176. //
  38177. // centroid of triangle is needed to get help normal computation
  38178. // (c1,c2) are used for centroid location
  38179. var interp_vertex = function (i1, i2, c1, c2) {
  38180. // vertex is interpolated from
  38181. // - face_vertex_pos[0..2]
  38182. // - face_vertex_uv[0..2]
  38183. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38184. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38185. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38186. pos_interp.normalize();
  38187. var vertex_normal;
  38188. if (flat) {
  38189. // in flat mode, recalculate normal as face centroid normal
  38190. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38191. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38192. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38193. }
  38194. else {
  38195. // in smooth mode, recalculate normal from each single vertex position
  38196. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38197. }
  38198. // Vertex normal need correction due to X,Y,Z radius scaling
  38199. vertex_normal.x /= radiusX;
  38200. vertex_normal.y /= radiusY;
  38201. vertex_normal.z /= radiusZ;
  38202. vertex_normal.normalize();
  38203. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38204. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38205. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38206. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38207. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38208. uvs.push(uv_interp.x, uv_interp.y);
  38209. // push each vertex has member of a face
  38210. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38211. indices.push(current_indice);
  38212. current_indice++;
  38213. };
  38214. for (var i2 = 0; i2 < subdivisions; i2++) {
  38215. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38216. // face : (i1,i2) for /\ :
  38217. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38218. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38219. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38220. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38221. if (i1 + i2 + 1 < subdivisions) {
  38222. // face : (i1,i2)' for \/ :
  38223. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38224. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38225. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38226. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38227. }
  38228. }
  38229. }
  38230. }
  38231. // Sides
  38232. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38233. // Result
  38234. var vertexData = new VertexData();
  38235. vertexData.indices = indices;
  38236. vertexData.positions = positions;
  38237. vertexData.normals = normals;
  38238. vertexData.uvs = uvs;
  38239. return vertexData;
  38240. };
  38241. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38242. /**
  38243. * Creates the VertexData of the Polyhedron.
  38244. */
  38245. VertexData.CreatePolyhedron = function (options) {
  38246. // provided polyhedron types :
  38247. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38248. // 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)
  38249. var polyhedra = [];
  38250. 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]] };
  38251. 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]] };
  38252. polyhedra[2] = {
  38253. 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]],
  38254. 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]]
  38255. };
  38256. polyhedra[3] = {
  38257. 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]],
  38258. 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]]
  38259. };
  38260. polyhedra[4] = {
  38261. 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]],
  38262. 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]]
  38263. };
  38264. 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]] };
  38265. 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]] };
  38266. 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]] };
  38267. 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]] };
  38268. 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]] };
  38269. 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]] };
  38270. 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]] };
  38271. 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]] };
  38272. 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]] };
  38273. polyhedra[14] = {
  38274. 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]],
  38275. 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]]
  38276. };
  38277. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38278. var size = options.size;
  38279. var sizeX = options.sizeX || size || 1;
  38280. var sizeY = options.sizeY || size || 1;
  38281. var sizeZ = options.sizeZ || size || 1;
  38282. var data = options.custom || polyhedra[type];
  38283. var nbfaces = data.face.length;
  38284. var faceUV = options.faceUV || new Array(nbfaces);
  38285. var faceColors = options.faceColors;
  38286. var flat = (options.flat === undefined) ? true : options.flat;
  38287. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38288. var positions = [];
  38289. var indices = [];
  38290. var normals = [];
  38291. var uvs = [];
  38292. var colors = [];
  38293. var index = 0;
  38294. var faceIdx = 0; // face cursor in the array "indexes"
  38295. var indexes = [];
  38296. var i = 0;
  38297. var f = 0;
  38298. var u, v, ang, x, y, tmp;
  38299. // default face colors and UV if undefined
  38300. if (flat) {
  38301. for (f = 0; f < nbfaces; f++) {
  38302. if (faceColors && faceColors[f] === undefined) {
  38303. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38304. }
  38305. if (faceUV && faceUV[f] === undefined) {
  38306. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38307. }
  38308. }
  38309. }
  38310. if (!flat) {
  38311. for (i = 0; i < data.vertex.length; i++) {
  38312. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38313. uvs.push(0, 0);
  38314. }
  38315. for (f = 0; f < nbfaces; f++) {
  38316. for (i = 0; i < data.face[f].length - 2; i++) {
  38317. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38318. }
  38319. }
  38320. }
  38321. else {
  38322. for (f = 0; f < nbfaces; f++) {
  38323. var fl = data.face[f].length; // number of vertices of the current face
  38324. ang = 2 * Math.PI / fl;
  38325. x = 0.5 * Math.tan(ang / 2);
  38326. y = 0.5;
  38327. // positions, uvs, colors
  38328. for (i = 0; i < fl; i++) {
  38329. // positions
  38330. 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);
  38331. indexes.push(index);
  38332. index++;
  38333. // uvs
  38334. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38335. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38336. uvs.push(u, v);
  38337. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38338. y = x * Math.sin(ang) + y * Math.cos(ang);
  38339. x = tmp;
  38340. // colors
  38341. if (faceColors) {
  38342. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38343. }
  38344. }
  38345. // indices from indexes
  38346. for (i = 0; i < fl - 2; i++) {
  38347. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38348. }
  38349. faceIdx += fl;
  38350. }
  38351. }
  38352. VertexData.ComputeNormals(positions, indices, normals);
  38353. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38354. var vertexData = new VertexData();
  38355. vertexData.positions = positions;
  38356. vertexData.indices = indices;
  38357. vertexData.normals = normals;
  38358. vertexData.uvs = uvs;
  38359. if (faceColors && flat) {
  38360. vertexData.colors = colors;
  38361. }
  38362. return vertexData;
  38363. };
  38364. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38365. /**
  38366. * Creates the VertexData of the Torus Knot.
  38367. */
  38368. VertexData.CreateTorusKnot = function (options) {
  38369. var indices = [];
  38370. var positions = [];
  38371. var normals = [];
  38372. var uvs = [];
  38373. var radius = options.radius || 2;
  38374. var tube = options.tube || 0.5;
  38375. var radialSegments = options.radialSegments || 32;
  38376. var tubularSegments = options.tubularSegments || 32;
  38377. var p = options.p || 2;
  38378. var q = options.q || 3;
  38379. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38380. // Helper
  38381. var getPos = function (angle) {
  38382. var cu = Math.cos(angle);
  38383. var su = Math.sin(angle);
  38384. var quOverP = q / p * angle;
  38385. var cs = Math.cos(quOverP);
  38386. var tx = radius * (2 + cs) * 0.5 * cu;
  38387. var ty = radius * (2 + cs) * su * 0.5;
  38388. var tz = radius * Math.sin(quOverP) * 0.5;
  38389. return new BABYLON.Vector3(tx, ty, tz);
  38390. };
  38391. // Vertices
  38392. var i;
  38393. var j;
  38394. for (i = 0; i <= radialSegments; i++) {
  38395. var modI = i % radialSegments;
  38396. var u = modI / radialSegments * 2 * p * Math.PI;
  38397. var p1 = getPos(u);
  38398. var p2 = getPos(u + 0.01);
  38399. var tang = p2.subtract(p1);
  38400. var n = p2.add(p1);
  38401. var bitan = BABYLON.Vector3.Cross(tang, n);
  38402. n = BABYLON.Vector3.Cross(bitan, tang);
  38403. bitan.normalize();
  38404. n.normalize();
  38405. for (j = 0; j < tubularSegments; j++) {
  38406. var modJ = j % tubularSegments;
  38407. var v = modJ / tubularSegments * 2 * Math.PI;
  38408. var cx = -tube * Math.cos(v);
  38409. var cy = tube * Math.sin(v);
  38410. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38411. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38412. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38413. uvs.push(i / radialSegments);
  38414. uvs.push(j / tubularSegments);
  38415. }
  38416. }
  38417. for (i = 0; i < radialSegments; i++) {
  38418. for (j = 0; j < tubularSegments; j++) {
  38419. var jNext = (j + 1) % tubularSegments;
  38420. var a = i * tubularSegments + j;
  38421. var b = (i + 1) * tubularSegments + j;
  38422. var c = (i + 1) * tubularSegments + jNext;
  38423. var d = i * tubularSegments + jNext;
  38424. indices.push(d);
  38425. indices.push(b);
  38426. indices.push(a);
  38427. indices.push(d);
  38428. indices.push(c);
  38429. indices.push(b);
  38430. }
  38431. }
  38432. // Normals
  38433. VertexData.ComputeNormals(positions, indices, normals);
  38434. // Sides
  38435. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38436. // Result
  38437. var vertexData = new VertexData();
  38438. vertexData.indices = indices;
  38439. vertexData.positions = positions;
  38440. vertexData.normals = normals;
  38441. vertexData.uvs = uvs;
  38442. return vertexData;
  38443. };
  38444. // Tools
  38445. /**
  38446. * @param {any} - positions (number[] or Float32Array)
  38447. * @param {any} - indices (number[] or Uint16Array)
  38448. * @param {any} - normals (number[] or Float32Array)
  38449. * options (optional) :
  38450. * facetPositions : optional array of facet positions (vector3)
  38451. * facetNormals : optional array of facet normals (vector3)
  38452. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38453. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38454. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38455. * bbSize : optional bounding box size data, required for facetPartitioning computation
  38456. * bInfo : optional bounding info, required for facetPartitioning computation
  38457. */
  38458. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38459. // temporary scalar variables
  38460. var index = 0; // facet index
  38461. var p1p2x = 0.0; // p1p2 vector x coordinate
  38462. var p1p2y = 0.0; // p1p2 vector y coordinate
  38463. var p1p2z = 0.0; // p1p2 vector z coordinate
  38464. var p3p2x = 0.0; // p3p2 vector x coordinate
  38465. var p3p2y = 0.0; // p3p2 vector y coordinate
  38466. var p3p2z = 0.0; // p3p2 vector z coordinate
  38467. var faceNormalx = 0.0; // facet normal x coordinate
  38468. var faceNormaly = 0.0; // facet normal y coordinate
  38469. var faceNormalz = 0.0; // facet normal z coordinate
  38470. var length = 0.0; // facet normal length before normalization
  38471. var v1x = 0; // vector1 x index in the positions array
  38472. var v1y = 0; // vector1 y index in the positions array
  38473. var v1z = 0; // vector1 z index in the positions array
  38474. var v2x = 0; // vector2 x index in the positions array
  38475. var v2y = 0; // vector2 y index in the positions array
  38476. var v2z = 0; // vector2 z index in the positions array
  38477. var v3x = 0; // vector3 x index in the positions array
  38478. var v3y = 0; // vector3 y index in the positions array
  38479. var v3z = 0; // vector3 z index in the positions array
  38480. var computeFacetNormals = false;
  38481. var computeFacetPositions = false;
  38482. var computeFacetPartitioning = false;
  38483. if (options) {
  38484. computeFacetNormals = (options.facetNormals) ? true : false;
  38485. computeFacetPositions = (options.facetPositions) ? true : false;
  38486. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38487. }
  38488. // facetPartitioning reinit if needed
  38489. if (computeFacetPartitioning) {
  38490. var ox = 0; // X partitioning index for facet position
  38491. var oy = 0; // Y partinioning index for facet position
  38492. var oz = 0; // Z partinioning index for facet position
  38493. var b1x = 0; // X partitioning index for facet v1 vertex
  38494. var b1y = 0; // Y partitioning index for facet v1 vertex
  38495. var b1z = 0; // z partitioning index for facet v1 vertex
  38496. var b2x = 0; // X partitioning index for facet v2 vertex
  38497. var b2y = 0; // Y partitioning index for facet v2 vertex
  38498. var b2z = 0; // Z partitioning index for facet v2 vertex
  38499. var b3x = 0; // X partitioning index for facet v3 vertex
  38500. var b3y = 0; // Y partitioning index for facet v3 vertex
  38501. var b3z = 0; // Z partitioning index for facet v3 vertex
  38502. var block_idx_o = 0; // facet barycenter block index
  38503. var block_idx_v1 = 0; // v1 vertex block index
  38504. var block_idx_v2 = 0; // v2 vertex block index
  38505. var block_idx_v3 = 0; // v3 vertex block index
  38506. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38507. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38508. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  38509. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  38510. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  38511. var subSq = options.subDiv.max * options.subDiv.max;
  38512. options.facetPartitioning.length = 0;
  38513. }
  38514. // reset the normals
  38515. for (index = 0; index < positions.length; index++) {
  38516. normals[index] = 0.0;
  38517. }
  38518. // Loop : 1 indice triplet = 1 facet
  38519. var nbFaces = indices.length / 3;
  38520. for (index = 0; index < nbFaces; index++) {
  38521. // get the indexes of the coordinates of each vertex of the facet
  38522. v1x = indices[index * 3] * 3;
  38523. v1y = v1x + 1;
  38524. v1z = v1x + 2;
  38525. v2x = indices[index * 3 + 1] * 3;
  38526. v2y = v2x + 1;
  38527. v2z = v2x + 2;
  38528. v3x = indices[index * 3 + 2] * 3;
  38529. v3y = v3x + 1;
  38530. v3z = v3x + 2;
  38531. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38532. p1p2y = positions[v1y] - positions[v2y];
  38533. p1p2z = positions[v1z] - positions[v2z];
  38534. p3p2x = positions[v3x] - positions[v2x];
  38535. p3p2y = positions[v3y] - positions[v2y];
  38536. p3p2z = positions[v3z] - positions[v2z];
  38537. // compute the face normal with the cross product
  38538. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  38539. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  38540. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  38541. // normalize this normal and store it in the array facetData
  38542. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38543. length = (length === 0) ? 1.0 : length;
  38544. faceNormalx /= length;
  38545. faceNormaly /= length;
  38546. faceNormalz /= length;
  38547. if (computeFacetNormals) {
  38548. options.facetNormals[index].x = faceNormalx;
  38549. options.facetNormals[index].y = faceNormaly;
  38550. options.facetNormals[index].z = faceNormalz;
  38551. }
  38552. if (computeFacetPositions) {
  38553. // compute and the facet barycenter coordinates in the array facetPositions
  38554. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38555. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38556. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38557. }
  38558. if (computeFacetPartitioning) {
  38559. // store the facet indexes in arrays in the main facetPartitioning array :
  38560. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38561. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38562. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38563. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38564. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38565. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38566. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38567. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38568. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38569. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38570. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38571. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38572. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38573. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38574. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38575. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38576. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38577. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38578. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38579. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38580. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38581. // push each facet index in each block containing the vertex
  38582. options.facetPartitioning[block_idx_v1].push(index);
  38583. if (block_idx_v2 != block_idx_v1) {
  38584. options.facetPartitioning[block_idx_v2].push(index);
  38585. }
  38586. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38587. options.facetPartitioning[block_idx_v3].push(index);
  38588. }
  38589. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38590. options.facetPartitioning[block_idx_o].push(index);
  38591. }
  38592. }
  38593. // compute the normals anyway
  38594. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38595. normals[v1y] += faceNormaly;
  38596. normals[v1z] += faceNormalz;
  38597. normals[v2x] += faceNormalx;
  38598. normals[v2y] += faceNormaly;
  38599. normals[v2z] += faceNormalz;
  38600. normals[v3x] += faceNormalx;
  38601. normals[v3y] += faceNormaly;
  38602. normals[v3z] += faceNormalz;
  38603. }
  38604. // last normalization of each normal
  38605. for (index = 0; index < normals.length / 3; index++) {
  38606. faceNormalx = normals[index * 3];
  38607. faceNormaly = normals[index * 3 + 1];
  38608. faceNormalz = normals[index * 3 + 2];
  38609. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38610. length = (length === 0) ? 1.0 : length;
  38611. faceNormalx /= length;
  38612. faceNormaly /= length;
  38613. faceNormalz /= length;
  38614. normals[index * 3] = faceNormalx;
  38615. normals[index * 3 + 1] = faceNormaly;
  38616. normals[index * 3 + 2] = faceNormalz;
  38617. }
  38618. };
  38619. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  38620. var li = indices.length;
  38621. var ln = normals.length;
  38622. var i;
  38623. var n;
  38624. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38625. switch (sideOrientation) {
  38626. case BABYLON.Mesh.FRONTSIDE:
  38627. // nothing changed
  38628. break;
  38629. case BABYLON.Mesh.BACKSIDE:
  38630. var tmp;
  38631. // indices
  38632. for (i = 0; i < li; i += 3) {
  38633. tmp = indices[i];
  38634. indices[i] = indices[i + 2];
  38635. indices[i + 2] = tmp;
  38636. }
  38637. // normals
  38638. for (n = 0; n < ln; n++) {
  38639. normals[n] = -normals[n];
  38640. }
  38641. break;
  38642. case BABYLON.Mesh.DOUBLESIDE:
  38643. // positions
  38644. var lp = positions.length;
  38645. var l = lp / 3;
  38646. for (var p = 0; p < lp; p++) {
  38647. positions[lp + p] = positions[p];
  38648. }
  38649. // indices
  38650. for (i = 0; i < li; i += 3) {
  38651. indices[i + li] = indices[i + 2] + l;
  38652. indices[i + 1 + li] = indices[i + 1] + l;
  38653. indices[i + 2 + li] = indices[i] + l;
  38654. }
  38655. // normals
  38656. for (n = 0; n < ln; n++) {
  38657. normals[ln + n] = -normals[n];
  38658. }
  38659. // uvs
  38660. var lu = uvs.length;
  38661. for (var u = 0; u < lu; u++) {
  38662. uvs[u + lu] = uvs[u];
  38663. }
  38664. break;
  38665. }
  38666. };
  38667. /**
  38668. * Creates a new VertexData from the imported parameters.
  38669. */
  38670. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38671. var vertexData = new VertexData();
  38672. // positions
  38673. var positions = parsedVertexData.positions;
  38674. if (positions) {
  38675. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38676. }
  38677. // normals
  38678. var normals = parsedVertexData.normals;
  38679. if (normals) {
  38680. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38681. }
  38682. // tangents
  38683. var tangents = parsedVertexData.tangents;
  38684. if (tangents) {
  38685. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38686. }
  38687. // uvs
  38688. var uvs = parsedVertexData.uvs;
  38689. if (uvs) {
  38690. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38691. }
  38692. // uv2s
  38693. var uv2s = parsedVertexData.uv2s;
  38694. if (uv2s) {
  38695. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38696. }
  38697. // uv3s
  38698. var uv3s = parsedVertexData.uv3s;
  38699. if (uv3s) {
  38700. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38701. }
  38702. // uv4s
  38703. var uv4s = parsedVertexData.uv4s;
  38704. if (uv4s) {
  38705. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38706. }
  38707. // uv5s
  38708. var uv5s = parsedVertexData.uv5s;
  38709. if (uv5s) {
  38710. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38711. }
  38712. // uv6s
  38713. var uv6s = parsedVertexData.uv6s;
  38714. if (uv6s) {
  38715. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38716. }
  38717. // colors
  38718. var colors = parsedVertexData.colors;
  38719. if (colors) {
  38720. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38721. }
  38722. // matricesIndices
  38723. var matricesIndices = parsedVertexData.matricesIndices;
  38724. if (matricesIndices) {
  38725. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38726. }
  38727. // matricesWeights
  38728. var matricesWeights = parsedVertexData.matricesWeights;
  38729. if (matricesWeights) {
  38730. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38731. }
  38732. // indices
  38733. var indices = parsedVertexData.indices;
  38734. if (indices) {
  38735. vertexData.indices = indices;
  38736. }
  38737. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38738. };
  38739. return VertexData;
  38740. }());
  38741. BABYLON.VertexData = VertexData;
  38742. })(BABYLON || (BABYLON = {}));
  38743. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38744. var BABYLON;
  38745. (function (BABYLON) {
  38746. var Tags = (function () {
  38747. function Tags() {
  38748. }
  38749. Tags.EnableFor = function (obj) {
  38750. obj._tags = obj._tags || {};
  38751. obj.hasTags = function () {
  38752. return Tags.HasTags(obj);
  38753. };
  38754. obj.addTags = function (tagsString) {
  38755. return Tags.AddTagsTo(obj, tagsString);
  38756. };
  38757. obj.removeTags = function (tagsString) {
  38758. return Tags.RemoveTagsFrom(obj, tagsString);
  38759. };
  38760. obj.matchesTagsQuery = function (tagsQuery) {
  38761. return Tags.MatchesQuery(obj, tagsQuery);
  38762. };
  38763. };
  38764. Tags.DisableFor = function (obj) {
  38765. delete obj._tags;
  38766. delete obj.hasTags;
  38767. delete obj.addTags;
  38768. delete obj.removeTags;
  38769. delete obj.matchesTagsQuery;
  38770. };
  38771. Tags.HasTags = function (obj) {
  38772. if (!obj._tags) {
  38773. return false;
  38774. }
  38775. return !BABYLON.Tools.IsEmpty(obj._tags);
  38776. };
  38777. Tags.GetTags = function (obj, asString) {
  38778. if (asString === void 0) { asString = true; }
  38779. if (!obj._tags) {
  38780. return null;
  38781. }
  38782. if (asString) {
  38783. var tagsArray = [];
  38784. for (var tag in obj._tags) {
  38785. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  38786. tagsArray.push(tag);
  38787. }
  38788. }
  38789. return tagsArray.join(" ");
  38790. }
  38791. else {
  38792. return obj._tags;
  38793. }
  38794. };
  38795. // the tags 'true' and 'false' are reserved and cannot be used as tags
  38796. // a tag cannot start with '||', '&&', and '!'
  38797. // it cannot contain whitespaces
  38798. Tags.AddTagsTo = function (obj, tagsString) {
  38799. if (!tagsString) {
  38800. return;
  38801. }
  38802. if (typeof tagsString !== "string") {
  38803. return;
  38804. }
  38805. var tags = tagsString.split(" ");
  38806. tags.forEach(function (tag, index, array) {
  38807. Tags._AddTagTo(obj, tag);
  38808. });
  38809. };
  38810. Tags._AddTagTo = function (obj, tag) {
  38811. tag = tag.trim();
  38812. if (tag === "" || tag === "true" || tag === "false") {
  38813. return;
  38814. }
  38815. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  38816. return;
  38817. }
  38818. Tags.EnableFor(obj);
  38819. obj._tags[tag] = true;
  38820. };
  38821. Tags.RemoveTagsFrom = function (obj, tagsString) {
  38822. if (!Tags.HasTags(obj)) {
  38823. return;
  38824. }
  38825. var tags = tagsString.split(" ");
  38826. for (var t in tags) {
  38827. Tags._RemoveTagFrom(obj, tags[t]);
  38828. }
  38829. };
  38830. Tags._RemoveTagFrom = function (obj, tag) {
  38831. delete obj._tags[tag];
  38832. };
  38833. Tags.MatchesQuery = function (obj, tagsQuery) {
  38834. if (tagsQuery === undefined) {
  38835. return true;
  38836. }
  38837. if (tagsQuery === "") {
  38838. return Tags.HasTags(obj);
  38839. }
  38840. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  38841. };
  38842. return Tags;
  38843. }());
  38844. BABYLON.Tags = Tags;
  38845. })(BABYLON || (BABYLON = {}));
  38846. //# sourceMappingURL=babylon.tags.js.map
  38847. var BABYLON;
  38848. (function (BABYLON) {
  38849. var Internals;
  38850. (function (Internals) {
  38851. var AndOrNotEvaluator = (function () {
  38852. function AndOrNotEvaluator() {
  38853. }
  38854. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  38855. if (!query.match(/\([^\(\)]*\)/g)) {
  38856. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  38857. }
  38858. else {
  38859. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  38860. // remove parenthesis
  38861. r = r.slice(1, r.length - 1);
  38862. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  38863. });
  38864. }
  38865. if (query === "true") {
  38866. return true;
  38867. }
  38868. if (query === "false") {
  38869. return false;
  38870. }
  38871. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  38872. };
  38873. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  38874. evaluateCallback = evaluateCallback || (function (r) {
  38875. return r === "true" ? true : false;
  38876. });
  38877. var result;
  38878. var or = parenthesisContent.split("||");
  38879. for (var i in or) {
  38880. if (or.hasOwnProperty(i)) {
  38881. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  38882. var and = ori.split("&&");
  38883. if (and.length > 1) {
  38884. for (var j = 0; j < and.length; ++j) {
  38885. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  38886. if (andj !== "true" && andj !== "false") {
  38887. if (andj[0] === "!") {
  38888. result = !evaluateCallback(andj.substring(1));
  38889. }
  38890. else {
  38891. result = evaluateCallback(andj);
  38892. }
  38893. }
  38894. else {
  38895. result = andj === "true" ? true : false;
  38896. }
  38897. if (!result) {
  38898. ori = "false";
  38899. break;
  38900. }
  38901. }
  38902. }
  38903. if (result || ori === "true") {
  38904. result = true;
  38905. break;
  38906. }
  38907. // result equals false (or undefined)
  38908. if (ori !== "true" && ori !== "false") {
  38909. if (ori[0] === "!") {
  38910. result = !evaluateCallback(ori.substring(1));
  38911. }
  38912. else {
  38913. result = evaluateCallback(ori);
  38914. }
  38915. }
  38916. else {
  38917. result = ori === "true" ? true : false;
  38918. }
  38919. }
  38920. }
  38921. // the whole parenthesis scope is replaced by 'true' or 'false'
  38922. return result ? "true" : "false";
  38923. };
  38924. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  38925. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  38926. // remove whitespaces
  38927. r = r.replace(/[\s]/g, function () { return ""; });
  38928. return r.length % 2 ? "!" : "";
  38929. });
  38930. booleanString = booleanString.trim();
  38931. if (booleanString === "!true") {
  38932. booleanString = "false";
  38933. }
  38934. else if (booleanString === "!false") {
  38935. booleanString = "true";
  38936. }
  38937. return booleanString;
  38938. };
  38939. return AndOrNotEvaluator;
  38940. }());
  38941. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  38942. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38943. })(BABYLON || (BABYLON = {}));
  38944. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  38945. var BABYLON;
  38946. (function (BABYLON) {
  38947. var PostProcessRenderPass = (function () {
  38948. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  38949. this._enabled = true;
  38950. this._refCount = 0;
  38951. this._name = name;
  38952. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  38953. this.setRenderList(renderList);
  38954. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  38955. this._renderTexture.onAfterRenderObservable.add(afterRender);
  38956. this._scene = scene;
  38957. this._renderList = renderList;
  38958. }
  38959. // private
  38960. PostProcessRenderPass.prototype._incRefCount = function () {
  38961. if (this._refCount === 0) {
  38962. this._scene.customRenderTargets.push(this._renderTexture);
  38963. }
  38964. return ++this._refCount;
  38965. };
  38966. PostProcessRenderPass.prototype._decRefCount = function () {
  38967. this._refCount--;
  38968. if (this._refCount <= 0) {
  38969. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  38970. }
  38971. return this._refCount;
  38972. };
  38973. PostProcessRenderPass.prototype._update = function () {
  38974. this.setRenderList(this._renderList);
  38975. };
  38976. // public
  38977. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  38978. this._renderTexture.renderList = renderList;
  38979. };
  38980. PostProcessRenderPass.prototype.getRenderTexture = function () {
  38981. return this._renderTexture;
  38982. };
  38983. return PostProcessRenderPass;
  38984. }());
  38985. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  38986. })(BABYLON || (BABYLON = {}));
  38987. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  38988. var BABYLON;
  38989. (function (BABYLON) {
  38990. var PostProcessRenderEffect = (function () {
  38991. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  38992. this._engine = engine;
  38993. this._name = name;
  38994. this._singleInstance = singleInstance || true;
  38995. this._getPostProcess = getPostProcess;
  38996. this._cameras = [];
  38997. this._indicesForCamera = [];
  38998. this._postProcesses = {};
  38999. this._renderPasses = {};
  39000. this._renderEffectAsPasses = {};
  39001. }
  39002. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  39003. get: function () {
  39004. for (var index in this._postProcesses) {
  39005. if (!this._postProcesses[index].isSupported) {
  39006. return false;
  39007. }
  39008. }
  39009. return true;
  39010. },
  39011. enumerable: true,
  39012. configurable: true
  39013. });
  39014. PostProcessRenderEffect.prototype._update = function () {
  39015. for (var renderPassName in this._renderPasses) {
  39016. this._renderPasses[renderPassName]._update();
  39017. }
  39018. };
  39019. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  39020. this._renderPasses[renderPass._name] = renderPass;
  39021. this._linkParameters();
  39022. };
  39023. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  39024. delete this._renderPasses[renderPass._name];
  39025. this._linkParameters();
  39026. };
  39027. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  39028. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  39029. this._linkParameters();
  39030. };
  39031. PostProcessRenderEffect.prototype.getPass = function (passName) {
  39032. for (var renderPassName in this._renderPasses) {
  39033. if (renderPassName === passName) {
  39034. return this._renderPasses[passName];
  39035. }
  39036. }
  39037. };
  39038. PostProcessRenderEffect.prototype.emptyPasses = function () {
  39039. this._renderPasses = {};
  39040. this._linkParameters();
  39041. };
  39042. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  39043. var cameraKey;
  39044. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39045. for (var i = 0; i < _cam.length; i++) {
  39046. var camera = _cam[i];
  39047. var cameraName = camera.name;
  39048. if (this._singleInstance) {
  39049. cameraKey = 0;
  39050. }
  39051. else {
  39052. cameraKey = cameraName;
  39053. }
  39054. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  39055. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  39056. if (!this._indicesForCamera[cameraName]) {
  39057. this._indicesForCamera[cameraName] = [];
  39058. }
  39059. this._indicesForCamera[cameraName].push(index);
  39060. if (this._cameras.indexOf(camera) === -1) {
  39061. this._cameras[cameraName] = camera;
  39062. }
  39063. for (var passName in this._renderPasses) {
  39064. this._renderPasses[passName]._incRefCount();
  39065. }
  39066. }
  39067. this._linkParameters();
  39068. };
  39069. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  39070. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39071. for (var i = 0; i < _cam.length; i++) {
  39072. var camera = _cam[i];
  39073. var cameraName = camera.name;
  39074. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39075. var index = this._cameras.indexOf(cameraName);
  39076. this._indicesForCamera.splice(index, 1);
  39077. this._cameras.splice(index, 1);
  39078. for (var passName in this._renderPasses) {
  39079. this._renderPasses[passName]._decRefCount();
  39080. }
  39081. }
  39082. };
  39083. PostProcessRenderEffect.prototype._enable = function (cameras) {
  39084. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39085. for (var i = 0; i < _cam.length; i++) {
  39086. var camera = _cam[i];
  39087. var cameraName = camera.name;
  39088. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  39089. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  39090. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  39091. }
  39092. }
  39093. for (var passName in this._renderPasses) {
  39094. this._renderPasses[passName]._incRefCount();
  39095. }
  39096. }
  39097. };
  39098. PostProcessRenderEffect.prototype._disable = function (cameras) {
  39099. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39100. for (var i = 0; i < _cam.length; i++) {
  39101. var camera = _cam[i];
  39102. var cameraName = camera.Name;
  39103. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39104. for (var passName in this._renderPasses) {
  39105. this._renderPasses[passName]._decRefCount();
  39106. }
  39107. }
  39108. };
  39109. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  39110. if (this._singleInstance) {
  39111. return this._postProcesses[0];
  39112. }
  39113. else {
  39114. return this._postProcesses[camera.name];
  39115. }
  39116. };
  39117. PostProcessRenderEffect.prototype._linkParameters = function () {
  39118. var _this = this;
  39119. for (var index in this._postProcesses) {
  39120. if (this.applyParameters) {
  39121. this.applyParameters(this._postProcesses[index]);
  39122. }
  39123. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  39124. _this._linkTextures(effect);
  39125. });
  39126. }
  39127. };
  39128. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  39129. for (var renderPassName in this._renderPasses) {
  39130. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  39131. }
  39132. for (var renderEffectName in this._renderEffectAsPasses) {
  39133. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  39134. }
  39135. };
  39136. return PostProcessRenderEffect;
  39137. }());
  39138. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  39139. })(BABYLON || (BABYLON = {}));
  39140. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  39141. var BABYLON;
  39142. (function (BABYLON) {
  39143. var PostProcessRenderPipeline = (function () {
  39144. function PostProcessRenderPipeline(engine, name) {
  39145. this._engine = engine;
  39146. this._name = name;
  39147. this._renderEffects = {};
  39148. this._renderEffectsForIsolatedPass = {};
  39149. this._cameras = [];
  39150. }
  39151. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  39152. get: function () {
  39153. for (var renderEffectName in this._renderEffects) {
  39154. if (!this._renderEffects[renderEffectName].isSupported) {
  39155. return false;
  39156. }
  39157. }
  39158. return true;
  39159. },
  39160. enumerable: true,
  39161. configurable: true
  39162. });
  39163. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  39164. this._renderEffects[renderEffect._name] = renderEffect;
  39165. };
  39166. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  39167. var renderEffects = this._renderEffects[renderEffectName];
  39168. if (!renderEffects) {
  39169. return;
  39170. }
  39171. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39172. };
  39173. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  39174. var renderEffects = this._renderEffects[renderEffectName];
  39175. if (!renderEffects) {
  39176. return;
  39177. }
  39178. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39179. };
  39180. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  39181. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39182. var indicesToDelete = [];
  39183. var i;
  39184. for (i = 0; i < _cam.length; i++) {
  39185. var camera = _cam[i];
  39186. var cameraName = camera.name;
  39187. if (this._cameras.indexOf(camera) === -1) {
  39188. this._cameras[cameraName] = camera;
  39189. }
  39190. else if (unique) {
  39191. indicesToDelete.push(i);
  39192. }
  39193. }
  39194. for (i = 0; i < indicesToDelete.length; i++) {
  39195. cameras.splice(indicesToDelete[i], 1);
  39196. }
  39197. for (var renderEffectName in this._renderEffects) {
  39198. this._renderEffects[renderEffectName]._attachCameras(_cam);
  39199. }
  39200. };
  39201. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  39202. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39203. for (var renderEffectName in this._renderEffects) {
  39204. this._renderEffects[renderEffectName]._detachCameras(_cam);
  39205. }
  39206. for (var i = 0; i < _cam.length; i++) {
  39207. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  39208. }
  39209. };
  39210. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  39211. var _this = this;
  39212. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39213. var pass = null;
  39214. var renderEffectName;
  39215. for (renderEffectName in this._renderEffects) {
  39216. pass = this._renderEffects[renderEffectName].getPass(passName);
  39217. if (pass != null) {
  39218. break;
  39219. }
  39220. }
  39221. if (pass === null) {
  39222. return;
  39223. }
  39224. for (renderEffectName in this._renderEffects) {
  39225. this._renderEffects[renderEffectName]._disable(_cam);
  39226. }
  39227. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  39228. for (var i = 0; i < _cam.length; i++) {
  39229. var camera = _cam[i];
  39230. var cameraName = camera.name;
  39231. 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); });
  39232. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  39233. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  39234. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  39235. }
  39236. };
  39237. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  39238. var _this = this;
  39239. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39240. for (var i = 0; i < _cam.length; i++) {
  39241. var camera = _cam[i];
  39242. var cameraName = camera.name;
  39243. 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); });
  39244. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  39245. }
  39246. for (var renderEffectName in this._renderEffects) {
  39247. this._renderEffects[renderEffectName]._enable(_cam);
  39248. }
  39249. };
  39250. PostProcessRenderPipeline.prototype._update = function () {
  39251. for (var renderEffectName in this._renderEffects) {
  39252. this._renderEffects[renderEffectName]._update();
  39253. }
  39254. for (var i = 0; i < this._cameras.length; i++) {
  39255. var cameraName = this._cameras[i].name;
  39256. if (this._renderEffectsForIsolatedPass[cameraName]) {
  39257. this._renderEffectsForIsolatedPass[cameraName]._update();
  39258. }
  39259. }
  39260. };
  39261. PostProcessRenderPipeline.prototype.dispose = function () {
  39262. // Must be implemented by children
  39263. };
  39264. return PostProcessRenderPipeline;
  39265. }());
  39266. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  39267. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  39268. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  39269. })(BABYLON || (BABYLON = {}));
  39270. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  39271. var BABYLON;
  39272. (function (BABYLON) {
  39273. var PostProcessRenderPipelineManager = (function () {
  39274. function PostProcessRenderPipelineManager() {
  39275. this._renderPipelines = {};
  39276. }
  39277. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  39278. this._renderPipelines[renderPipeline._name] = renderPipeline;
  39279. };
  39280. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  39281. var renderPipeline = this._renderPipelines[renderPipelineName];
  39282. if (!renderPipeline) {
  39283. return;
  39284. }
  39285. renderPipeline._attachCameras(cameras, unique);
  39286. };
  39287. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  39288. var renderPipeline = this._renderPipelines[renderPipelineName];
  39289. if (!renderPipeline) {
  39290. return;
  39291. }
  39292. renderPipeline._detachCameras(cameras);
  39293. };
  39294. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39295. var renderPipeline = this._renderPipelines[renderPipelineName];
  39296. if (!renderPipeline) {
  39297. return;
  39298. }
  39299. renderPipeline._enableEffect(renderEffectName, cameras);
  39300. };
  39301. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39302. var renderPipeline = this._renderPipelines[renderPipelineName];
  39303. if (!renderPipeline) {
  39304. return;
  39305. }
  39306. renderPipeline._disableEffect(renderEffectName, cameras);
  39307. };
  39308. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  39309. var renderPipeline = this._renderPipelines[renderPipelineName];
  39310. if (!renderPipeline) {
  39311. return;
  39312. }
  39313. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  39314. };
  39315. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  39316. var renderPipeline = this._renderPipelines[renderPipelineName];
  39317. if (!renderPipeline) {
  39318. return;
  39319. }
  39320. renderPipeline._disableDisplayOnlyPass(cameras);
  39321. };
  39322. PostProcessRenderPipelineManager.prototype.update = function () {
  39323. for (var renderPipelineName in this._renderPipelines) {
  39324. var pipeline = this._renderPipelines[renderPipelineName];
  39325. if (!pipeline.isSupported) {
  39326. pipeline.dispose();
  39327. delete this._renderPipelines[renderPipelineName];
  39328. }
  39329. else {
  39330. pipeline._update();
  39331. }
  39332. }
  39333. };
  39334. return PostProcessRenderPipelineManager;
  39335. }());
  39336. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  39337. })(BABYLON || (BABYLON = {}));
  39338. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  39339. var BABYLON;
  39340. (function (BABYLON) {
  39341. var BoundingBoxRenderer = (function () {
  39342. function BoundingBoxRenderer(scene) {
  39343. this.frontColor = new BABYLON.Color3(1, 1, 1);
  39344. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  39345. this.showBackLines = true;
  39346. this.renderList = new BABYLON.SmartArray(32);
  39347. this._vertexBuffers = {};
  39348. this._scene = scene;
  39349. }
  39350. BoundingBoxRenderer.prototype._prepareRessources = function () {
  39351. if (this._colorShader) {
  39352. return;
  39353. }
  39354. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  39355. attributes: [BABYLON.VertexBuffer.PositionKind],
  39356. uniforms: ["worldViewProjection", "color"]
  39357. });
  39358. var engine = this._scene.getEngine();
  39359. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  39360. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  39361. this._indexBuffer = 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]);
  39362. };
  39363. BoundingBoxRenderer.prototype.reset = function () {
  39364. this.renderList.reset();
  39365. };
  39366. BoundingBoxRenderer.prototype.render = function () {
  39367. if (this.renderList.length === 0) {
  39368. return;
  39369. }
  39370. this._prepareRessources();
  39371. if (!this._colorShader.isReady()) {
  39372. return;
  39373. }
  39374. var engine = this._scene.getEngine();
  39375. engine.setDepthWrite(false);
  39376. this._colorShader._preBind();
  39377. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  39378. var boundingBox = this.renderList.data[boundingBoxIndex];
  39379. var min = boundingBox.minimum;
  39380. var max = boundingBox.maximum;
  39381. var diff = max.subtract(min);
  39382. var median = min.add(diff.scale(0.5));
  39383. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  39384. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  39385. .multiply(boundingBox.getWorldMatrix());
  39386. // VBOs
  39387. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  39388. if (this.showBackLines) {
  39389. // Back
  39390. engine.setDepthFunctionToGreaterOrEqual();
  39391. this._scene.resetCachedMaterial();
  39392. this._colorShader.setColor4("color", this.backColor.toColor4());
  39393. this._colorShader.bind(worldMatrix);
  39394. // Draw order
  39395. engine.draw(false, 0, 24);
  39396. }
  39397. // Front
  39398. engine.setDepthFunctionToLess();
  39399. this._scene.resetCachedMaterial();
  39400. this._colorShader.setColor4("color", this.frontColor.toColor4());
  39401. this._colorShader.bind(worldMatrix);
  39402. // Draw order
  39403. engine.draw(false, 0, 24);
  39404. }
  39405. this._colorShader.unbind();
  39406. engine.setDepthFunctionToLessOrEqual();
  39407. engine.setDepthWrite(true);
  39408. };
  39409. BoundingBoxRenderer.prototype.dispose = function () {
  39410. if (!this._colorShader) {
  39411. return;
  39412. }
  39413. this.renderList.dispose();
  39414. this._colorShader.dispose();
  39415. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39416. if (buffer) {
  39417. buffer.dispose();
  39418. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39419. }
  39420. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39421. };
  39422. return BoundingBoxRenderer;
  39423. }());
  39424. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  39425. })(BABYLON || (BABYLON = {}));
  39426. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  39427. var BABYLON;
  39428. (function (BABYLON) {
  39429. var Condition = (function () {
  39430. function Condition(actionManager) {
  39431. this._actionManager = actionManager;
  39432. }
  39433. Condition.prototype.isValid = function () {
  39434. return true;
  39435. };
  39436. Condition.prototype._getProperty = function (propertyPath) {
  39437. return this._actionManager._getProperty(propertyPath);
  39438. };
  39439. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  39440. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39441. };
  39442. Condition.prototype.serialize = function () {
  39443. };
  39444. Condition.prototype._serialize = function (serializedCondition) {
  39445. return {
  39446. type: 2,
  39447. children: [],
  39448. name: serializedCondition.name,
  39449. properties: serializedCondition.properties
  39450. };
  39451. };
  39452. return Condition;
  39453. }());
  39454. BABYLON.Condition = Condition;
  39455. var ValueCondition = (function (_super) {
  39456. __extends(ValueCondition, _super);
  39457. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  39458. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  39459. var _this = _super.call(this, actionManager) || this;
  39460. _this.propertyPath = propertyPath;
  39461. _this.value = value;
  39462. _this.operator = operator;
  39463. _this._target = target;
  39464. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  39465. _this._property = _this._getProperty(_this.propertyPath);
  39466. return _this;
  39467. }
  39468. Object.defineProperty(ValueCondition, "IsEqual", {
  39469. get: function () {
  39470. return ValueCondition._IsEqual;
  39471. },
  39472. enumerable: true,
  39473. configurable: true
  39474. });
  39475. Object.defineProperty(ValueCondition, "IsDifferent", {
  39476. get: function () {
  39477. return ValueCondition._IsDifferent;
  39478. },
  39479. enumerable: true,
  39480. configurable: true
  39481. });
  39482. Object.defineProperty(ValueCondition, "IsGreater", {
  39483. get: function () {
  39484. return ValueCondition._IsGreater;
  39485. },
  39486. enumerable: true,
  39487. configurable: true
  39488. });
  39489. Object.defineProperty(ValueCondition, "IsLesser", {
  39490. get: function () {
  39491. return ValueCondition._IsLesser;
  39492. },
  39493. enumerable: true,
  39494. configurable: true
  39495. });
  39496. // Methods
  39497. ValueCondition.prototype.isValid = function () {
  39498. switch (this.operator) {
  39499. case ValueCondition.IsGreater:
  39500. return this._effectiveTarget[this._property] > this.value;
  39501. case ValueCondition.IsLesser:
  39502. return this._effectiveTarget[this._property] < this.value;
  39503. case ValueCondition.IsEqual:
  39504. case ValueCondition.IsDifferent:
  39505. var check;
  39506. if (this.value.equals) {
  39507. check = this.value.equals(this._effectiveTarget[this._property]);
  39508. }
  39509. else {
  39510. check = this.value === this._effectiveTarget[this._property];
  39511. }
  39512. return this.operator === ValueCondition.IsEqual ? check : !check;
  39513. }
  39514. return false;
  39515. };
  39516. ValueCondition.prototype.serialize = function () {
  39517. return this._serialize({
  39518. name: "ValueCondition",
  39519. properties: [
  39520. BABYLON.Action._GetTargetProperty(this._target),
  39521. { name: "propertyPath", value: this.propertyPath },
  39522. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39523. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  39524. ]
  39525. });
  39526. };
  39527. ValueCondition.GetOperatorName = function (operator) {
  39528. switch (operator) {
  39529. case ValueCondition._IsEqual: return "IsEqual";
  39530. case ValueCondition._IsDifferent: return "IsDifferent";
  39531. case ValueCondition._IsGreater: return "IsGreater";
  39532. case ValueCondition._IsLesser: return "IsLesser";
  39533. default: return "";
  39534. }
  39535. };
  39536. return ValueCondition;
  39537. }(Condition));
  39538. // Statics
  39539. ValueCondition._IsEqual = 0;
  39540. ValueCondition._IsDifferent = 1;
  39541. ValueCondition._IsGreater = 2;
  39542. ValueCondition._IsLesser = 3;
  39543. BABYLON.ValueCondition = ValueCondition;
  39544. var PredicateCondition = (function (_super) {
  39545. __extends(PredicateCondition, _super);
  39546. function PredicateCondition(actionManager, predicate) {
  39547. var _this = _super.call(this, actionManager) || this;
  39548. _this.predicate = predicate;
  39549. return _this;
  39550. }
  39551. PredicateCondition.prototype.isValid = function () {
  39552. return this.predicate();
  39553. };
  39554. return PredicateCondition;
  39555. }(Condition));
  39556. BABYLON.PredicateCondition = PredicateCondition;
  39557. var StateCondition = (function (_super) {
  39558. __extends(StateCondition, _super);
  39559. function StateCondition(actionManager, target, value) {
  39560. var _this = _super.call(this, actionManager) || this;
  39561. _this.value = value;
  39562. _this._target = target;
  39563. return _this;
  39564. }
  39565. // Methods
  39566. StateCondition.prototype.isValid = function () {
  39567. return this._target.state === this.value;
  39568. };
  39569. StateCondition.prototype.serialize = function () {
  39570. return this._serialize({
  39571. name: "StateCondition",
  39572. properties: [
  39573. BABYLON.Action._GetTargetProperty(this._target),
  39574. { name: "value", value: this.value }
  39575. ]
  39576. });
  39577. };
  39578. return StateCondition;
  39579. }(Condition));
  39580. BABYLON.StateCondition = StateCondition;
  39581. })(BABYLON || (BABYLON = {}));
  39582. //# sourceMappingURL=babylon.condition.js.map
  39583. var BABYLON;
  39584. (function (BABYLON) {
  39585. var Action = (function () {
  39586. function Action(triggerOptions, condition) {
  39587. this.triggerOptions = triggerOptions;
  39588. if (triggerOptions.parameter) {
  39589. this.trigger = triggerOptions.trigger;
  39590. this._triggerParameter = triggerOptions.parameter;
  39591. }
  39592. else {
  39593. this.trigger = triggerOptions;
  39594. }
  39595. this._nextActiveAction = this;
  39596. this._condition = condition;
  39597. }
  39598. // Methods
  39599. Action.prototype._prepare = function () {
  39600. };
  39601. Action.prototype.getTriggerParameter = function () {
  39602. return this._triggerParameter;
  39603. };
  39604. Action.prototype._executeCurrent = function (evt) {
  39605. if (this._nextActiveAction._condition) {
  39606. var condition = this._nextActiveAction._condition;
  39607. var currentRenderId = this._actionManager.getScene().getRenderId();
  39608. // We cache the current evaluation for the current frame
  39609. if (condition._evaluationId === currentRenderId) {
  39610. if (!condition._currentResult) {
  39611. return;
  39612. }
  39613. }
  39614. else {
  39615. condition._evaluationId = currentRenderId;
  39616. if (!condition.isValid()) {
  39617. condition._currentResult = false;
  39618. return;
  39619. }
  39620. condition._currentResult = true;
  39621. }
  39622. }
  39623. this._nextActiveAction.execute(evt);
  39624. this.skipToNextActiveAction();
  39625. };
  39626. Action.prototype.execute = function (evt) {
  39627. };
  39628. Action.prototype.skipToNextActiveAction = function () {
  39629. if (this._nextActiveAction._child) {
  39630. if (!this._nextActiveAction._child._actionManager) {
  39631. this._nextActiveAction._child._actionManager = this._actionManager;
  39632. }
  39633. this._nextActiveAction = this._nextActiveAction._child;
  39634. }
  39635. else {
  39636. this._nextActiveAction = this;
  39637. }
  39638. };
  39639. Action.prototype.then = function (action) {
  39640. this._child = action;
  39641. action._actionManager = this._actionManager;
  39642. action._prepare();
  39643. return action;
  39644. };
  39645. Action.prototype._getProperty = function (propertyPath) {
  39646. return this._actionManager._getProperty(propertyPath);
  39647. };
  39648. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  39649. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39650. };
  39651. Action.prototype.serialize = function (parent) {
  39652. };
  39653. // Called by BABYLON.Action objects in serialize(...). Internal use
  39654. Action.prototype._serialize = function (serializedAction, parent) {
  39655. var serializationObject = {
  39656. type: 1,
  39657. children: [],
  39658. name: serializedAction.name,
  39659. properties: serializedAction.properties || []
  39660. };
  39661. // Serialize child
  39662. if (this._child) {
  39663. this._child.serialize(serializationObject);
  39664. }
  39665. // Check if "this" has a condition
  39666. if (this._condition) {
  39667. var serializedCondition = this._condition.serialize();
  39668. serializedCondition.children.push(serializationObject);
  39669. if (parent) {
  39670. parent.children.push(serializedCondition);
  39671. }
  39672. return serializedCondition;
  39673. }
  39674. if (parent) {
  39675. parent.children.push(serializationObject);
  39676. }
  39677. return serializationObject;
  39678. };
  39679. return Action;
  39680. }());
  39681. Action._SerializeValueAsString = function (value) {
  39682. if (typeof value === "number") {
  39683. return value.toString();
  39684. }
  39685. if (typeof value === "boolean") {
  39686. return value ? "true" : "false";
  39687. }
  39688. if (value instanceof BABYLON.Vector2) {
  39689. return value.x + ", " + value.y;
  39690. }
  39691. if (value instanceof BABYLON.Vector3) {
  39692. return value.x + ", " + value.y + ", " + value.z;
  39693. }
  39694. if (value instanceof BABYLON.Color3) {
  39695. return value.r + ", " + value.g + ", " + value.b;
  39696. }
  39697. if (value instanceof BABYLON.Color4) {
  39698. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  39699. }
  39700. return value; // string
  39701. };
  39702. Action._GetTargetProperty = function (target) {
  39703. return {
  39704. name: "target",
  39705. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  39706. : target instanceof BABYLON.Light ? "LightProperties"
  39707. : target instanceof BABYLON.Camera ? "CameraProperties"
  39708. : "SceneProperties",
  39709. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  39710. };
  39711. };
  39712. BABYLON.Action = Action;
  39713. })(BABYLON || (BABYLON = {}));
  39714. //# sourceMappingURL=babylon.action.js.map
  39715. var BABYLON;
  39716. (function (BABYLON) {
  39717. /**
  39718. * ActionEvent is the event beint sent when an action is triggered.
  39719. */
  39720. var ActionEvent = (function () {
  39721. /**
  39722. * @constructor
  39723. * @param source The mesh or sprite that triggered the action.
  39724. * @param pointerX The X mouse cursor position at the time of the event
  39725. * @param pointerY The Y mouse cursor position at the time of the event
  39726. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  39727. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  39728. */
  39729. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  39730. this.source = source;
  39731. this.pointerX = pointerX;
  39732. this.pointerY = pointerY;
  39733. this.meshUnderPointer = meshUnderPointer;
  39734. this.sourceEvent = sourceEvent;
  39735. this.additionalData = additionalData;
  39736. }
  39737. /**
  39738. * Helper function to auto-create an ActionEvent from a source mesh.
  39739. * @param source The source mesh that triggered the event
  39740. * @param evt {Event} The original (browser) event
  39741. */
  39742. ActionEvent.CreateNew = function (source, evt, additionalData) {
  39743. var scene = source.getScene();
  39744. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  39745. };
  39746. /**
  39747. * Helper function to auto-create an ActionEvent from a source mesh.
  39748. * @param source The source sprite that triggered the event
  39749. * @param scene Scene associated with the sprite
  39750. * @param evt {Event} The original (browser) event
  39751. */
  39752. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  39753. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  39754. };
  39755. /**
  39756. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  39757. * @param scene the scene where the event occurred
  39758. * @param evt {Event} The original (browser) event
  39759. */
  39760. ActionEvent.CreateNewFromScene = function (scene, evt) {
  39761. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  39762. };
  39763. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  39764. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  39765. };
  39766. return ActionEvent;
  39767. }());
  39768. BABYLON.ActionEvent = ActionEvent;
  39769. /**
  39770. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  39771. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  39772. */
  39773. var ActionManager = (function () {
  39774. function ActionManager(scene) {
  39775. // Members
  39776. this.actions = new Array();
  39777. this.hoverCursor = '';
  39778. this._scene = scene;
  39779. scene._actionManagers.push(this);
  39780. }
  39781. Object.defineProperty(ActionManager, "NothingTrigger", {
  39782. get: function () {
  39783. return ActionManager._NothingTrigger;
  39784. },
  39785. enumerable: true,
  39786. configurable: true
  39787. });
  39788. Object.defineProperty(ActionManager, "OnPickTrigger", {
  39789. get: function () {
  39790. return ActionManager._OnPickTrigger;
  39791. },
  39792. enumerable: true,
  39793. configurable: true
  39794. });
  39795. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  39796. get: function () {
  39797. return ActionManager._OnLeftPickTrigger;
  39798. },
  39799. enumerable: true,
  39800. configurable: true
  39801. });
  39802. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  39803. get: function () {
  39804. return ActionManager._OnRightPickTrigger;
  39805. },
  39806. enumerable: true,
  39807. configurable: true
  39808. });
  39809. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  39810. get: function () {
  39811. return ActionManager._OnCenterPickTrigger;
  39812. },
  39813. enumerable: true,
  39814. configurable: true
  39815. });
  39816. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  39817. get: function () {
  39818. return ActionManager._OnPickDownTrigger;
  39819. },
  39820. enumerable: true,
  39821. configurable: true
  39822. });
  39823. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  39824. get: function () {
  39825. return ActionManager._OnDoublePickTrigger;
  39826. },
  39827. enumerable: true,
  39828. configurable: true
  39829. });
  39830. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  39831. get: function () {
  39832. return ActionManager._OnPickUpTrigger;
  39833. },
  39834. enumerable: true,
  39835. configurable: true
  39836. });
  39837. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  39838. /// This trigger will only be raised if you also declared a OnPickDown
  39839. get: function () {
  39840. return ActionManager._OnPickOutTrigger;
  39841. },
  39842. enumerable: true,
  39843. configurable: true
  39844. });
  39845. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  39846. get: function () {
  39847. return ActionManager._OnLongPressTrigger;
  39848. },
  39849. enumerable: true,
  39850. configurable: true
  39851. });
  39852. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  39853. get: function () {
  39854. return ActionManager._OnPointerOverTrigger;
  39855. },
  39856. enumerable: true,
  39857. configurable: true
  39858. });
  39859. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  39860. get: function () {
  39861. return ActionManager._OnPointerOutTrigger;
  39862. },
  39863. enumerable: true,
  39864. configurable: true
  39865. });
  39866. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  39867. get: function () {
  39868. return ActionManager._OnEveryFrameTrigger;
  39869. },
  39870. enumerable: true,
  39871. configurable: true
  39872. });
  39873. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  39874. get: function () {
  39875. return ActionManager._OnIntersectionEnterTrigger;
  39876. },
  39877. enumerable: true,
  39878. configurable: true
  39879. });
  39880. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  39881. get: function () {
  39882. return ActionManager._OnIntersectionExitTrigger;
  39883. },
  39884. enumerable: true,
  39885. configurable: true
  39886. });
  39887. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  39888. get: function () {
  39889. return ActionManager._OnKeyDownTrigger;
  39890. },
  39891. enumerable: true,
  39892. configurable: true
  39893. });
  39894. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  39895. get: function () {
  39896. return ActionManager._OnKeyUpTrigger;
  39897. },
  39898. enumerable: true,
  39899. configurable: true
  39900. });
  39901. // Methods
  39902. ActionManager.prototype.dispose = function () {
  39903. var index = this._scene._actionManagers.indexOf(this);
  39904. for (var i = 0; i < this.actions.length; i++) {
  39905. var action = this.actions[i];
  39906. ActionManager.Triggers[action.trigger]--;
  39907. if (ActionManager.Triggers[action.trigger] === 0) {
  39908. delete ActionManager.Triggers[action.trigger];
  39909. }
  39910. }
  39911. if (index > -1) {
  39912. this._scene._actionManagers.splice(index, 1);
  39913. }
  39914. };
  39915. ActionManager.prototype.getScene = function () {
  39916. return this._scene;
  39917. };
  39918. /**
  39919. * Does this action manager handles actions of any of the given triggers
  39920. * @param {number[]} triggers - the triggers to be tested
  39921. * @return {boolean} whether one (or more) of the triggers is handeled
  39922. */
  39923. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  39924. for (var index = 0; index < this.actions.length; index++) {
  39925. var action = this.actions[index];
  39926. if (triggers.indexOf(action.trigger) > -1) {
  39927. return true;
  39928. }
  39929. }
  39930. return false;
  39931. };
  39932. /**
  39933. * Does this action manager handles actions of a given trigger
  39934. * @param {number} trigger - the trigger to be tested
  39935. * @return {boolean} whether the trigger is handeled
  39936. */
  39937. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  39938. for (var index = 0; index < this.actions.length; index++) {
  39939. var action = this.actions[index];
  39940. if (action.trigger === trigger) {
  39941. return true;
  39942. }
  39943. }
  39944. return false;
  39945. };
  39946. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  39947. /**
  39948. * Does this action manager has pointer triggers
  39949. * @return {boolean} whether or not it has pointer triggers
  39950. */
  39951. get: function () {
  39952. for (var index = 0; index < this.actions.length; index++) {
  39953. var action = this.actions[index];
  39954. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  39955. return true;
  39956. }
  39957. }
  39958. return false;
  39959. },
  39960. enumerable: true,
  39961. configurable: true
  39962. });
  39963. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  39964. /**
  39965. * Does this action manager has pick triggers
  39966. * @return {boolean} whether or not it has pick triggers
  39967. */
  39968. get: function () {
  39969. for (var index = 0; index < this.actions.length; index++) {
  39970. var action = this.actions[index];
  39971. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  39972. return true;
  39973. }
  39974. }
  39975. return false;
  39976. },
  39977. enumerable: true,
  39978. configurable: true
  39979. });
  39980. Object.defineProperty(ActionManager, "HasTriggers", {
  39981. /**
  39982. * Does exist one action manager with at least one trigger
  39983. * @return {boolean} whether or not it exists one action manager with one trigger
  39984. **/
  39985. get: function () {
  39986. for (var t in ActionManager.Triggers) {
  39987. if (ActionManager.Triggers.hasOwnProperty(t)) {
  39988. return true;
  39989. }
  39990. }
  39991. return false;
  39992. },
  39993. enumerable: true,
  39994. configurable: true
  39995. });
  39996. Object.defineProperty(ActionManager, "HasPickTriggers", {
  39997. /**
  39998. * Does exist one action manager with at least one pick trigger
  39999. * @return {boolean} whether or not it exists one action manager with one pick trigger
  40000. **/
  40001. get: function () {
  40002. for (var t in ActionManager.Triggers) {
  40003. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40004. var t_int = parseInt(t);
  40005. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  40006. return true;
  40007. }
  40008. }
  40009. }
  40010. return false;
  40011. },
  40012. enumerable: true,
  40013. configurable: true
  40014. });
  40015. /**
  40016. * Does exist one action manager that handles actions of a given trigger
  40017. * @param {number} trigger - the trigger to be tested
  40018. * @return {boolean} whether the trigger is handeled by at least one action manager
  40019. **/
  40020. ActionManager.HasSpecificTrigger = function (trigger) {
  40021. for (var t in ActionManager.Triggers) {
  40022. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40023. var t_int = parseInt(t);
  40024. if (t_int === trigger) {
  40025. return true;
  40026. }
  40027. }
  40028. }
  40029. return false;
  40030. };
  40031. /**
  40032. * Registers an action to this action manager
  40033. * @param {BABYLON.Action} action - the action to be registered
  40034. * @return {BABYLON.Action} the action amended (prepared) after registration
  40035. */
  40036. ActionManager.prototype.registerAction = function (action) {
  40037. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  40038. if (this.getScene().actionManager !== this) {
  40039. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  40040. return null;
  40041. }
  40042. }
  40043. this.actions.push(action);
  40044. if (ActionManager.Triggers[action.trigger]) {
  40045. ActionManager.Triggers[action.trigger]++;
  40046. }
  40047. else {
  40048. ActionManager.Triggers[action.trigger] = 1;
  40049. }
  40050. action._actionManager = this;
  40051. action._prepare();
  40052. return action;
  40053. };
  40054. /**
  40055. * Process a specific trigger
  40056. * @param {number} trigger - the trigger to process
  40057. * @param evt {BABYLON.ActionEvent} the event details to be processed
  40058. */
  40059. ActionManager.prototype.processTrigger = function (trigger, evt) {
  40060. for (var index = 0; index < this.actions.length; index++) {
  40061. var action = this.actions[index];
  40062. if (action.trigger === trigger) {
  40063. if (trigger === ActionManager.OnKeyUpTrigger
  40064. || trigger === ActionManager.OnKeyDownTrigger) {
  40065. var parameter = action.getTriggerParameter();
  40066. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  40067. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  40068. var actualkey = String.fromCharCode(unicode).toLowerCase();
  40069. if (actualkey !== parameter.toLowerCase()) {
  40070. continue;
  40071. }
  40072. }
  40073. }
  40074. action._executeCurrent(evt);
  40075. }
  40076. }
  40077. };
  40078. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  40079. var properties = propertyPath.split(".");
  40080. for (var index = 0; index < properties.length - 1; index++) {
  40081. target = target[properties[index]];
  40082. }
  40083. return target;
  40084. };
  40085. ActionManager.prototype._getProperty = function (propertyPath) {
  40086. var properties = propertyPath.split(".");
  40087. return properties[properties.length - 1];
  40088. };
  40089. ActionManager.prototype.serialize = function (name) {
  40090. var root = {
  40091. children: [],
  40092. name: name,
  40093. type: 3,
  40094. properties: [] // Empty for root but required
  40095. };
  40096. for (var i = 0; i < this.actions.length; i++) {
  40097. var triggerObject = {
  40098. type: 0,
  40099. children: [],
  40100. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  40101. properties: []
  40102. };
  40103. var triggerOptions = this.actions[i].triggerOptions;
  40104. if (triggerOptions && typeof triggerOptions !== "number") {
  40105. if (triggerOptions.parameter instanceof BABYLON.Node) {
  40106. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  40107. }
  40108. else {
  40109. var parameter = {};
  40110. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  40111. if (triggerOptions.parameter.mesh) {
  40112. parameter._meshId = triggerOptions.parameter.mesh.id;
  40113. }
  40114. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  40115. }
  40116. }
  40117. // Serialize child action, recursively
  40118. this.actions[i].serialize(triggerObject);
  40119. // Add serialized trigger
  40120. root.children.push(triggerObject);
  40121. }
  40122. return root;
  40123. };
  40124. ActionManager.Parse = function (parsedActions, object, scene) {
  40125. var actionManager = new BABYLON.ActionManager(scene);
  40126. if (object === null)
  40127. scene.actionManager = actionManager;
  40128. else
  40129. object.actionManager = actionManager;
  40130. // instanciate a new object
  40131. var instanciate = function (name, params) {
  40132. var newInstance = Object.create(BABYLON[name].prototype);
  40133. newInstance.constructor.apply(newInstance, params);
  40134. return newInstance;
  40135. };
  40136. var parseParameter = function (name, value, target, propertyPath) {
  40137. if (propertyPath === null) {
  40138. // String, boolean or float
  40139. var floatValue = parseFloat(value);
  40140. if (value === "true" || value === "false")
  40141. return value === "true";
  40142. else
  40143. return isNaN(floatValue) ? value : floatValue;
  40144. }
  40145. var effectiveTarget = propertyPath.split(".");
  40146. var values = value.split(",");
  40147. // Get effective Target
  40148. for (var i = 0; i < effectiveTarget.length; i++) {
  40149. target = target[effectiveTarget[i]];
  40150. }
  40151. // Return appropriate value with its type
  40152. if (typeof (target) === "boolean")
  40153. return values[0] === "true";
  40154. if (typeof (target) === "string")
  40155. return values[0];
  40156. // Parameters with multiple values such as Vector3 etc.
  40157. var split = new Array();
  40158. for (var i = 0; i < values.length; i++)
  40159. split.push(parseFloat(values[i]));
  40160. if (target instanceof BABYLON.Vector3)
  40161. return BABYLON.Vector3.FromArray(split);
  40162. if (target instanceof BABYLON.Vector4)
  40163. return BABYLON.Vector4.FromArray(split);
  40164. if (target instanceof BABYLON.Color3)
  40165. return BABYLON.Color3.FromArray(split);
  40166. if (target instanceof BABYLON.Color4)
  40167. return BABYLON.Color4.FromArray(split);
  40168. return parseFloat(values[0]);
  40169. };
  40170. // traverse graph per trigger
  40171. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  40172. if (combineArray === void 0) { combineArray = null; }
  40173. if (parsedAction.detached)
  40174. return;
  40175. var parameters = new Array();
  40176. var target = null;
  40177. var propertyPath = null;
  40178. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  40179. // Parameters
  40180. if (parsedAction.type === 2)
  40181. parameters.push(actionManager);
  40182. else
  40183. parameters.push(trigger);
  40184. if (combine) {
  40185. var actions = new Array();
  40186. for (var j = 0; j < parsedAction.combine.length; j++) {
  40187. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  40188. }
  40189. parameters.push(actions);
  40190. }
  40191. else {
  40192. for (var i = 0; i < parsedAction.properties.length; i++) {
  40193. var value = parsedAction.properties[i].value;
  40194. var name = parsedAction.properties[i].name;
  40195. var targetType = parsedAction.properties[i].targetType;
  40196. if (name === "target")
  40197. if (targetType !== null && targetType === "SceneProperties")
  40198. value = target = scene;
  40199. else
  40200. value = target = scene.getNodeByName(value);
  40201. else if (name === "parent")
  40202. value = scene.getNodeByName(value);
  40203. else if (name === "sound")
  40204. value = scene.getSoundByName(value);
  40205. else if (name !== "propertyPath") {
  40206. if (parsedAction.type === 2 && name === "operator")
  40207. value = BABYLON.ValueCondition[value];
  40208. else
  40209. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  40210. }
  40211. else {
  40212. propertyPath = value;
  40213. }
  40214. parameters.push(value);
  40215. }
  40216. }
  40217. if (combineArray === null) {
  40218. parameters.push(condition);
  40219. }
  40220. else {
  40221. parameters.push(null);
  40222. }
  40223. // If interpolate value action
  40224. if (parsedAction.name === "InterpolateValueAction") {
  40225. var param = parameters[parameters.length - 2];
  40226. parameters[parameters.length - 1] = param;
  40227. parameters[parameters.length - 2] = condition;
  40228. }
  40229. // Action or condition(s) and not CombineAction
  40230. var newAction = instanciate(parsedAction.name, parameters);
  40231. if (newAction instanceof BABYLON.Condition && condition !== null) {
  40232. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  40233. if (action)
  40234. action.then(nothing);
  40235. else
  40236. actionManager.registerAction(nothing);
  40237. action = nothing;
  40238. }
  40239. if (combineArray === null) {
  40240. if (newAction instanceof BABYLON.Condition) {
  40241. condition = newAction;
  40242. newAction = action;
  40243. }
  40244. else {
  40245. condition = null;
  40246. if (action)
  40247. action.then(newAction);
  40248. else
  40249. actionManager.registerAction(newAction);
  40250. }
  40251. }
  40252. else {
  40253. combineArray.push(newAction);
  40254. }
  40255. for (var i = 0; i < parsedAction.children.length; i++)
  40256. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  40257. };
  40258. // triggers
  40259. for (var i = 0; i < parsedActions.children.length; i++) {
  40260. var triggerParams;
  40261. var trigger = parsedActions.children[i];
  40262. if (trigger.properties.length > 0) {
  40263. var param = trigger.properties[0].value;
  40264. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  40265. if (value._meshId) {
  40266. value.mesh = scene.getMeshByID(value._meshId);
  40267. }
  40268. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  40269. }
  40270. else
  40271. triggerParams = BABYLON.ActionManager[trigger.name];
  40272. for (var j = 0; j < trigger.children.length; j++) {
  40273. if (!trigger.detached)
  40274. traverse(trigger.children[j], triggerParams, null, null);
  40275. }
  40276. }
  40277. };
  40278. ActionManager.GetTriggerName = function (trigger) {
  40279. switch (trigger) {
  40280. case 0: return "NothingTrigger";
  40281. case 1: return "OnPickTrigger";
  40282. case 2: return "OnLeftPickTrigger";
  40283. case 3: return "OnRightPickTrigger";
  40284. case 4: return "OnCenterPickTrigger";
  40285. case 5: return "OnPickDownTrigger";
  40286. case 6: return "OnPickUpTrigger";
  40287. case 7: return "OnLongPressTrigger";
  40288. case 8: return "OnPointerOverTrigger";
  40289. case 9: return "OnPointerOutTrigger";
  40290. case 10: return "OnEveryFrameTrigger";
  40291. case 11: return "OnIntersectionEnterTrigger";
  40292. case 12: return "OnIntersectionExitTrigger";
  40293. case 13: return "OnKeyDownTrigger";
  40294. case 14: return "OnKeyUpTrigger";
  40295. case 15: return "OnPickOutTrigger";
  40296. default: return "";
  40297. }
  40298. };
  40299. return ActionManager;
  40300. }());
  40301. // Statics
  40302. ActionManager._NothingTrigger = 0;
  40303. ActionManager._OnPickTrigger = 1;
  40304. ActionManager._OnLeftPickTrigger = 2;
  40305. ActionManager._OnRightPickTrigger = 3;
  40306. ActionManager._OnCenterPickTrigger = 4;
  40307. ActionManager._OnPickDownTrigger = 5;
  40308. ActionManager._OnDoublePickTrigger = 6;
  40309. ActionManager._OnPickUpTrigger = 7;
  40310. ActionManager._OnLongPressTrigger = 8;
  40311. ActionManager._OnPointerOverTrigger = 9;
  40312. ActionManager._OnPointerOutTrigger = 10;
  40313. ActionManager._OnEveryFrameTrigger = 11;
  40314. ActionManager._OnIntersectionEnterTrigger = 12;
  40315. ActionManager._OnIntersectionExitTrigger = 13;
  40316. ActionManager._OnKeyDownTrigger = 14;
  40317. ActionManager._OnKeyUpTrigger = 15;
  40318. ActionManager._OnPickOutTrigger = 16;
  40319. ActionManager.Triggers = {};
  40320. BABYLON.ActionManager = ActionManager;
  40321. })(BABYLON || (BABYLON = {}));
  40322. //# sourceMappingURL=babylon.actionManager.js.map
  40323. var BABYLON;
  40324. (function (BABYLON) {
  40325. var InterpolateValueAction = (function (_super) {
  40326. __extends(InterpolateValueAction, _super);
  40327. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  40328. if (duration === void 0) { duration = 1000; }
  40329. var _this = _super.call(this, triggerOptions, condition) || this;
  40330. _this.propertyPath = propertyPath;
  40331. _this.value = value;
  40332. _this.duration = duration;
  40333. _this.stopOtherAnimations = stopOtherAnimations;
  40334. _this.onInterpolationDone = onInterpolationDone;
  40335. _this._target = _this._effectiveTarget = target;
  40336. return _this;
  40337. }
  40338. InterpolateValueAction.prototype._prepare = function () {
  40339. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40340. this._property = this._getProperty(this.propertyPath);
  40341. };
  40342. InterpolateValueAction.prototype.execute = function () {
  40343. var scene = this._actionManager.getScene();
  40344. var keys = [
  40345. {
  40346. frame: 0,
  40347. value: this._effectiveTarget[this._property]
  40348. }, {
  40349. frame: 100,
  40350. value: this.value
  40351. }
  40352. ];
  40353. var dataType;
  40354. if (typeof this.value === "number") {
  40355. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  40356. }
  40357. else if (this.value instanceof BABYLON.Color3) {
  40358. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  40359. }
  40360. else if (this.value instanceof BABYLON.Vector3) {
  40361. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  40362. }
  40363. else if (this.value instanceof BABYLON.Matrix) {
  40364. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  40365. }
  40366. else if (this.value instanceof BABYLON.Quaternion) {
  40367. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  40368. }
  40369. else {
  40370. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  40371. return;
  40372. }
  40373. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40374. animation.setKeys(keys);
  40375. if (this.stopOtherAnimations) {
  40376. scene.stopAnimation(this._effectiveTarget);
  40377. }
  40378. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  40379. };
  40380. InterpolateValueAction.prototype.serialize = function (parent) {
  40381. return _super.prototype._serialize.call(this, {
  40382. name: "InterpolateValueAction",
  40383. properties: [
  40384. BABYLON.Action._GetTargetProperty(this._target),
  40385. { name: "propertyPath", value: this.propertyPath },
  40386. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  40387. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  40388. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  40389. ]
  40390. }, parent);
  40391. };
  40392. return InterpolateValueAction;
  40393. }(BABYLON.Action));
  40394. BABYLON.InterpolateValueAction = InterpolateValueAction;
  40395. })(BABYLON || (BABYLON = {}));
  40396. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  40397. var BABYLON;
  40398. (function (BABYLON) {
  40399. var SwitchBooleanAction = (function (_super) {
  40400. __extends(SwitchBooleanAction, _super);
  40401. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  40402. var _this = _super.call(this, triggerOptions, condition) || this;
  40403. _this.propertyPath = propertyPath;
  40404. _this._target = _this._effectiveTarget = target;
  40405. return _this;
  40406. }
  40407. SwitchBooleanAction.prototype._prepare = function () {
  40408. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40409. this._property = this._getProperty(this.propertyPath);
  40410. };
  40411. SwitchBooleanAction.prototype.execute = function () {
  40412. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  40413. };
  40414. SwitchBooleanAction.prototype.serialize = function (parent) {
  40415. return _super.prototype._serialize.call(this, {
  40416. name: "SwitchBooleanAction",
  40417. properties: [
  40418. BABYLON.Action._GetTargetProperty(this._target),
  40419. { name: "propertyPath", value: this.propertyPath }
  40420. ]
  40421. }, parent);
  40422. };
  40423. return SwitchBooleanAction;
  40424. }(BABYLON.Action));
  40425. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  40426. var SetStateAction = (function (_super) {
  40427. __extends(SetStateAction, _super);
  40428. function SetStateAction(triggerOptions, target, value, condition) {
  40429. var _this = _super.call(this, triggerOptions, condition) || this;
  40430. _this.value = value;
  40431. _this._target = target;
  40432. return _this;
  40433. }
  40434. SetStateAction.prototype.execute = function () {
  40435. this._target.state = this.value;
  40436. };
  40437. SetStateAction.prototype.serialize = function (parent) {
  40438. return _super.prototype._serialize.call(this, {
  40439. name: "SetStateAction",
  40440. properties: [
  40441. BABYLON.Action._GetTargetProperty(this._target),
  40442. { name: "value", value: this.value }
  40443. ]
  40444. }, parent);
  40445. };
  40446. return SetStateAction;
  40447. }(BABYLON.Action));
  40448. BABYLON.SetStateAction = SetStateAction;
  40449. var SetValueAction = (function (_super) {
  40450. __extends(SetValueAction, _super);
  40451. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  40452. var _this = _super.call(this, triggerOptions, condition) || this;
  40453. _this.propertyPath = propertyPath;
  40454. _this.value = value;
  40455. _this._target = _this._effectiveTarget = target;
  40456. return _this;
  40457. }
  40458. SetValueAction.prototype._prepare = function () {
  40459. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40460. this._property = this._getProperty(this.propertyPath);
  40461. };
  40462. SetValueAction.prototype.execute = function () {
  40463. this._effectiveTarget[this._property] = this.value;
  40464. if (this._target.markAsDirty) {
  40465. this._target.markAsDirty(this._property);
  40466. }
  40467. };
  40468. SetValueAction.prototype.serialize = function (parent) {
  40469. return _super.prototype._serialize.call(this, {
  40470. name: "SetValueAction",
  40471. properties: [
  40472. BABYLON.Action._GetTargetProperty(this._target),
  40473. { name: "propertyPath", value: this.propertyPath },
  40474. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40475. ]
  40476. }, parent);
  40477. };
  40478. return SetValueAction;
  40479. }(BABYLON.Action));
  40480. BABYLON.SetValueAction = SetValueAction;
  40481. var IncrementValueAction = (function (_super) {
  40482. __extends(IncrementValueAction, _super);
  40483. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  40484. var _this = _super.call(this, triggerOptions, condition) || this;
  40485. _this.propertyPath = propertyPath;
  40486. _this.value = value;
  40487. _this._target = _this._effectiveTarget = target;
  40488. return _this;
  40489. }
  40490. IncrementValueAction.prototype._prepare = function () {
  40491. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40492. this._property = this._getProperty(this.propertyPath);
  40493. if (typeof this._effectiveTarget[this._property] !== "number") {
  40494. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  40495. }
  40496. };
  40497. IncrementValueAction.prototype.execute = function () {
  40498. this._effectiveTarget[this._property] += this.value;
  40499. if (this._target.markAsDirty) {
  40500. this._target.markAsDirty(this._property);
  40501. }
  40502. };
  40503. IncrementValueAction.prototype.serialize = function (parent) {
  40504. return _super.prototype._serialize.call(this, {
  40505. name: "IncrementValueAction",
  40506. properties: [
  40507. BABYLON.Action._GetTargetProperty(this._target),
  40508. { name: "propertyPath", value: this.propertyPath },
  40509. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40510. ]
  40511. }, parent);
  40512. };
  40513. return IncrementValueAction;
  40514. }(BABYLON.Action));
  40515. BABYLON.IncrementValueAction = IncrementValueAction;
  40516. var PlayAnimationAction = (function (_super) {
  40517. __extends(PlayAnimationAction, _super);
  40518. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  40519. var _this = _super.call(this, triggerOptions, condition) || this;
  40520. _this.from = from;
  40521. _this.to = to;
  40522. _this.loop = loop;
  40523. _this._target = target;
  40524. return _this;
  40525. }
  40526. PlayAnimationAction.prototype._prepare = function () {
  40527. };
  40528. PlayAnimationAction.prototype.execute = function () {
  40529. var scene = this._actionManager.getScene();
  40530. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  40531. };
  40532. PlayAnimationAction.prototype.serialize = function (parent) {
  40533. return _super.prototype._serialize.call(this, {
  40534. name: "PlayAnimationAction",
  40535. properties: [
  40536. BABYLON.Action._GetTargetProperty(this._target),
  40537. { name: "from", value: String(this.from) },
  40538. { name: "to", value: String(this.to) },
  40539. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  40540. ]
  40541. }, parent);
  40542. };
  40543. return PlayAnimationAction;
  40544. }(BABYLON.Action));
  40545. BABYLON.PlayAnimationAction = PlayAnimationAction;
  40546. var StopAnimationAction = (function (_super) {
  40547. __extends(StopAnimationAction, _super);
  40548. function StopAnimationAction(triggerOptions, target, condition) {
  40549. var _this = _super.call(this, triggerOptions, condition) || this;
  40550. _this._target = target;
  40551. return _this;
  40552. }
  40553. StopAnimationAction.prototype._prepare = function () {
  40554. };
  40555. StopAnimationAction.prototype.execute = function () {
  40556. var scene = this._actionManager.getScene();
  40557. scene.stopAnimation(this._target);
  40558. };
  40559. StopAnimationAction.prototype.serialize = function (parent) {
  40560. return _super.prototype._serialize.call(this, {
  40561. name: "StopAnimationAction",
  40562. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  40563. }, parent);
  40564. };
  40565. return StopAnimationAction;
  40566. }(BABYLON.Action));
  40567. BABYLON.StopAnimationAction = StopAnimationAction;
  40568. var DoNothingAction = (function (_super) {
  40569. __extends(DoNothingAction, _super);
  40570. function DoNothingAction(triggerOptions, condition) {
  40571. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  40572. return _super.call(this, triggerOptions, condition) || this;
  40573. }
  40574. DoNothingAction.prototype.execute = function () {
  40575. };
  40576. DoNothingAction.prototype.serialize = function (parent) {
  40577. return _super.prototype._serialize.call(this, {
  40578. name: "DoNothingAction",
  40579. properties: []
  40580. }, parent);
  40581. };
  40582. return DoNothingAction;
  40583. }(BABYLON.Action));
  40584. BABYLON.DoNothingAction = DoNothingAction;
  40585. var CombineAction = (function (_super) {
  40586. __extends(CombineAction, _super);
  40587. function CombineAction(triggerOptions, children, condition) {
  40588. var _this = _super.call(this, triggerOptions, condition) || this;
  40589. _this.children = children;
  40590. return _this;
  40591. }
  40592. CombineAction.prototype._prepare = function () {
  40593. for (var index = 0; index < this.children.length; index++) {
  40594. this.children[index]._actionManager = this._actionManager;
  40595. this.children[index]._prepare();
  40596. }
  40597. };
  40598. CombineAction.prototype.execute = function (evt) {
  40599. for (var index = 0; index < this.children.length; index++) {
  40600. this.children[index].execute(evt);
  40601. }
  40602. };
  40603. CombineAction.prototype.serialize = function (parent) {
  40604. var serializationObject = _super.prototype._serialize.call(this, {
  40605. name: "CombineAction",
  40606. properties: [],
  40607. combine: []
  40608. }, parent);
  40609. for (var i = 0; i < this.children.length; i++) {
  40610. serializationObject.combine.push(this.children[i].serialize(null));
  40611. }
  40612. return serializationObject;
  40613. };
  40614. return CombineAction;
  40615. }(BABYLON.Action));
  40616. BABYLON.CombineAction = CombineAction;
  40617. var ExecuteCodeAction = (function (_super) {
  40618. __extends(ExecuteCodeAction, _super);
  40619. function ExecuteCodeAction(triggerOptions, func, condition) {
  40620. var _this = _super.call(this, triggerOptions, condition) || this;
  40621. _this.func = func;
  40622. return _this;
  40623. }
  40624. ExecuteCodeAction.prototype.execute = function (evt) {
  40625. this.func(evt);
  40626. };
  40627. return ExecuteCodeAction;
  40628. }(BABYLON.Action));
  40629. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  40630. var SetParentAction = (function (_super) {
  40631. __extends(SetParentAction, _super);
  40632. function SetParentAction(triggerOptions, target, parent, condition) {
  40633. var _this = _super.call(this, triggerOptions, condition) || this;
  40634. _this._target = target;
  40635. _this._parent = parent;
  40636. return _this;
  40637. }
  40638. SetParentAction.prototype._prepare = function () {
  40639. };
  40640. SetParentAction.prototype.execute = function () {
  40641. if (this._target.parent === this._parent) {
  40642. return;
  40643. }
  40644. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  40645. invertParentWorldMatrix.invert();
  40646. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  40647. this._target.parent = this._parent;
  40648. };
  40649. SetParentAction.prototype.serialize = function (parent) {
  40650. return _super.prototype._serialize.call(this, {
  40651. name: "SetParentAction",
  40652. properties: [
  40653. BABYLON.Action._GetTargetProperty(this._target),
  40654. BABYLON.Action._GetTargetProperty(this._parent),
  40655. ]
  40656. }, parent);
  40657. };
  40658. return SetParentAction;
  40659. }(BABYLON.Action));
  40660. BABYLON.SetParentAction = SetParentAction;
  40661. var PlaySoundAction = (function (_super) {
  40662. __extends(PlaySoundAction, _super);
  40663. function PlaySoundAction(triggerOptions, sound, condition) {
  40664. var _this = _super.call(this, triggerOptions, condition) || this;
  40665. _this._sound = sound;
  40666. return _this;
  40667. }
  40668. PlaySoundAction.prototype._prepare = function () {
  40669. };
  40670. PlaySoundAction.prototype.execute = function () {
  40671. if (this._sound !== undefined)
  40672. this._sound.play();
  40673. };
  40674. PlaySoundAction.prototype.serialize = function (parent) {
  40675. return _super.prototype._serialize.call(this, {
  40676. name: "PlaySoundAction",
  40677. properties: [{ name: "sound", value: this._sound.name }]
  40678. }, parent);
  40679. };
  40680. return PlaySoundAction;
  40681. }(BABYLON.Action));
  40682. BABYLON.PlaySoundAction = PlaySoundAction;
  40683. var StopSoundAction = (function (_super) {
  40684. __extends(StopSoundAction, _super);
  40685. function StopSoundAction(triggerOptions, sound, condition) {
  40686. var _this = _super.call(this, triggerOptions, condition) || this;
  40687. _this._sound = sound;
  40688. return _this;
  40689. }
  40690. StopSoundAction.prototype._prepare = function () {
  40691. };
  40692. StopSoundAction.prototype.execute = function () {
  40693. if (this._sound !== undefined)
  40694. this._sound.stop();
  40695. };
  40696. StopSoundAction.prototype.serialize = function (parent) {
  40697. return _super.prototype._serialize.call(this, {
  40698. name: "StopSoundAction",
  40699. properties: [{ name: "sound", value: this._sound.name }]
  40700. }, parent);
  40701. };
  40702. return StopSoundAction;
  40703. }(BABYLON.Action));
  40704. BABYLON.StopSoundAction = StopSoundAction;
  40705. })(BABYLON || (BABYLON = {}));
  40706. //# sourceMappingURL=babylon.directActions.js.map
  40707. var BABYLON;
  40708. (function (BABYLON) {
  40709. var Geometry = (function () {
  40710. function Geometry(id, scene, vertexData, updatable, mesh) {
  40711. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40712. this._totalVertices = 0;
  40713. this._isDisposed = false;
  40714. this.id = id;
  40715. this._engine = scene.getEngine();
  40716. this._meshes = [];
  40717. this._scene = scene;
  40718. //Init vertex buffer cache
  40719. this._vertexBuffers = {};
  40720. this._indices = [];
  40721. // vertexData
  40722. if (vertexData) {
  40723. this.setAllVerticesData(vertexData, updatable);
  40724. }
  40725. else {
  40726. this._totalVertices = 0;
  40727. this._indices = [];
  40728. }
  40729. if (this._engine.getCaps().vertexArrayObject) {
  40730. this._vertexArrayObjects = {};
  40731. }
  40732. // applyToMesh
  40733. if (mesh) {
  40734. if (mesh instanceof BABYLON.LinesMesh) {
  40735. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40736. this.updateExtend();
  40737. }
  40738. this.applyToMesh(mesh);
  40739. mesh.computeWorldMatrix(true);
  40740. }
  40741. }
  40742. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40743. /**
  40744. * 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
  40745. * @returns The Bias Vector
  40746. */
  40747. get: function () {
  40748. return this._boundingBias;
  40749. },
  40750. set: function (value) {
  40751. if (this._boundingBias && this._boundingBias.equals(value)) {
  40752. return;
  40753. }
  40754. this._boundingBias = value.clone();
  40755. this.updateBoundingInfo(true, null);
  40756. },
  40757. enumerable: true,
  40758. configurable: true
  40759. });
  40760. Object.defineProperty(Geometry.prototype, "extend", {
  40761. get: function () {
  40762. return this._extend;
  40763. },
  40764. enumerable: true,
  40765. configurable: true
  40766. });
  40767. Geometry.prototype.getScene = function () {
  40768. return this._scene;
  40769. };
  40770. Geometry.prototype.getEngine = function () {
  40771. return this._engine;
  40772. };
  40773. Geometry.prototype.isReady = function () {
  40774. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40775. };
  40776. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40777. get: function () {
  40778. for (var index = 0; index < this._meshes.length; index++) {
  40779. if (!this._meshes[index].doNotSerialize) {
  40780. return false;
  40781. }
  40782. }
  40783. return true;
  40784. },
  40785. enumerable: true,
  40786. configurable: true
  40787. });
  40788. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40789. vertexData.applyToGeometry(this, updatable);
  40790. this.notifyUpdate();
  40791. };
  40792. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40793. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40794. this.setVerticesBuffer(buffer);
  40795. };
  40796. Geometry.prototype.setVerticesBuffer = function (buffer) {
  40797. var kind = buffer.getKind();
  40798. if (this._vertexBuffers[kind]) {
  40799. this._vertexBuffers[kind].dispose();
  40800. }
  40801. this._vertexBuffers[kind] = buffer;
  40802. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40803. var data = buffer.getData();
  40804. var stride = buffer.getStrideSize();
  40805. this._totalVertices = data.length / stride;
  40806. this.updateExtend(data, stride);
  40807. var meshes = this._meshes;
  40808. var numOfMeshes = meshes.length;
  40809. for (var index = 0; index < numOfMeshes; index++) {
  40810. var mesh = meshes[index];
  40811. mesh._resetPointsArrayCache();
  40812. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40813. mesh._createGlobalSubMesh();
  40814. mesh.computeWorldMatrix(true);
  40815. }
  40816. }
  40817. this.notifyUpdate(kind);
  40818. if (this._vertexArrayObjects) {
  40819. this._disposeVertexArrayObjects();
  40820. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40821. }
  40822. };
  40823. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  40824. var vertexBuffer = this.getVertexBuffer(kind);
  40825. if (!vertexBuffer) {
  40826. return;
  40827. }
  40828. vertexBuffer.updateDirectly(data, offset);
  40829. this.notifyUpdate(kind);
  40830. };
  40831. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40832. var vertexBuffer = this.getVertexBuffer(kind);
  40833. if (!vertexBuffer) {
  40834. return;
  40835. }
  40836. vertexBuffer.update(data);
  40837. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40838. var stride = vertexBuffer.getStrideSize();
  40839. this._totalVertices = data.length / stride;
  40840. this.updateBoundingInfo(updateExtends, data);
  40841. }
  40842. this.notifyUpdate(kind);
  40843. };
  40844. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  40845. if (updateExtends) {
  40846. this.updateExtend(data);
  40847. }
  40848. var meshes = this._meshes;
  40849. var numOfMeshes = meshes.length;
  40850. for (var index = 0; index < numOfMeshes; index++) {
  40851. var mesh = meshes[index];
  40852. mesh._resetPointsArrayCache();
  40853. if (updateExtends) {
  40854. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40855. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40856. var subMesh = mesh.subMeshes[subIndex];
  40857. subMesh.refreshBoundingInfo();
  40858. }
  40859. }
  40860. }
  40861. };
  40862. Geometry.prototype._bind = function (effect, indexToBind) {
  40863. if (indexToBind === void 0) { indexToBind = undefined; }
  40864. if (indexToBind === undefined) {
  40865. indexToBind = this._indexBuffer;
  40866. }
  40867. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40868. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  40869. return;
  40870. }
  40871. // Using VAO
  40872. if (!this._vertexArrayObjects[effect.key]) {
  40873. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  40874. }
  40875. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40876. };
  40877. Geometry.prototype.getTotalVertices = function () {
  40878. if (!this.isReady()) {
  40879. return 0;
  40880. }
  40881. return this._totalVertices;
  40882. };
  40883. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  40884. var vertexBuffer = this.getVertexBuffer(kind);
  40885. if (!vertexBuffer) {
  40886. return null;
  40887. }
  40888. var orig = vertexBuffer.getData();
  40889. if (!copyWhenShared || this._meshes.length === 1) {
  40890. return orig;
  40891. }
  40892. else {
  40893. var len = orig.length;
  40894. var copy = [];
  40895. for (var i = 0; i < len; i++) {
  40896. copy.push(orig[i]);
  40897. }
  40898. return copy;
  40899. }
  40900. };
  40901. Geometry.prototype.getVertexBuffer = function (kind) {
  40902. if (!this.isReady()) {
  40903. return null;
  40904. }
  40905. return this._vertexBuffers[kind];
  40906. };
  40907. Geometry.prototype.getVertexBuffers = function () {
  40908. if (!this.isReady()) {
  40909. return null;
  40910. }
  40911. return this._vertexBuffers;
  40912. };
  40913. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40914. if (!this._vertexBuffers) {
  40915. if (this._delayInfo) {
  40916. return this._delayInfo.indexOf(kind) !== -1;
  40917. }
  40918. return false;
  40919. }
  40920. return this._vertexBuffers[kind] !== undefined;
  40921. };
  40922. Geometry.prototype.getVerticesDataKinds = function () {
  40923. var result = [];
  40924. var kind;
  40925. if (!this._vertexBuffers && this._delayInfo) {
  40926. for (kind in this._delayInfo) {
  40927. result.push(kind);
  40928. }
  40929. }
  40930. else {
  40931. for (kind in this._vertexBuffers) {
  40932. result.push(kind);
  40933. }
  40934. }
  40935. return result;
  40936. };
  40937. Geometry.prototype.setIndices = function (indices, totalVertices) {
  40938. if (this._indexBuffer) {
  40939. this._engine._releaseBuffer(this._indexBuffer);
  40940. }
  40941. this._disposeVertexArrayObjects();
  40942. this._indices = indices;
  40943. if (this._meshes.length !== 0 && this._indices) {
  40944. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40945. }
  40946. if (totalVertices !== undefined) {
  40947. this._totalVertices = totalVertices;
  40948. }
  40949. var meshes = this._meshes;
  40950. var numOfMeshes = meshes.length;
  40951. for (var index = 0; index < numOfMeshes; index++) {
  40952. meshes[index]._createGlobalSubMesh();
  40953. }
  40954. this.notifyUpdate();
  40955. };
  40956. Geometry.prototype.getTotalIndices = function () {
  40957. if (!this.isReady()) {
  40958. return 0;
  40959. }
  40960. return this._indices.length;
  40961. };
  40962. Geometry.prototype.getIndices = function (copyWhenShared) {
  40963. if (!this.isReady()) {
  40964. return null;
  40965. }
  40966. var orig = this._indices;
  40967. if (!copyWhenShared || this._meshes.length === 1) {
  40968. return orig;
  40969. }
  40970. else {
  40971. var len = orig.length;
  40972. var copy = [];
  40973. for (var i = 0; i < len; i++) {
  40974. copy.push(orig[i]);
  40975. }
  40976. return copy;
  40977. }
  40978. };
  40979. Geometry.prototype.getIndexBuffer = function () {
  40980. if (!this.isReady()) {
  40981. return null;
  40982. }
  40983. return this._indexBuffer;
  40984. };
  40985. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40986. var meshes = this._meshes;
  40987. var index = meshes.indexOf(mesh);
  40988. if (index === -1) {
  40989. return;
  40990. }
  40991. meshes.splice(index, 1);
  40992. mesh._geometry = null;
  40993. if (meshes.length === 0 && shouldDispose) {
  40994. this.dispose();
  40995. }
  40996. };
  40997. Geometry.prototype.applyToMesh = function (mesh) {
  40998. if (mesh._geometry === this) {
  40999. return;
  41000. }
  41001. var previousGeometry = mesh._geometry;
  41002. if (previousGeometry) {
  41003. previousGeometry.releaseForMesh(mesh);
  41004. }
  41005. var meshes = this._meshes;
  41006. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  41007. mesh._geometry = this;
  41008. this._scene.pushGeometry(this);
  41009. meshes.push(mesh);
  41010. if (this.isReady()) {
  41011. this._applyToMesh(mesh);
  41012. }
  41013. else {
  41014. mesh._boundingInfo = this._boundingInfo;
  41015. }
  41016. };
  41017. Geometry.prototype.updateExtend = function (data, stride) {
  41018. if (data === void 0) { data = null; }
  41019. if (!data) {
  41020. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  41021. }
  41022. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  41023. };
  41024. Geometry.prototype._applyToMesh = function (mesh) {
  41025. var numOfMeshes = this._meshes.length;
  41026. // vertexBuffers
  41027. for (var kind in this._vertexBuffers) {
  41028. if (numOfMeshes === 1) {
  41029. this._vertexBuffers[kind].create();
  41030. }
  41031. var buffer = this._vertexBuffers[kind].getBuffer();
  41032. if (buffer)
  41033. buffer.references = numOfMeshes;
  41034. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41035. mesh._resetPointsArrayCache();
  41036. if (!this._extend) {
  41037. this.updateExtend(this._vertexBuffers[kind].getData());
  41038. }
  41039. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41040. mesh._createGlobalSubMesh();
  41041. //bounding info was just created again, world matrix should be applied again.
  41042. mesh._updateBoundingInfo();
  41043. }
  41044. }
  41045. // indexBuffer
  41046. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  41047. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41048. }
  41049. if (this._indexBuffer) {
  41050. this._indexBuffer.references = numOfMeshes;
  41051. }
  41052. };
  41053. Geometry.prototype.notifyUpdate = function (kind) {
  41054. if (this.onGeometryUpdated) {
  41055. this.onGeometryUpdated(this, kind);
  41056. }
  41057. };
  41058. Geometry.prototype.load = function (scene, onLoaded) {
  41059. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  41060. return;
  41061. }
  41062. if (this.isReady()) {
  41063. if (onLoaded) {
  41064. onLoaded();
  41065. }
  41066. return;
  41067. }
  41068. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  41069. this._queueLoad(scene, onLoaded);
  41070. };
  41071. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  41072. var _this = this;
  41073. scene._addPendingData(this);
  41074. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  41075. _this._delayLoadingFunction(JSON.parse(data), _this);
  41076. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41077. _this._delayInfo = [];
  41078. scene._removePendingData(_this);
  41079. var meshes = _this._meshes;
  41080. var numOfMeshes = meshes.length;
  41081. for (var index = 0; index < numOfMeshes; index++) {
  41082. _this._applyToMesh(meshes[index]);
  41083. }
  41084. if (onLoaded) {
  41085. onLoaded();
  41086. }
  41087. }, function () { }, scene.database);
  41088. };
  41089. /**
  41090. * Invert the geometry to move from a right handed system to a left handed one.
  41091. */
  41092. Geometry.prototype.toLeftHanded = function () {
  41093. // Flip faces
  41094. var tIndices = this.getIndices(false);
  41095. if (tIndices != null && tIndices.length > 0) {
  41096. for (var i = 0; i < tIndices.length; i += 3) {
  41097. var tTemp = tIndices[i + 0];
  41098. tIndices[i + 0] = tIndices[i + 2];
  41099. tIndices[i + 2] = tTemp;
  41100. }
  41101. this.setIndices(tIndices);
  41102. }
  41103. // Negate position.z
  41104. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  41105. if (tPositions != null && tPositions.length > 0) {
  41106. for (var i = 0; i < tPositions.length; i += 3) {
  41107. tPositions[i + 2] = -tPositions[i + 2];
  41108. }
  41109. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  41110. }
  41111. // Negate normal.z
  41112. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  41113. if (tNormals != null && tNormals.length > 0) {
  41114. for (var i = 0; i < tNormals.length; i += 3) {
  41115. tNormals[i + 2] = -tNormals[i + 2];
  41116. }
  41117. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  41118. }
  41119. };
  41120. Geometry.prototype.isDisposed = function () {
  41121. return this._isDisposed;
  41122. };
  41123. Geometry.prototype._disposeVertexArrayObjects = function () {
  41124. if (this._vertexArrayObjects) {
  41125. for (var kind in this._vertexArrayObjects) {
  41126. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  41127. }
  41128. this._vertexArrayObjects = {};
  41129. }
  41130. };
  41131. Geometry.prototype.dispose = function () {
  41132. var meshes = this._meshes;
  41133. var numOfMeshes = meshes.length;
  41134. var index;
  41135. for (index = 0; index < numOfMeshes; index++) {
  41136. this.releaseForMesh(meshes[index]);
  41137. }
  41138. this._meshes = [];
  41139. this._disposeVertexArrayObjects();
  41140. for (var kind in this._vertexBuffers) {
  41141. this._vertexBuffers[kind].dispose();
  41142. }
  41143. this._vertexBuffers = {};
  41144. this._totalVertices = 0;
  41145. if (this._indexBuffer) {
  41146. this._engine._releaseBuffer(this._indexBuffer);
  41147. }
  41148. this._indexBuffer = null;
  41149. this._indices = [];
  41150. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41151. this.delayLoadingFile = null;
  41152. this._delayLoadingFunction = null;
  41153. this._delayInfo = [];
  41154. this._boundingInfo = null;
  41155. this._scene.removeGeometry(this);
  41156. this._isDisposed = true;
  41157. };
  41158. Geometry.prototype.copy = function (id) {
  41159. var vertexData = new BABYLON.VertexData();
  41160. vertexData.indices = [];
  41161. var indices = this.getIndices();
  41162. for (var index = 0; index < indices.length; index++) {
  41163. vertexData.indices.push(indices[index]);
  41164. }
  41165. var updatable = false;
  41166. var stopChecking = false;
  41167. var kind;
  41168. for (kind in this._vertexBuffers) {
  41169. // using slice() to make a copy of the array and not just reference it
  41170. var data = this.getVerticesData(kind);
  41171. if (data instanceof Float32Array) {
  41172. vertexData.set(new Float32Array(data), kind);
  41173. }
  41174. else {
  41175. vertexData.set(data.slice(0), kind);
  41176. }
  41177. if (!stopChecking) {
  41178. updatable = this.getVertexBuffer(kind).isUpdatable();
  41179. stopChecking = !updatable;
  41180. }
  41181. }
  41182. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  41183. geometry.delayLoadState = this.delayLoadState;
  41184. geometry.delayLoadingFile = this.delayLoadingFile;
  41185. geometry._delayLoadingFunction = this._delayLoadingFunction;
  41186. for (kind in this._delayInfo) {
  41187. geometry._delayInfo = geometry._delayInfo || [];
  41188. geometry._delayInfo.push(kind);
  41189. }
  41190. // Bounding info
  41191. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41192. return geometry;
  41193. };
  41194. Geometry.prototype.serialize = function () {
  41195. var serializationObject = {};
  41196. serializationObject.id = this.id;
  41197. if (BABYLON.Tags.HasTags(this)) {
  41198. serializationObject.tags = BABYLON.Tags.GetTags(this);
  41199. }
  41200. return serializationObject;
  41201. };
  41202. Geometry.prototype.serializeVerticeData = function () {
  41203. var serializationObject = this.serialize();
  41204. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41205. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41206. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  41207. serializationObject.positions._updatable = true;
  41208. }
  41209. }
  41210. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41211. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41212. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  41213. serializationObject.normals._updatable = true;
  41214. }
  41215. }
  41216. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41217. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41218. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  41219. serializationObject.uvs._updatable = true;
  41220. }
  41221. }
  41222. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41223. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  41224. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  41225. serializationObject.uv2s._updatable = true;
  41226. }
  41227. }
  41228. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41229. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  41230. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  41231. serializationObject.uv3s._updatable = true;
  41232. }
  41233. }
  41234. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41235. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  41236. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  41237. serializationObject.uv4s._updatable = true;
  41238. }
  41239. }
  41240. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41241. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  41242. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  41243. serializationObject.uv5s._updatable = true;
  41244. }
  41245. }
  41246. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41247. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  41248. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  41249. serializationObject.uv6s._updatable = true;
  41250. }
  41251. }
  41252. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41253. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41254. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  41255. serializationObject.colors._updatable = true;
  41256. }
  41257. }
  41258. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41259. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41260. serializationObject.matricesIndices._isExpanded = true;
  41261. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  41262. serializationObject.matricesIndices._updatable = true;
  41263. }
  41264. }
  41265. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41266. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  41267. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  41268. serializationObject.matricesWeights._updatable = true;
  41269. }
  41270. }
  41271. serializationObject.indices = this.getIndices();
  41272. return serializationObject;
  41273. };
  41274. // Statics
  41275. Geometry.ExtractFromMesh = function (mesh, id) {
  41276. var geometry = mesh._geometry;
  41277. if (!geometry) {
  41278. return null;
  41279. }
  41280. return geometry.copy(id);
  41281. };
  41282. /**
  41283. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41284. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41285. * Be aware Math.random() could cause collisions, but:
  41286. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  41287. */
  41288. Geometry.RandomId = function () {
  41289. return BABYLON.Tools.RandomId();
  41290. };
  41291. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  41292. var scene = mesh.getScene();
  41293. // Geometry
  41294. var geometryId = parsedGeometry.geometryId;
  41295. if (geometryId) {
  41296. var geometry = scene.getGeometryByID(geometryId);
  41297. if (geometry) {
  41298. geometry.applyToMesh(mesh);
  41299. }
  41300. }
  41301. else if (parsedGeometry instanceof ArrayBuffer) {
  41302. var binaryInfo = mesh._binaryInfo;
  41303. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41304. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41305. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41306. }
  41307. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41308. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41309. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41310. }
  41311. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41312. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41313. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41314. }
  41315. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41316. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41317. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41318. }
  41319. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41320. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41321. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41322. }
  41323. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41324. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41325. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41326. }
  41327. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41328. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41329. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41330. }
  41331. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41332. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41333. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41334. }
  41335. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41336. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41337. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41338. }
  41339. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41340. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41341. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  41342. }
  41343. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41344. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41345. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41346. }
  41347. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41348. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41349. mesh.setIndices(indicesData);
  41350. }
  41351. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41352. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41353. mesh.subMeshes = [];
  41354. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41355. var materialIndex = subMeshesData[(i * 5) + 0];
  41356. var verticesStart = subMeshesData[(i * 5) + 1];
  41357. var verticesCount = subMeshesData[(i * 5) + 2];
  41358. var indexStart = subMeshesData[(i * 5) + 3];
  41359. var indexCount = subMeshesData[(i * 5) + 4];
  41360. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41361. }
  41362. }
  41363. }
  41364. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41365. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41366. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41367. if (parsedGeometry.uvs) {
  41368. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41369. }
  41370. if (parsedGeometry.uvs2) {
  41371. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41372. }
  41373. if (parsedGeometry.uvs3) {
  41374. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41375. }
  41376. if (parsedGeometry.uvs4) {
  41377. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41378. }
  41379. if (parsedGeometry.uvs5) {
  41380. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41381. }
  41382. if (parsedGeometry.uvs6) {
  41383. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41384. }
  41385. if (parsedGeometry.colors) {
  41386. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41387. }
  41388. if (parsedGeometry.matricesIndices) {
  41389. if (!parsedGeometry.matricesIndices._isExpanded) {
  41390. var floatIndices = [];
  41391. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41392. var matricesIndex = parsedGeometry.matricesIndices[i];
  41393. floatIndices.push(matricesIndex & 0x000000FF);
  41394. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41395. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41396. floatIndices.push(matricesIndex >> 24);
  41397. }
  41398. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41399. }
  41400. else {
  41401. delete parsedGeometry.matricesIndices._isExpanded;
  41402. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41403. }
  41404. }
  41405. if (parsedGeometry.matricesIndicesExtra) {
  41406. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41407. var floatIndices = [];
  41408. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41409. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41410. floatIndices.push(matricesIndex & 0x000000FF);
  41411. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41412. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41413. floatIndices.push(matricesIndex >> 24);
  41414. }
  41415. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41416. }
  41417. else {
  41418. delete parsedGeometry.matricesIndices._isExpanded;
  41419. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41420. }
  41421. }
  41422. if (parsedGeometry.matricesWeights) {
  41423. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41424. }
  41425. if (parsedGeometry.matricesWeightsExtra) {
  41426. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41427. }
  41428. mesh.setIndices(parsedGeometry.indices);
  41429. }
  41430. // SubMeshes
  41431. if (parsedGeometry.subMeshes) {
  41432. mesh.subMeshes = [];
  41433. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41434. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41435. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41436. }
  41437. }
  41438. // Flat shading
  41439. if (mesh._shouldGenerateFlatShading) {
  41440. mesh.convertToFlatShadedMesh();
  41441. delete mesh._shouldGenerateFlatShading;
  41442. }
  41443. // Update
  41444. mesh.computeWorldMatrix(true);
  41445. // Octree
  41446. if (scene['_selectionOctree']) {
  41447. scene['_selectionOctree'].addMesh(mesh);
  41448. }
  41449. };
  41450. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41451. if (scene.getGeometryByID(parsedVertexData.id)) {
  41452. return null; // null since geometry could be something else than a box...
  41453. }
  41454. var geometry = new Geometry(parsedVertexData.id, scene);
  41455. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41456. if (parsedVertexData.delayLoadingFile) {
  41457. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41458. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41459. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41460. geometry._delayInfo = [];
  41461. if (parsedVertexData.hasUVs) {
  41462. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41463. }
  41464. if (parsedVertexData.hasUVs2) {
  41465. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41466. }
  41467. if (parsedVertexData.hasUVs3) {
  41468. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41469. }
  41470. if (parsedVertexData.hasUVs4) {
  41471. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41472. }
  41473. if (parsedVertexData.hasUVs5) {
  41474. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41475. }
  41476. if (parsedVertexData.hasUVs6) {
  41477. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41478. }
  41479. if (parsedVertexData.hasColors) {
  41480. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41481. }
  41482. if (parsedVertexData.hasMatricesIndices) {
  41483. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41484. }
  41485. if (parsedVertexData.hasMatricesWeights) {
  41486. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41487. }
  41488. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41489. }
  41490. else {
  41491. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41492. }
  41493. scene.pushGeometry(geometry, true);
  41494. return geometry;
  41495. };
  41496. return Geometry;
  41497. }());
  41498. BABYLON.Geometry = Geometry;
  41499. /////// Primitives //////////////////////////////////////////////
  41500. (function (Geometry) {
  41501. var Primitives;
  41502. (function (Primitives) {
  41503. /// Abstract class
  41504. var _Primitive = (function (_super) {
  41505. __extends(_Primitive, _super);
  41506. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  41507. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  41508. _this._canBeRegenerated = _canBeRegenerated;
  41509. _this._beingRegenerated = true;
  41510. _this.regenerate();
  41511. _this._beingRegenerated = false;
  41512. return _this;
  41513. }
  41514. _Primitive.prototype.canBeRegenerated = function () {
  41515. return this._canBeRegenerated;
  41516. };
  41517. _Primitive.prototype.regenerate = function () {
  41518. if (!this._canBeRegenerated) {
  41519. return;
  41520. }
  41521. this._beingRegenerated = true;
  41522. this.setAllVerticesData(this._regenerateVertexData(), false);
  41523. this._beingRegenerated = false;
  41524. };
  41525. _Primitive.prototype.asNewGeometry = function (id) {
  41526. return _super.prototype.copy.call(this, id);
  41527. };
  41528. // overrides
  41529. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  41530. if (!this._beingRegenerated) {
  41531. return;
  41532. }
  41533. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41534. };
  41535. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  41536. if (!this._beingRegenerated) {
  41537. return;
  41538. }
  41539. _super.prototype.setVerticesData.call(this, kind, data, false);
  41540. };
  41541. // to override
  41542. // protected
  41543. _Primitive.prototype._regenerateVertexData = function () {
  41544. throw new Error("Abstract method");
  41545. };
  41546. _Primitive.prototype.copy = function (id) {
  41547. throw new Error("Must be overriden in sub-classes.");
  41548. };
  41549. _Primitive.prototype.serialize = function () {
  41550. var serializationObject = _super.prototype.serialize.call(this);
  41551. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41552. return serializationObject;
  41553. };
  41554. return _Primitive;
  41555. }(Geometry));
  41556. Primitives._Primitive = _Primitive;
  41557. var Ribbon = (function (_super) {
  41558. __extends(Ribbon, _super);
  41559. // Members
  41560. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  41561. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41562. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41563. _this.pathArray = pathArray;
  41564. _this.closeArray = closeArray;
  41565. _this.closePath = closePath;
  41566. _this.offset = offset;
  41567. _this.side = side;
  41568. return _this;
  41569. }
  41570. Ribbon.prototype._regenerateVertexData = function () {
  41571. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41572. };
  41573. Ribbon.prototype.copy = function (id) {
  41574. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  41575. };
  41576. return Ribbon;
  41577. }(_Primitive));
  41578. Primitives.Ribbon = Ribbon;
  41579. var Box = (function (_super) {
  41580. __extends(Box, _super);
  41581. // Members
  41582. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  41583. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41584. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41585. _this.size = size;
  41586. _this.side = side;
  41587. return _this;
  41588. }
  41589. Box.prototype._regenerateVertexData = function () {
  41590. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41591. };
  41592. Box.prototype.copy = function (id) {
  41593. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41594. };
  41595. Box.prototype.serialize = function () {
  41596. var serializationObject = _super.prototype.serialize.call(this);
  41597. serializationObject.size = this.size;
  41598. return serializationObject;
  41599. };
  41600. Box.Parse = function (parsedBox, scene) {
  41601. if (scene.getGeometryByID(parsedBox.id)) {
  41602. return null; // null since geometry could be something else than a box...
  41603. }
  41604. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41605. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41606. scene.pushGeometry(box, true);
  41607. return box;
  41608. };
  41609. return Box;
  41610. }(_Primitive));
  41611. Primitives.Box = Box;
  41612. var Sphere = (function (_super) {
  41613. __extends(Sphere, _super);
  41614. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  41615. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41616. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41617. _this.segments = segments;
  41618. _this.diameter = diameter;
  41619. _this.side = side;
  41620. return _this;
  41621. }
  41622. Sphere.prototype._regenerateVertexData = function () {
  41623. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41624. };
  41625. Sphere.prototype.copy = function (id) {
  41626. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41627. };
  41628. Sphere.prototype.serialize = function () {
  41629. var serializationObject = _super.prototype.serialize.call(this);
  41630. serializationObject.segments = this.segments;
  41631. serializationObject.diameter = this.diameter;
  41632. return serializationObject;
  41633. };
  41634. Sphere.Parse = function (parsedSphere, scene) {
  41635. if (scene.getGeometryByID(parsedSphere.id)) {
  41636. return null; // null since geometry could be something else than a sphere...
  41637. }
  41638. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41639. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41640. scene.pushGeometry(sphere, true);
  41641. return sphere;
  41642. };
  41643. return Sphere;
  41644. }(_Primitive));
  41645. Primitives.Sphere = Sphere;
  41646. var Disc = (function (_super) {
  41647. __extends(Disc, _super);
  41648. // Members
  41649. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  41650. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41651. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41652. _this.radius = radius;
  41653. _this.tessellation = tessellation;
  41654. _this.side = side;
  41655. return _this;
  41656. }
  41657. Disc.prototype._regenerateVertexData = function () {
  41658. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41659. };
  41660. Disc.prototype.copy = function (id) {
  41661. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41662. };
  41663. return Disc;
  41664. }(_Primitive));
  41665. Primitives.Disc = Disc;
  41666. var Cylinder = (function (_super) {
  41667. __extends(Cylinder, _super);
  41668. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  41669. if (subdivisions === void 0) { subdivisions = 1; }
  41670. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41671. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41672. _this.height = height;
  41673. _this.diameterTop = diameterTop;
  41674. _this.diameterBottom = diameterBottom;
  41675. _this.tessellation = tessellation;
  41676. _this.subdivisions = subdivisions;
  41677. _this.side = side;
  41678. return _this;
  41679. }
  41680. Cylinder.prototype._regenerateVertexData = function () {
  41681. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41682. };
  41683. Cylinder.prototype.copy = function (id) {
  41684. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41685. };
  41686. Cylinder.prototype.serialize = function () {
  41687. var serializationObject = _super.prototype.serialize.call(this);
  41688. serializationObject.height = this.height;
  41689. serializationObject.diameterTop = this.diameterTop;
  41690. serializationObject.diameterBottom = this.diameterBottom;
  41691. serializationObject.tessellation = this.tessellation;
  41692. return serializationObject;
  41693. };
  41694. Cylinder.Parse = function (parsedCylinder, scene) {
  41695. if (scene.getGeometryByID(parsedCylinder.id)) {
  41696. return null; // null since geometry could be something else than a cylinder...
  41697. }
  41698. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41699. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41700. scene.pushGeometry(cylinder, true);
  41701. return cylinder;
  41702. };
  41703. return Cylinder;
  41704. }(_Primitive));
  41705. Primitives.Cylinder = Cylinder;
  41706. var Torus = (function (_super) {
  41707. __extends(Torus, _super);
  41708. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  41709. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41710. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41711. _this.diameter = diameter;
  41712. _this.thickness = thickness;
  41713. _this.tessellation = tessellation;
  41714. _this.side = side;
  41715. return _this;
  41716. }
  41717. Torus.prototype._regenerateVertexData = function () {
  41718. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41719. };
  41720. Torus.prototype.copy = function (id) {
  41721. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41722. };
  41723. Torus.prototype.serialize = function () {
  41724. var serializationObject = _super.prototype.serialize.call(this);
  41725. serializationObject.diameter = this.diameter;
  41726. serializationObject.thickness = this.thickness;
  41727. serializationObject.tessellation = this.tessellation;
  41728. return serializationObject;
  41729. };
  41730. Torus.Parse = function (parsedTorus, scene) {
  41731. if (scene.getGeometryByID(parsedTorus.id)) {
  41732. return null; // null since geometry could be something else than a torus...
  41733. }
  41734. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41735. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41736. scene.pushGeometry(torus, true);
  41737. return torus;
  41738. };
  41739. return Torus;
  41740. }(_Primitive));
  41741. Primitives.Torus = Torus;
  41742. var Ground = (function (_super) {
  41743. __extends(Ground, _super);
  41744. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  41745. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41746. _this.width = width;
  41747. _this.height = height;
  41748. _this.subdivisions = subdivisions;
  41749. return _this;
  41750. }
  41751. Ground.prototype._regenerateVertexData = function () {
  41752. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41753. };
  41754. Ground.prototype.copy = function (id) {
  41755. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41756. };
  41757. Ground.prototype.serialize = function () {
  41758. var serializationObject = _super.prototype.serialize.call(this);
  41759. serializationObject.width = this.width;
  41760. serializationObject.height = this.height;
  41761. serializationObject.subdivisions = this.subdivisions;
  41762. return serializationObject;
  41763. };
  41764. Ground.Parse = function (parsedGround, scene) {
  41765. if (scene.getGeometryByID(parsedGround.id)) {
  41766. return null; // null since geometry could be something else than a ground...
  41767. }
  41768. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41769. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41770. scene.pushGeometry(ground, true);
  41771. return ground;
  41772. };
  41773. return Ground;
  41774. }(_Primitive));
  41775. Primitives.Ground = Ground;
  41776. var TiledGround = (function (_super) {
  41777. __extends(TiledGround, _super);
  41778. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  41779. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41780. _this.xmin = xmin;
  41781. _this.zmin = zmin;
  41782. _this.xmax = xmax;
  41783. _this.zmax = zmax;
  41784. _this.subdivisions = subdivisions;
  41785. _this.precision = precision;
  41786. return _this;
  41787. }
  41788. TiledGround.prototype._regenerateVertexData = function () {
  41789. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41790. };
  41791. TiledGround.prototype.copy = function (id) {
  41792. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41793. };
  41794. return TiledGround;
  41795. }(_Primitive));
  41796. Primitives.TiledGround = TiledGround;
  41797. var Plane = (function (_super) {
  41798. __extends(Plane, _super);
  41799. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  41800. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41801. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41802. _this.size = size;
  41803. _this.side = side;
  41804. return _this;
  41805. }
  41806. Plane.prototype._regenerateVertexData = function () {
  41807. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41808. };
  41809. Plane.prototype.copy = function (id) {
  41810. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41811. };
  41812. Plane.prototype.serialize = function () {
  41813. var serializationObject = _super.prototype.serialize.call(this);
  41814. serializationObject.size = this.size;
  41815. return serializationObject;
  41816. };
  41817. Plane.Parse = function (parsedPlane, scene) {
  41818. if (scene.getGeometryByID(parsedPlane.id)) {
  41819. return null; // null since geometry could be something else than a ground...
  41820. }
  41821. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41822. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41823. scene.pushGeometry(plane, true);
  41824. return plane;
  41825. };
  41826. return Plane;
  41827. }(_Primitive));
  41828. Primitives.Plane = Plane;
  41829. var TorusKnot = (function (_super) {
  41830. __extends(TorusKnot, _super);
  41831. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  41832. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41833. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41834. _this.radius = radius;
  41835. _this.tube = tube;
  41836. _this.radialSegments = radialSegments;
  41837. _this.tubularSegments = tubularSegments;
  41838. _this.p = p;
  41839. _this.q = q;
  41840. _this.side = side;
  41841. return _this;
  41842. }
  41843. TorusKnot.prototype._regenerateVertexData = function () {
  41844. 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 });
  41845. };
  41846. TorusKnot.prototype.copy = function (id) {
  41847. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41848. };
  41849. TorusKnot.prototype.serialize = function () {
  41850. var serializationObject = _super.prototype.serialize.call(this);
  41851. serializationObject.radius = this.radius;
  41852. serializationObject.tube = this.tube;
  41853. serializationObject.radialSegments = this.radialSegments;
  41854. serializationObject.tubularSegments = this.tubularSegments;
  41855. serializationObject.p = this.p;
  41856. serializationObject.q = this.q;
  41857. return serializationObject;
  41858. };
  41859. ;
  41860. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  41861. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41862. return null; // null since geometry could be something else than a ground...
  41863. }
  41864. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41865. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41866. scene.pushGeometry(torusKnot, true);
  41867. return torusKnot;
  41868. };
  41869. return TorusKnot;
  41870. }(_Primitive));
  41871. Primitives.TorusKnot = TorusKnot;
  41872. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  41873. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  41874. })(BABYLON || (BABYLON = {}));
  41875. //# sourceMappingURL=babylon.geometry.js.map
  41876. /// <reference path="babylon.mesh.ts" />
  41877. var BABYLON;
  41878. (function (BABYLON) {
  41879. var GroundMesh = (function (_super) {
  41880. __extends(GroundMesh, _super);
  41881. function GroundMesh(name, scene) {
  41882. var _this = _super.call(this, name, scene) || this;
  41883. _this.generateOctree = false;
  41884. _this._worldInverse = new BABYLON.Matrix();
  41885. return _this;
  41886. }
  41887. GroundMesh.prototype.getClassName = function () {
  41888. return "GroundMesh";
  41889. };
  41890. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  41891. get: function () {
  41892. return Math.min(this._subdivisionsX, this._subdivisionsY);
  41893. },
  41894. enumerable: true,
  41895. configurable: true
  41896. });
  41897. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  41898. get: function () {
  41899. return this._subdivisionsX;
  41900. },
  41901. enumerable: true,
  41902. configurable: true
  41903. });
  41904. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  41905. get: function () {
  41906. return this._subdivisionsY;
  41907. },
  41908. enumerable: true,
  41909. configurable: true
  41910. });
  41911. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  41912. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  41913. this._subdivisionsX = chunksCount;
  41914. this._subdivisionsY = chunksCount;
  41915. this.subdivide(chunksCount);
  41916. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  41917. };
  41918. /**
  41919. * Returns a height (y) value in the Worl system :
  41920. * the ground altitude at the coordinates (x, z) expressed in the World system.
  41921. * Returns the ground y position if (x, z) are outside the ground surface.
  41922. */
  41923. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  41924. var world = this.getWorldMatrix();
  41925. var invMat = BABYLON.Tmp.Matrix[5];
  41926. world.invertToRef(invMat);
  41927. var tmpVect = BABYLON.Tmp.Vector3[8];
  41928. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  41929. x = tmpVect.x;
  41930. z = tmpVect.z;
  41931. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41932. return this.position.y;
  41933. }
  41934. if (!this._heightQuads || this._heightQuads.length == 0) {
  41935. this._initHeightQuads();
  41936. this._computeHeightQuads();
  41937. }
  41938. var facet = this._getFacetAt(x, z);
  41939. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  41940. // return y in the World system
  41941. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  41942. return tmpVect.y;
  41943. };
  41944. /**
  41945. * Returns a normalized vector (Vector3) orthogonal to the ground
  41946. * at the ground coordinates (x, z) expressed in the World system.
  41947. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  41948. */
  41949. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  41950. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  41951. this.getNormalAtCoordinatesToRef(x, z, normal);
  41952. return normal;
  41953. };
  41954. /**
  41955. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  41956. * at the ground coordinates (x, z) expressed in the World system.
  41957. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  41958. * Returns the GroundMesh.
  41959. */
  41960. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  41961. var world = this.getWorldMatrix();
  41962. var tmpMat = BABYLON.Tmp.Matrix[5];
  41963. world.invertToRef(tmpMat);
  41964. var tmpVect = BABYLON.Tmp.Vector3[8];
  41965. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  41966. x = tmpVect.x;
  41967. z = tmpVect.z;
  41968. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41969. return this;
  41970. }
  41971. if (!this._heightQuads || this._heightQuads.length == 0) {
  41972. this._initHeightQuads();
  41973. this._computeHeightQuads();
  41974. }
  41975. var facet = this._getFacetAt(x, z);
  41976. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  41977. return this;
  41978. };
  41979. /**
  41980. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  41981. * if the ground has been updated.
  41982. * This can be used in the render loop.
  41983. * Returns the GroundMesh.
  41984. */
  41985. GroundMesh.prototype.updateCoordinateHeights = function () {
  41986. if (!this._heightQuads || this._heightQuads.length == 0) {
  41987. this._initHeightQuads();
  41988. }
  41989. this._computeHeightQuads();
  41990. return this;
  41991. };
  41992. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  41993. GroundMesh.prototype._getFacetAt = function (x, z) {
  41994. // retrieve col and row from x, z coordinates in the ground local system
  41995. var subdivisionsX = this._subdivisionsX;
  41996. var subdivisionsY = this._subdivisionsY;
  41997. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  41998. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  41999. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42000. var facet;
  42001. if (z < quad.slope.x * x + quad.slope.y) {
  42002. facet = quad.facet1;
  42003. }
  42004. else {
  42005. facet = quad.facet2;
  42006. }
  42007. return facet;
  42008. };
  42009. // Creates and populates the heightMap array with "facet" elements :
  42010. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42011. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42012. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42013. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42014. // Returns the GroundMesh.
  42015. GroundMesh.prototype._initHeightQuads = function () {
  42016. var subdivisionsX = this._subdivisionsX;
  42017. var subdivisionsY = this._subdivisionsY;
  42018. this._heightQuads = new Array();
  42019. for (var row = 0; row < subdivisionsY; row++) {
  42020. for (var col = 0; col < subdivisionsX; col++) {
  42021. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  42022. this._heightQuads[row * subdivisionsX + col] = quad;
  42023. }
  42024. }
  42025. return this;
  42026. };
  42027. // Compute each quad element values and update the the heightMap array :
  42028. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42029. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42030. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42031. // Returns the GroundMesh.
  42032. GroundMesh.prototype._computeHeightQuads = function () {
  42033. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42034. var v1 = BABYLON.Tmp.Vector3[3];
  42035. var v2 = BABYLON.Tmp.Vector3[2];
  42036. var v3 = BABYLON.Tmp.Vector3[1];
  42037. var v4 = BABYLON.Tmp.Vector3[0];
  42038. var v1v2 = BABYLON.Tmp.Vector3[4];
  42039. var v1v3 = BABYLON.Tmp.Vector3[5];
  42040. var v1v4 = BABYLON.Tmp.Vector3[6];
  42041. var norm1 = BABYLON.Tmp.Vector3[7];
  42042. var norm2 = BABYLON.Tmp.Vector3[8];
  42043. var i = 0;
  42044. var j = 0;
  42045. var k = 0;
  42046. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42047. var h = 0;
  42048. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42049. var d2 = 0;
  42050. var subdivisionsX = this._subdivisionsX;
  42051. var subdivisionsY = this._subdivisionsY;
  42052. for (var row = 0; row < subdivisionsY; row++) {
  42053. for (var col = 0; col < subdivisionsX; col++) {
  42054. i = col * 3;
  42055. j = row * (subdivisionsX + 1) * 3;
  42056. k = (row + 1) * (subdivisionsX + 1) * 3;
  42057. v1.x = positions[j + i];
  42058. v1.y = positions[j + i + 1];
  42059. v1.z = positions[j + i + 2];
  42060. v2.x = positions[j + i + 3];
  42061. v2.y = positions[j + i + 4];
  42062. v2.z = positions[j + i + 5];
  42063. v3.x = positions[k + i];
  42064. v3.y = positions[k + i + 1];
  42065. v3.z = positions[k + i + 2];
  42066. v4.x = positions[k + i + 3];
  42067. v4.y = positions[k + i + 4];
  42068. v4.z = positions[k + i + 5];
  42069. // 2D slope V1V4
  42070. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42071. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42072. // facet equations :
  42073. // we compute each facet normal vector
  42074. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42075. // we compute the value d by applying the equation to v1 which belongs to the plane
  42076. // then we store the facet equation in a Vector4
  42077. v2.subtractToRef(v1, v1v2);
  42078. v3.subtractToRef(v1, v1v3);
  42079. v4.subtractToRef(v1, v1v4);
  42080. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42081. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42082. norm1.normalize();
  42083. norm2.normalize();
  42084. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42085. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42086. var quad = this._heightQuads[row * subdivisionsX + col];
  42087. quad.slope.copyFromFloats(cd, h);
  42088. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42089. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42090. }
  42091. }
  42092. return this;
  42093. };
  42094. GroundMesh.prototype.serialize = function (serializationObject) {
  42095. _super.prototype.serialize.call(this, serializationObject);
  42096. serializationObject.subdivisionsX = this._subdivisionsX;
  42097. serializationObject.subdivisionsY = this._subdivisionsY;
  42098. serializationObject.minX = this._minX;
  42099. serializationObject.maxX = this._maxX;
  42100. serializationObject.minZ = this._minZ;
  42101. serializationObject.maxZ = this._maxZ;
  42102. serializationObject.width = this._width;
  42103. serializationObject.height = this._height;
  42104. };
  42105. GroundMesh.Parse = function (parsedMesh, scene) {
  42106. var result = new GroundMesh(parsedMesh.name, scene);
  42107. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  42108. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  42109. result._minX = parsedMesh.minX;
  42110. result._maxX = parsedMesh.maxX;
  42111. result._minZ = parsedMesh.minZ;
  42112. result._maxZ = parsedMesh.maxZ;
  42113. result._width = parsedMesh.width;
  42114. result._height = parsedMesh.height;
  42115. return result;
  42116. };
  42117. return GroundMesh;
  42118. }(BABYLON.Mesh));
  42119. BABYLON.GroundMesh = GroundMesh;
  42120. })(BABYLON || (BABYLON = {}));
  42121. //# sourceMappingURL=babylon.groundMesh.js.map
  42122. /// <reference path="babylon.mesh.ts" />
  42123. var BABYLON;
  42124. (function (BABYLON) {
  42125. var LinesMesh = (function (_super) {
  42126. __extends(LinesMesh, _super);
  42127. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  42128. if (parent === void 0) { parent = null; }
  42129. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  42130. _this.color = new BABYLON.Color3(1, 1, 1);
  42131. _this.alpha = 1;
  42132. _this._positionBuffer = {};
  42133. if (source) {
  42134. _this.color = source.color.clone();
  42135. _this.alpha = source.alpha;
  42136. }
  42137. _this._intersectionThreshold = 0.1;
  42138. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  42139. attributes: [BABYLON.VertexBuffer.PositionKind],
  42140. uniforms: ["worldViewProjection", "color"],
  42141. needAlphaBlending: true
  42142. });
  42143. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  42144. return _this;
  42145. }
  42146. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  42147. /**
  42148. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42149. * This margin is expressed in world space coordinates, so its value may vary.
  42150. * Default value is 0.1
  42151. * @returns the intersection Threshold value.
  42152. */
  42153. get: function () {
  42154. return this._intersectionThreshold;
  42155. },
  42156. /**
  42157. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42158. * This margin is expressed in world space coordinates, so its value may vary.
  42159. * @param value the new threshold to apply
  42160. */
  42161. set: function (value) {
  42162. if (this._intersectionThreshold === value) {
  42163. return;
  42164. }
  42165. this._intersectionThreshold = value;
  42166. if (this.geometry) {
  42167. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  42168. }
  42169. },
  42170. enumerable: true,
  42171. configurable: true
  42172. });
  42173. /**
  42174. * Returns the string "LineMesh"
  42175. */
  42176. LinesMesh.prototype.getClassName = function () {
  42177. return "LinesMesh";
  42178. };
  42179. Object.defineProperty(LinesMesh.prototype, "material", {
  42180. get: function () {
  42181. return this._colorShader;
  42182. },
  42183. enumerable: true,
  42184. configurable: true
  42185. });
  42186. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  42187. get: function () {
  42188. return false;
  42189. },
  42190. enumerable: true,
  42191. configurable: true
  42192. });
  42193. LinesMesh.prototype.createInstance = function (name) {
  42194. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  42195. return null;
  42196. };
  42197. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  42198. var engine = this.getScene().getEngine();
  42199. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  42200. // VBOs
  42201. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  42202. // Color
  42203. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  42204. return this;
  42205. };
  42206. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  42207. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  42208. return this;
  42209. }
  42210. var engine = this.getScene().getEngine();
  42211. // Draw order
  42212. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  42213. return this;
  42214. };
  42215. LinesMesh.prototype.dispose = function (doNotRecurse) {
  42216. this._colorShader.dispose();
  42217. _super.prototype.dispose.call(this, doNotRecurse);
  42218. };
  42219. /**
  42220. * Returns a new LineMesh object cloned from the current one.
  42221. */
  42222. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42223. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  42224. };
  42225. return LinesMesh;
  42226. }(BABYLON.Mesh));
  42227. BABYLON.LinesMesh = LinesMesh;
  42228. })(BABYLON || (BABYLON = {}));
  42229. //# sourceMappingURL=babylon.linesMesh.js.map
  42230. var BABYLON;
  42231. (function (BABYLON) {
  42232. var DefaultLoadingScreen = (function () {
  42233. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  42234. if (_loadingText === void 0) { _loadingText = ""; }
  42235. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  42236. var _this = this;
  42237. this._renderingCanvas = _renderingCanvas;
  42238. this._loadingText = _loadingText;
  42239. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  42240. // Resize
  42241. this._resizeLoadingUI = function () {
  42242. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  42243. _this._loadingDiv.style.position = "absolute";
  42244. _this._loadingDiv.style.left = canvasRect.left + "px";
  42245. _this._loadingDiv.style.top = canvasRect.top + "px";
  42246. _this._loadingDiv.style.width = canvasRect.width + "px";
  42247. _this._loadingDiv.style.height = canvasRect.height + "px";
  42248. };
  42249. }
  42250. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  42251. var _this = this;
  42252. if (this._loadingDiv) {
  42253. // Do not add a loading screen if there is already one
  42254. return;
  42255. }
  42256. this._loadingDiv = document.createElement("div");
  42257. this._loadingDiv.id = "babylonjsLoadingDiv";
  42258. this._loadingDiv.style.opacity = "0";
  42259. this._loadingDiv.style.transition = "opacity 1.5s ease";
  42260. // Loading text
  42261. this._loadingTextDiv = document.createElement("div");
  42262. this._loadingTextDiv.style.position = "absolute";
  42263. this._loadingTextDiv.style.left = "0";
  42264. this._loadingTextDiv.style.top = "50%";
  42265. this._loadingTextDiv.style.marginTop = "80px";
  42266. this._loadingTextDiv.style.width = "100%";
  42267. this._loadingTextDiv.style.height = "20px";
  42268. this._loadingTextDiv.style.fontFamily = "Arial";
  42269. this._loadingTextDiv.style.fontSize = "14px";
  42270. this._loadingTextDiv.style.color = "white";
  42271. this._loadingTextDiv.style.textAlign = "center";
  42272. this._loadingTextDiv.innerHTML = "Loading";
  42273. this._loadingDiv.appendChild(this._loadingTextDiv);
  42274. //set the predefined text
  42275. this._loadingTextDiv.innerHTML = this._loadingText;
  42276. // Loading img
  42277. var imgBack = new Image();
  42278. 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==";
  42279. imgBack.style.position = "absolute";
  42280. imgBack.style.left = "50%";
  42281. imgBack.style.top = "50%";
  42282. imgBack.style.marginLeft = "-50px";
  42283. imgBack.style.marginTop = "-50px";
  42284. imgBack.style.transition = "transform 1.0s ease";
  42285. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  42286. var deg = 360;
  42287. var onTransitionEnd = function () {
  42288. deg += 360;
  42289. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  42290. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  42291. };
  42292. imgBack.addEventListener("transitionend", onTransitionEnd);
  42293. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  42294. this._loadingDiv.appendChild(imgBack);
  42295. // front image
  42296. var imgFront = new Image();
  42297. 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=";
  42298. imgFront.style.position = "absolute";
  42299. imgFront.style.left = "50%";
  42300. imgFront.style.top = "50%";
  42301. imgFront.style.marginLeft = "-50px";
  42302. imgFront.style.marginTop = "-50px";
  42303. this._loadingDiv.appendChild(imgFront);
  42304. this._resizeLoadingUI();
  42305. window.addEventListener("resize", this._resizeLoadingUI);
  42306. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42307. document.body.appendChild(this._loadingDiv);
  42308. setTimeout(function () {
  42309. _this._loadingDiv.style.opacity = "1";
  42310. imgBack.style.transform = "rotateZ(360deg)";
  42311. imgBack.style.webkitTransform = "rotateZ(360deg)";
  42312. }, 0);
  42313. };
  42314. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  42315. var _this = this;
  42316. if (!this._loadingDiv) {
  42317. return;
  42318. }
  42319. var onTransitionEnd = function () {
  42320. if (!_this._loadingDiv) {
  42321. return;
  42322. }
  42323. document.body.removeChild(_this._loadingDiv);
  42324. window.removeEventListener("resize", _this._resizeLoadingUI);
  42325. _this._loadingDiv = null;
  42326. };
  42327. this._loadingDiv.style.opacity = "0";
  42328. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  42329. };
  42330. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  42331. set: function (text) {
  42332. this._loadingText = text;
  42333. if (this._loadingTextDiv) {
  42334. this._loadingTextDiv.innerHTML = this._loadingText;
  42335. }
  42336. },
  42337. enumerable: true,
  42338. configurable: true
  42339. });
  42340. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  42341. get: function () {
  42342. return this._loadingDivBackgroundColor;
  42343. },
  42344. set: function (color) {
  42345. this._loadingDivBackgroundColor = color;
  42346. if (!this._loadingDiv) {
  42347. return;
  42348. }
  42349. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42350. },
  42351. enumerable: true,
  42352. configurable: true
  42353. });
  42354. return DefaultLoadingScreen;
  42355. }());
  42356. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  42357. })(BABYLON || (BABYLON = {}));
  42358. //# sourceMappingURL=babylon.loadingScreen.js.map
  42359. var BABYLON;
  42360. (function (BABYLON) {
  42361. var AudioEngine = (function () {
  42362. function AudioEngine() {
  42363. this._audioContext = null;
  42364. this._audioContextInitialized = false;
  42365. this.canUseWebAudio = false;
  42366. this.WarnedWebAudioUnsupported = false;
  42367. this.unlocked = false;
  42368. this.isMP3supported = false;
  42369. this.isOGGsupported = false;
  42370. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  42371. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  42372. this.canUseWebAudio = true;
  42373. }
  42374. var audioElem = document.createElement('audio');
  42375. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  42376. this.isMP3supported = true;
  42377. }
  42378. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  42379. this.isOGGsupported = true;
  42380. }
  42381. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  42382. this._unlockiOSaudio();
  42383. }
  42384. else {
  42385. this.unlocked = true;
  42386. }
  42387. }
  42388. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  42389. get: function () {
  42390. if (!this._audioContextInitialized) {
  42391. this._initializeAudioContext();
  42392. }
  42393. return this._audioContext;
  42394. },
  42395. enumerable: true,
  42396. configurable: true
  42397. });
  42398. AudioEngine.prototype._unlockiOSaudio = function () {
  42399. var _this = this;
  42400. var unlockaudio = function () {
  42401. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  42402. var source = _this.audioContext.createBufferSource();
  42403. source.buffer = buffer;
  42404. source.connect(_this.audioContext.destination);
  42405. source.start(0);
  42406. setTimeout(function () {
  42407. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  42408. _this.unlocked = true;
  42409. window.removeEventListener('touchend', unlockaudio, false);
  42410. if (_this.onAudioUnlocked) {
  42411. _this.onAudioUnlocked();
  42412. }
  42413. }
  42414. }, 0);
  42415. };
  42416. window.addEventListener('touchend', unlockaudio, false);
  42417. };
  42418. AudioEngine.prototype._initializeAudioContext = function () {
  42419. try {
  42420. if (this.canUseWebAudio) {
  42421. this._audioContext = new AudioContext();
  42422. // create a global volume gain node
  42423. this.masterGain = this._audioContext.createGain();
  42424. this.masterGain.gain.value = 1;
  42425. this.masterGain.connect(this._audioContext.destination);
  42426. this._audioContextInitialized = true;
  42427. }
  42428. }
  42429. catch (e) {
  42430. this.canUseWebAudio = false;
  42431. BABYLON.Tools.Error("Web Audio: " + e.message);
  42432. }
  42433. };
  42434. AudioEngine.prototype.dispose = function () {
  42435. if (this.canUseWebAudio && this._audioContextInitialized) {
  42436. if (this._connectedAnalyser) {
  42437. this._connectedAnalyser.stopDebugCanvas();
  42438. this._connectedAnalyser.dispose();
  42439. this.masterGain.disconnect();
  42440. this.masterGain.connect(this._audioContext.destination);
  42441. this._connectedAnalyser = null;
  42442. }
  42443. this.masterGain.gain.value = 1;
  42444. }
  42445. this.WarnedWebAudioUnsupported = false;
  42446. };
  42447. AudioEngine.prototype.getGlobalVolume = function () {
  42448. if (this.canUseWebAudio && this._audioContextInitialized) {
  42449. return this.masterGain.gain.value;
  42450. }
  42451. else {
  42452. return -1;
  42453. }
  42454. };
  42455. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  42456. if (this.canUseWebAudio && this._audioContextInitialized) {
  42457. this.masterGain.gain.value = newVolume;
  42458. }
  42459. };
  42460. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  42461. if (this._connectedAnalyser) {
  42462. this._connectedAnalyser.stopDebugCanvas();
  42463. }
  42464. if (this.canUseWebAudio && this._audioContextInitialized) {
  42465. this._connectedAnalyser = analyser;
  42466. this.masterGain.disconnect();
  42467. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  42468. }
  42469. };
  42470. return AudioEngine;
  42471. }());
  42472. BABYLON.AudioEngine = AudioEngine;
  42473. })(BABYLON || (BABYLON = {}));
  42474. //# sourceMappingURL=babylon.audioEngine.js.map
  42475. var BABYLON;
  42476. (function (BABYLON) {
  42477. var Sound = (function () {
  42478. /**
  42479. * Create a sound and attach it to a scene
  42480. * @param name Name of your sound
  42481. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  42482. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  42483. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  42484. */
  42485. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  42486. var _this = this;
  42487. this.autoplay = false;
  42488. this.loop = false;
  42489. this.useCustomAttenuation = false;
  42490. this.spatialSound = false;
  42491. this.refDistance = 1;
  42492. this.rolloffFactor = 1;
  42493. this.maxDistance = 100;
  42494. this.distanceModel = "linear";
  42495. this._panningModel = "equalpower";
  42496. this._playbackRate = 1;
  42497. this._streaming = false;
  42498. this._startTime = 0;
  42499. this._startOffset = 0;
  42500. this._position = BABYLON.Vector3.Zero();
  42501. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  42502. this._volume = 1;
  42503. this._isLoaded = false;
  42504. this._isReadyToPlay = false;
  42505. this.isPlaying = false;
  42506. this.isPaused = false;
  42507. this._isDirectional = false;
  42508. // Used if you'd like to create a directional sound.
  42509. // If not set, the sound will be omnidirectional
  42510. this._coneInnerAngle = 360;
  42511. this._coneOuterAngle = 360;
  42512. this._coneOuterGain = 0;
  42513. this._isOutputConnected = false;
  42514. this._urlType = "Unknown";
  42515. this.name = name;
  42516. this._scene = scene;
  42517. this._readyToPlayCallback = readyToPlayCallback;
  42518. // Default custom attenuation function is a linear attenuation
  42519. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  42520. if (currentDistance < maxDistance) {
  42521. return currentVolume * (1 - currentDistance / maxDistance);
  42522. }
  42523. else {
  42524. return 0;
  42525. }
  42526. };
  42527. if (options) {
  42528. this.autoplay = options.autoplay || false;
  42529. this.loop = options.loop || false;
  42530. // if volume === 0, we need another way to check this option
  42531. if (options.volume !== undefined) {
  42532. this._volume = options.volume;
  42533. }
  42534. this.spatialSound = options.spatialSound || false;
  42535. this.maxDistance = options.maxDistance || 100;
  42536. this.useCustomAttenuation = options.useCustomAttenuation || false;
  42537. this.rolloffFactor = options.rolloffFactor || 1;
  42538. this.refDistance = options.refDistance || 1;
  42539. this.distanceModel = options.distanceModel || "linear";
  42540. this._playbackRate = options.playbackRate || 1;
  42541. this._streaming = options.streaming || false;
  42542. }
  42543. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42544. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  42545. this._soundGain.gain.value = this._volume;
  42546. this._inputAudioNode = this._soundGain;
  42547. this._ouputAudioNode = this._soundGain;
  42548. if (this.spatialSound) {
  42549. this._createSpatialParameters();
  42550. }
  42551. this._scene.mainSoundTrack.AddSound(this);
  42552. var validParameter = true;
  42553. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  42554. if (urlOrArrayBuffer) {
  42555. if (typeof (urlOrArrayBuffer) === "string")
  42556. this._urlType = "String";
  42557. if (Array.isArray(urlOrArrayBuffer))
  42558. this._urlType = "Array";
  42559. if (urlOrArrayBuffer instanceof ArrayBuffer)
  42560. this._urlType = "ArrayBuffer";
  42561. var urls = [];
  42562. var codecSupportedFound = false;
  42563. switch (this._urlType) {
  42564. case "ArrayBuffer":
  42565. if (urlOrArrayBuffer.byteLength > 0) {
  42566. codecSupportedFound = true;
  42567. this._soundLoaded(urlOrArrayBuffer);
  42568. }
  42569. break;
  42570. case "String":
  42571. urls.push(urlOrArrayBuffer);
  42572. case "Array":
  42573. if (urls.length === 0)
  42574. urls = urlOrArrayBuffer;
  42575. // If we found a supported format, we load it immediately and stop the loop
  42576. for (var i = 0; i < urls.length; i++) {
  42577. var url = urls[i];
  42578. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  42579. codecSupportedFound = true;
  42580. }
  42581. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  42582. codecSupportedFound = true;
  42583. }
  42584. if (url.indexOf(".wav", url.length - 4) !== -1) {
  42585. codecSupportedFound = true;
  42586. }
  42587. if (codecSupportedFound) {
  42588. // Loading sound using XHR2
  42589. if (!this._streaming) {
  42590. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  42591. }
  42592. else {
  42593. this._htmlAudioElement = new Audio(url);
  42594. this._htmlAudioElement.controls = false;
  42595. this._htmlAudioElement.loop = this.loop;
  42596. this._htmlAudioElement.crossOrigin = "anonymous";
  42597. this._htmlAudioElement.preload = "auto";
  42598. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  42599. _this._isReadyToPlay = true;
  42600. if (_this.autoplay) {
  42601. _this.play();
  42602. }
  42603. if (_this._readyToPlayCallback) {
  42604. _this._readyToPlayCallback();
  42605. }
  42606. });
  42607. document.body.appendChild(this._htmlAudioElement);
  42608. }
  42609. break;
  42610. }
  42611. }
  42612. break;
  42613. default:
  42614. validParameter = false;
  42615. break;
  42616. }
  42617. if (!validParameter) {
  42618. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  42619. }
  42620. else {
  42621. if (!codecSupportedFound) {
  42622. this._isReadyToPlay = true;
  42623. // Simulating a ready to play event to avoid breaking code path
  42624. if (this._readyToPlayCallback) {
  42625. window.setTimeout(function () {
  42626. _this._readyToPlayCallback();
  42627. }, 1000);
  42628. }
  42629. }
  42630. }
  42631. }
  42632. }
  42633. else {
  42634. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  42635. this._scene.mainSoundTrack.AddSound(this);
  42636. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  42637. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  42638. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  42639. }
  42640. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  42641. if (this._readyToPlayCallback) {
  42642. window.setTimeout(function () {
  42643. _this._readyToPlayCallback();
  42644. }, 1000);
  42645. }
  42646. }
  42647. }
  42648. Sound.prototype.dispose = function () {
  42649. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  42650. if (this.isPlaying) {
  42651. this.stop();
  42652. }
  42653. this._isReadyToPlay = false;
  42654. if (this.soundTrackId === -1) {
  42655. this._scene.mainSoundTrack.RemoveSound(this);
  42656. }
  42657. else {
  42658. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  42659. }
  42660. if (this._soundGain) {
  42661. this._soundGain.disconnect();
  42662. this._soundGain = null;
  42663. }
  42664. if (this._soundPanner) {
  42665. this._soundPanner.disconnect();
  42666. this._soundPanner = null;
  42667. }
  42668. if (this._soundSource) {
  42669. this._soundSource.disconnect();
  42670. this._soundSource = null;
  42671. }
  42672. this._audioBuffer = null;
  42673. if (this._htmlAudioElement) {
  42674. this._htmlAudioElement.pause();
  42675. this._htmlAudioElement.src = "";
  42676. document.body.removeChild(this._htmlAudioElement);
  42677. }
  42678. if (this._connectedMesh) {
  42679. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42680. this._connectedMesh = null;
  42681. }
  42682. }
  42683. };
  42684. Sound.prototype.isReady = function () {
  42685. return this._isReadyToPlay;
  42686. };
  42687. Sound.prototype._soundLoaded = function (audioData) {
  42688. var _this = this;
  42689. this._isLoaded = true;
  42690. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  42691. _this._audioBuffer = buffer;
  42692. _this._isReadyToPlay = true;
  42693. if (_this.autoplay) {
  42694. _this.play();
  42695. }
  42696. if (_this._readyToPlayCallback) {
  42697. _this._readyToPlayCallback();
  42698. }
  42699. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  42700. };
  42701. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  42702. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42703. this._audioBuffer = audioBuffer;
  42704. this._isReadyToPlay = true;
  42705. }
  42706. };
  42707. Sound.prototype.updateOptions = function (options) {
  42708. if (options) {
  42709. this.loop = options.loop || this.loop;
  42710. this.maxDistance = options.maxDistance || this.maxDistance;
  42711. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  42712. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  42713. this.refDistance = options.refDistance || this.refDistance;
  42714. this.distanceModel = options.distanceModel || this.distanceModel;
  42715. this._playbackRate = options.playbackRate || this._playbackRate;
  42716. this._updateSpatialParameters();
  42717. if (this.isPlaying) {
  42718. if (this._streaming) {
  42719. this._htmlAudioElement.playbackRate = this._playbackRate;
  42720. }
  42721. else {
  42722. this._soundSource.playbackRate.value = this._playbackRate;
  42723. }
  42724. }
  42725. }
  42726. };
  42727. Sound.prototype._createSpatialParameters = function () {
  42728. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42729. if (this._scene.headphone) {
  42730. this._panningModel = "HRTF";
  42731. }
  42732. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  42733. this._updateSpatialParameters();
  42734. this._soundPanner.connect(this._ouputAudioNode);
  42735. this._inputAudioNode = this._soundPanner;
  42736. }
  42737. };
  42738. Sound.prototype._updateSpatialParameters = function () {
  42739. if (this.spatialSound) {
  42740. if (this.useCustomAttenuation) {
  42741. // Tricks to disable in a way embedded Web Audio attenuation
  42742. this._soundPanner.distanceModel = "linear";
  42743. this._soundPanner.maxDistance = Number.MAX_VALUE;
  42744. this._soundPanner.refDistance = 1;
  42745. this._soundPanner.rolloffFactor = 1;
  42746. this._soundPanner.panningModel = this._panningModel;
  42747. }
  42748. else {
  42749. this._soundPanner.distanceModel = this.distanceModel;
  42750. this._soundPanner.maxDistance = this.maxDistance;
  42751. this._soundPanner.refDistance = this.refDistance;
  42752. this._soundPanner.rolloffFactor = this.rolloffFactor;
  42753. this._soundPanner.panningModel = this._panningModel;
  42754. }
  42755. }
  42756. };
  42757. Sound.prototype.switchPanningModelToHRTF = function () {
  42758. this._panningModel = "HRTF";
  42759. this._switchPanningModel();
  42760. };
  42761. Sound.prototype.switchPanningModelToEqualPower = function () {
  42762. this._panningModel = "equalpower";
  42763. this._switchPanningModel();
  42764. };
  42765. Sound.prototype._switchPanningModel = function () {
  42766. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42767. this._soundPanner.panningModel = this._panningModel;
  42768. }
  42769. };
  42770. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  42771. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42772. if (this._isOutputConnected) {
  42773. this._ouputAudioNode.disconnect();
  42774. }
  42775. this._ouputAudioNode.connect(soundTrackAudioNode);
  42776. this._isOutputConnected = true;
  42777. }
  42778. };
  42779. /**
  42780. * Transform this sound into a directional source
  42781. * @param coneInnerAngle Size of the inner cone in degree
  42782. * @param coneOuterAngle Size of the outer cone in degree
  42783. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  42784. */
  42785. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  42786. if (coneOuterAngle < coneInnerAngle) {
  42787. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  42788. return;
  42789. }
  42790. this._coneInnerAngle = coneInnerAngle;
  42791. this._coneOuterAngle = coneOuterAngle;
  42792. this._coneOuterGain = coneOuterGain;
  42793. this._isDirectional = true;
  42794. if (this.isPlaying && this.loop) {
  42795. this.stop();
  42796. this.play();
  42797. }
  42798. };
  42799. Sound.prototype.setPosition = function (newPosition) {
  42800. this._position = newPosition;
  42801. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42802. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42803. }
  42804. };
  42805. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  42806. this._localDirection = newLocalDirection;
  42807. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  42808. this._updateDirection();
  42809. }
  42810. };
  42811. Sound.prototype._updateDirection = function () {
  42812. var mat = this._connectedMesh.getWorldMatrix();
  42813. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  42814. direction.normalize();
  42815. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  42816. };
  42817. Sound.prototype.updateDistanceFromListener = function () {
  42818. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  42819. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  42820. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  42821. }
  42822. };
  42823. Sound.prototype.setAttenuationFunction = function (callback) {
  42824. this._customAttenuationFunction = callback;
  42825. };
  42826. /**
  42827. * Play the sound
  42828. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  42829. * @param offset (optional) Start the sound setting it at a specific time
  42830. */
  42831. Sound.prototype.play = function (time, offset) {
  42832. var _this = this;
  42833. if (this._isReadyToPlay && this._scene.audioEnabled) {
  42834. try {
  42835. if (this._startOffset < 0) {
  42836. time = -this._startOffset;
  42837. this._startOffset = 0;
  42838. }
  42839. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42840. if (!this._soundSource || !this._streamingSource) {
  42841. if (this.spatialSound) {
  42842. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42843. if (this._isDirectional) {
  42844. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  42845. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  42846. this._soundPanner.coneOuterGain = this._coneOuterGain;
  42847. if (this._connectedMesh) {
  42848. this._updateDirection();
  42849. }
  42850. else {
  42851. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  42852. }
  42853. }
  42854. }
  42855. }
  42856. if (this._streaming) {
  42857. if (!this._streamingSource) {
  42858. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  42859. this._htmlAudioElement.onended = function () { _this._onended(); };
  42860. this._htmlAudioElement.playbackRate = this._playbackRate;
  42861. }
  42862. this._streamingSource.disconnect();
  42863. this._streamingSource.connect(this._inputAudioNode);
  42864. this._htmlAudioElement.play();
  42865. }
  42866. else {
  42867. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  42868. this._soundSource.buffer = this._audioBuffer;
  42869. this._soundSource.connect(this._inputAudioNode);
  42870. this._soundSource.loop = this.loop;
  42871. this._soundSource.playbackRate.value = this._playbackRate;
  42872. this._soundSource.onended = function () { _this._onended(); };
  42873. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  42874. }
  42875. this._startTime = startTime;
  42876. this.isPlaying = true;
  42877. this.isPaused = false;
  42878. }
  42879. catch (ex) {
  42880. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  42881. }
  42882. }
  42883. };
  42884. Sound.prototype._onended = function () {
  42885. this.isPlaying = false;
  42886. if (this.onended) {
  42887. this.onended();
  42888. }
  42889. };
  42890. /**
  42891. * Stop the sound
  42892. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  42893. */
  42894. Sound.prototype.stop = function (time) {
  42895. if (this.isPlaying) {
  42896. if (this._streaming) {
  42897. this._htmlAudioElement.pause();
  42898. // Test needed for Firefox or it will generate an Invalid State Error
  42899. if (this._htmlAudioElement.currentTime > 0) {
  42900. this._htmlAudioElement.currentTime = 0;
  42901. }
  42902. }
  42903. else {
  42904. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42905. this._soundSource.stop(stopTime);
  42906. this._soundSource.onended = null;
  42907. if (!this.isPaused) {
  42908. this._startOffset = 0;
  42909. }
  42910. }
  42911. this.isPlaying = false;
  42912. }
  42913. };
  42914. Sound.prototype.pause = function () {
  42915. if (this.isPlaying) {
  42916. this.isPaused = true;
  42917. if (this._streaming) {
  42918. this._htmlAudioElement.pause();
  42919. }
  42920. else {
  42921. this.stop(0);
  42922. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  42923. }
  42924. }
  42925. };
  42926. Sound.prototype.setVolume = function (newVolume, time) {
  42927. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42928. if (time) {
  42929. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  42930. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  42931. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  42932. }
  42933. else {
  42934. this._soundGain.gain.value = newVolume;
  42935. }
  42936. }
  42937. this._volume = newVolume;
  42938. };
  42939. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  42940. this._playbackRate = newPlaybackRate;
  42941. if (this.isPlaying) {
  42942. if (this._streaming) {
  42943. this._htmlAudioElement.playbackRate = this._playbackRate;
  42944. }
  42945. else {
  42946. this._soundSource.playbackRate.value = this._playbackRate;
  42947. }
  42948. }
  42949. };
  42950. Sound.prototype.getVolume = function () {
  42951. return this._volume;
  42952. };
  42953. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  42954. var _this = this;
  42955. if (this._connectedMesh) {
  42956. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42957. this._registerFunc = null;
  42958. }
  42959. this._connectedMesh = meshToConnectTo;
  42960. if (!this.spatialSound) {
  42961. this.spatialSound = true;
  42962. this._createSpatialParameters();
  42963. if (this.isPlaying && this.loop) {
  42964. this.stop();
  42965. this.play();
  42966. }
  42967. }
  42968. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  42969. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  42970. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  42971. };
  42972. Sound.prototype.detachFromMesh = function () {
  42973. if (this._connectedMesh) {
  42974. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42975. this._registerFunc = null;
  42976. this._connectedMesh = null;
  42977. }
  42978. };
  42979. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  42980. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  42981. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  42982. this._updateDirection();
  42983. }
  42984. };
  42985. Sound.prototype.clone = function () {
  42986. var _this = this;
  42987. if (!this._streaming) {
  42988. var setBufferAndRun = function () {
  42989. if (_this._isReadyToPlay) {
  42990. clonedSound._audioBuffer = _this.getAudioBuffer();
  42991. clonedSound._isReadyToPlay = true;
  42992. if (clonedSound.autoplay) {
  42993. clonedSound.play();
  42994. }
  42995. }
  42996. else {
  42997. window.setTimeout(setBufferAndRun, 300);
  42998. }
  42999. };
  43000. var currentOptions = {
  43001. autoplay: this.autoplay, loop: this.loop,
  43002. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  43003. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  43004. refDistance: this.refDistance, distanceModel: this.distanceModel
  43005. };
  43006. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  43007. if (this.useCustomAttenuation) {
  43008. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  43009. }
  43010. clonedSound.setPosition(this._position);
  43011. clonedSound.setPlaybackRate(this._playbackRate);
  43012. setBufferAndRun();
  43013. return clonedSound;
  43014. }
  43015. else {
  43016. return null;
  43017. }
  43018. };
  43019. Sound.prototype.getAudioBuffer = function () {
  43020. return this._audioBuffer;
  43021. };
  43022. Sound.prototype.serialize = function () {
  43023. var serializationObject = {
  43024. name: this.name,
  43025. url: this.name,
  43026. autoplay: this.autoplay,
  43027. loop: this.loop,
  43028. volume: this._volume,
  43029. spatialSound: this.spatialSound,
  43030. maxDistance: this.maxDistance,
  43031. rolloffFactor: this.rolloffFactor,
  43032. refDistance: this.refDistance,
  43033. distanceModel: this.distanceModel,
  43034. playbackRate: this._playbackRate,
  43035. panningModel: this._panningModel,
  43036. soundTrackId: this.soundTrackId
  43037. };
  43038. if (this.spatialSound) {
  43039. if (this._connectedMesh)
  43040. serializationObject.connectedMeshId = this._connectedMesh.id;
  43041. serializationObject.position = this._position.asArray();
  43042. serializationObject.refDistance = this.refDistance;
  43043. serializationObject.distanceModel = this.distanceModel;
  43044. serializationObject.isDirectional = this._isDirectional;
  43045. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  43046. serializationObject.coneInnerAngle = this._coneInnerAngle;
  43047. serializationObject.coneOuterAngle = this._coneOuterAngle;
  43048. serializationObject.coneOuterGain = this._coneOuterGain;
  43049. }
  43050. return serializationObject;
  43051. };
  43052. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  43053. var soundName = parsedSound.name;
  43054. var soundUrl;
  43055. if (parsedSound.url) {
  43056. soundUrl = rootUrl + parsedSound.url;
  43057. }
  43058. else {
  43059. soundUrl = rootUrl + soundName;
  43060. }
  43061. var options = {
  43062. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  43063. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  43064. rolloffFactor: parsedSound.rolloffFactor,
  43065. refDistance: parsedSound.refDistance,
  43066. distanceModel: parsedSound.distanceModel,
  43067. playbackRate: parsedSound.playbackRate
  43068. };
  43069. var newSound;
  43070. if (!sourceSound) {
  43071. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  43072. scene._addPendingData(newSound);
  43073. }
  43074. else {
  43075. var setBufferAndRun = function () {
  43076. if (sourceSound._isReadyToPlay) {
  43077. newSound._audioBuffer = sourceSound.getAudioBuffer();
  43078. newSound._isReadyToPlay = true;
  43079. if (newSound.autoplay) {
  43080. newSound.play();
  43081. }
  43082. }
  43083. else {
  43084. window.setTimeout(setBufferAndRun, 300);
  43085. }
  43086. };
  43087. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  43088. setBufferAndRun();
  43089. }
  43090. if (parsedSound.position) {
  43091. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  43092. newSound.setPosition(soundPosition);
  43093. }
  43094. if (parsedSound.isDirectional) {
  43095. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  43096. if (parsedSound.localDirectionToMesh) {
  43097. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  43098. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  43099. }
  43100. }
  43101. if (parsedSound.connectedMeshId) {
  43102. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  43103. if (connectedMesh) {
  43104. newSound.attachToMesh(connectedMesh);
  43105. }
  43106. }
  43107. return newSound;
  43108. };
  43109. return Sound;
  43110. }());
  43111. BABYLON.Sound = Sound;
  43112. })(BABYLON || (BABYLON = {}));
  43113. //# sourceMappingURL=babylon.sound.js.map
  43114. var BABYLON;
  43115. (function (BABYLON) {
  43116. var SoundTrack = (function () {
  43117. function SoundTrack(scene, options) {
  43118. this.id = -1;
  43119. this._isMainTrack = false;
  43120. this._isInitialized = false;
  43121. this._scene = scene;
  43122. this.soundCollection = new Array();
  43123. this._options = options;
  43124. if (!this._isMainTrack) {
  43125. this._scene.soundTracks.push(this);
  43126. this.id = this._scene.soundTracks.length - 1;
  43127. }
  43128. }
  43129. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  43130. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43131. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  43132. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  43133. if (this._options) {
  43134. if (this._options.volume) {
  43135. this._outputAudioNode.gain.value = this._options.volume;
  43136. }
  43137. if (this._options.mainTrack) {
  43138. this._isMainTrack = this._options.mainTrack;
  43139. }
  43140. }
  43141. this._isInitialized = true;
  43142. }
  43143. };
  43144. SoundTrack.prototype.dispose = function () {
  43145. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43146. if (this._connectedAnalyser) {
  43147. this._connectedAnalyser.stopDebugCanvas();
  43148. }
  43149. while (this.soundCollection.length) {
  43150. this.soundCollection[0].dispose();
  43151. }
  43152. if (this._outputAudioNode) {
  43153. this._outputAudioNode.disconnect();
  43154. }
  43155. this._outputAudioNode = null;
  43156. }
  43157. };
  43158. SoundTrack.prototype.AddSound = function (sound) {
  43159. if (!this._isInitialized) {
  43160. this._initializeSoundTrackAudioGraph();
  43161. }
  43162. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43163. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  43164. }
  43165. if (sound.soundTrackId) {
  43166. if (sound.soundTrackId === -1) {
  43167. this._scene.mainSoundTrack.RemoveSound(sound);
  43168. }
  43169. else {
  43170. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  43171. }
  43172. }
  43173. this.soundCollection.push(sound);
  43174. sound.soundTrackId = this.id;
  43175. };
  43176. SoundTrack.prototype.RemoveSound = function (sound) {
  43177. var index = this.soundCollection.indexOf(sound);
  43178. if (index !== -1) {
  43179. this.soundCollection.splice(index, 1);
  43180. }
  43181. };
  43182. SoundTrack.prototype.setVolume = function (newVolume) {
  43183. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43184. this._outputAudioNode.gain.value = newVolume;
  43185. }
  43186. };
  43187. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  43188. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43189. for (var i = 0; i < this.soundCollection.length; i++) {
  43190. this.soundCollection[i].switchPanningModelToHRTF();
  43191. }
  43192. }
  43193. };
  43194. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  43195. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43196. for (var i = 0; i < this.soundCollection.length; i++) {
  43197. this.soundCollection[i].switchPanningModelToEqualPower();
  43198. }
  43199. }
  43200. };
  43201. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  43202. if (this._connectedAnalyser) {
  43203. this._connectedAnalyser.stopDebugCanvas();
  43204. }
  43205. this._connectedAnalyser = analyser;
  43206. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43207. this._outputAudioNode.disconnect();
  43208. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  43209. }
  43210. };
  43211. return SoundTrack;
  43212. }());
  43213. BABYLON.SoundTrack = SoundTrack;
  43214. })(BABYLON || (BABYLON = {}));
  43215. //# sourceMappingURL=babylon.soundtrack.js.map
  43216. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  43217. /// <reference path="..\Math\babylon.math.ts" />
  43218. var BABYLON;
  43219. (function (BABYLON) {
  43220. /**
  43221. * Special Glow Blur post process only blurring the alpha channel
  43222. * It enforces keeping the most luminous color in the color channel.
  43223. */
  43224. var GlowBlurPostProcess = (function (_super) {
  43225. __extends(GlowBlurPostProcess, _super);
  43226. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  43227. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  43228. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  43229. _this.direction = direction;
  43230. _this.blurWidth = blurWidth;
  43231. _this.onApplyObservable.add(function (effect) {
  43232. effect.setFloat2("screenSize", _this.width, _this.height);
  43233. effect.setVector2("direction", _this.direction);
  43234. effect.setFloat("blurWidth", _this.blurWidth);
  43235. });
  43236. return _this;
  43237. }
  43238. return GlowBlurPostProcess;
  43239. }(BABYLON.PostProcess));
  43240. /**
  43241. * The highlight layer Helps adding a glow effect around a mesh.
  43242. *
  43243. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  43244. * glowy meshes to your scene.
  43245. *
  43246. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  43247. */
  43248. var HighlightLayer = (function () {
  43249. /**
  43250. * Instantiates a new highlight Layer and references it to the scene..
  43251. * @param name The name of the layer
  43252. * @param scene The scene to use the layer in
  43253. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  43254. */
  43255. function HighlightLayer(name, scene, options) {
  43256. this.name = name;
  43257. this._vertexBuffers = {};
  43258. this._mainTextureDesiredSize = { width: 0, height: 0 };
  43259. this._meshes = {};
  43260. this._maxSize = 0;
  43261. this._shouldRender = false;
  43262. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  43263. this._excludedMeshes = {};
  43264. /**
  43265. * Specifies whether or not the inner glow is ACTIVE in the layer.
  43266. */
  43267. this.innerGlow = true;
  43268. /**
  43269. * Specifies whether or not the outer glow is ACTIVE in the layer.
  43270. */
  43271. this.outerGlow = true;
  43272. /**
  43273. * Specifies wether the highlight layer is enabled or not.
  43274. */
  43275. this.isEnabled = true;
  43276. /**
  43277. * An event triggered when the highlight layer has been disposed.
  43278. * @type {BABYLON.Observable}
  43279. */
  43280. this.onDisposeObservable = new BABYLON.Observable();
  43281. /**
  43282. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  43283. * @type {BABYLON.Observable}
  43284. */
  43285. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  43286. /**
  43287. * An event triggered when the highlight layer is being blurred.
  43288. * @type {BABYLON.Observable}
  43289. */
  43290. this.onBeforeBlurObservable = new BABYLON.Observable();
  43291. /**
  43292. * An event triggered when the highlight layer has been blurred.
  43293. * @type {BABYLON.Observable}
  43294. */
  43295. this.onAfterBlurObservable = new BABYLON.Observable();
  43296. /**
  43297. * An event triggered when the glowing blurred texture is being merged in the scene.
  43298. * @type {BABYLON.Observable}
  43299. */
  43300. this.onBeforeComposeObservable = new BABYLON.Observable();
  43301. /**
  43302. * An event triggered when the glowing blurred texture has been merged in the scene.
  43303. * @type {BABYLON.Observable}
  43304. */
  43305. this.onAfterComposeObservable = new BABYLON.Observable();
  43306. /**
  43307. * An event triggered when the highlight layer changes its size.
  43308. * @type {BABYLON.Observable}
  43309. */
  43310. this.onSizeChangedObservable = new BABYLON.Observable();
  43311. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43312. var engine = scene.getEngine();
  43313. this._engine = engine;
  43314. this._maxSize = this._engine.getCaps().maxTextureSize;
  43315. this._scene.highlightLayers.push(this);
  43316. // Warn on stencil.
  43317. if (!this._engine.isStencilEnable) {
  43318. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  43319. }
  43320. // Adapt options
  43321. this._options = options || {
  43322. mainTextureRatio: 0.25,
  43323. blurTextureSizeRatio: 0.5,
  43324. blurHorizontalSize: 1,
  43325. blurVerticalSize: 1,
  43326. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  43327. };
  43328. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  43329. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  43330. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  43331. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  43332. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  43333. // VBO
  43334. var vertices = [];
  43335. vertices.push(1, 1);
  43336. vertices.push(-1, 1);
  43337. vertices.push(-1, -1);
  43338. vertices.push(1, -1);
  43339. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  43340. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  43341. // Indices
  43342. var indices = [];
  43343. indices.push(0);
  43344. indices.push(1);
  43345. indices.push(2);
  43346. indices.push(0);
  43347. indices.push(2);
  43348. indices.push(3);
  43349. this._indexBuffer = engine.createIndexBuffer(indices);
  43350. // Effect
  43351. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  43352. // Render target
  43353. this.setMainTextureSize();
  43354. // Create Textures and post processes
  43355. this.createTextureAndPostProcesses();
  43356. }
  43357. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  43358. /**
  43359. * Gets the horizontal size of the blur.
  43360. */
  43361. get: function () {
  43362. return this._horizontalBlurPostprocess.blurWidth;
  43363. },
  43364. /**
  43365. * Specifies the horizontal size of the blur.
  43366. */
  43367. set: function (value) {
  43368. this._horizontalBlurPostprocess.blurWidth = value;
  43369. },
  43370. enumerable: true,
  43371. configurable: true
  43372. });
  43373. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  43374. /**
  43375. * Gets the vertical size of the blur.
  43376. */
  43377. get: function () {
  43378. return this._verticalBlurPostprocess.blurWidth;
  43379. },
  43380. /**
  43381. * Specifies the vertical size of the blur.
  43382. */
  43383. set: function (value) {
  43384. this._verticalBlurPostprocess.blurWidth = value;
  43385. },
  43386. enumerable: true,
  43387. configurable: true
  43388. });
  43389. Object.defineProperty(HighlightLayer.prototype, "camera", {
  43390. /**
  43391. * Gets the camera attached to the layer.
  43392. */
  43393. get: function () {
  43394. return this._options.camera;
  43395. },
  43396. enumerable: true,
  43397. configurable: true
  43398. });
  43399. /**
  43400. * Creates the render target textures and post processes used in the highlight layer.
  43401. */
  43402. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  43403. var _this = this;
  43404. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  43405. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  43406. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  43407. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  43408. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  43409. width: this._mainTextureDesiredSize.width,
  43410. height: this._mainTextureDesiredSize.height
  43411. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  43412. this._mainTexture.activeCamera = this._options.camera;
  43413. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43414. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43415. this._mainTexture.anisotropicFilteringLevel = 1;
  43416. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43417. this._mainTexture.renderParticles = false;
  43418. this._mainTexture.renderList = null;
  43419. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  43420. width: blurTextureWidth,
  43421. height: blurTextureHeight
  43422. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  43423. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43424. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43425. this._blurTexture.anisotropicFilteringLevel = 16;
  43426. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  43427. this._blurTexture.renderParticles = false;
  43428. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43429. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  43430. effect.setTexture("textureSampler", _this._mainTexture);
  43431. });
  43432. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  43433. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43434. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  43435. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43436. });
  43437. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43438. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  43439. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43440. });
  43441. }
  43442. else {
  43443. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43444. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  43445. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43446. });
  43447. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43448. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  43449. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43450. });
  43451. }
  43452. this._mainTexture.onAfterUnbindObservable.add(function () {
  43453. _this.onBeforeBlurObservable.notifyObservers(_this);
  43454. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  43455. _this.onAfterBlurObservable.notifyObservers(_this);
  43456. });
  43457. // Custom render function
  43458. var renderSubMesh = function (subMesh) {
  43459. var mesh = subMesh.getRenderingMesh();
  43460. var scene = _this._scene;
  43461. var engine = scene.getEngine();
  43462. // Culling
  43463. engine.setState(subMesh.getMaterial().backFaceCulling);
  43464. // Managing instances
  43465. var batch = mesh._getInstancesRenderList(subMesh._id);
  43466. if (batch.mustReturn) {
  43467. return;
  43468. }
  43469. // Excluded Mesh
  43470. if (_this._excludedMeshes[mesh.uniqueId]) {
  43471. return;
  43472. }
  43473. ;
  43474. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43475. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  43476. var material = subMesh.getMaterial();
  43477. var emissiveTexture = null;
  43478. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  43479. emissiveTexture = material.emissiveTexture;
  43480. }
  43481. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  43482. engine.enableEffect(_this._glowMapGenerationEffect);
  43483. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  43484. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  43485. if (highlightLayerMesh) {
  43486. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  43487. }
  43488. else {
  43489. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  43490. }
  43491. // Alpha test
  43492. if (material && material.needAlphaTesting()) {
  43493. var alphaTexture = material.getAlphaTestTexture();
  43494. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  43495. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43496. }
  43497. // Glow emissive only
  43498. if (emissiveTexture) {
  43499. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  43500. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  43501. }
  43502. // Bones
  43503. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43504. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43505. }
  43506. // Draw
  43507. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  43508. }
  43509. else {
  43510. // Need to reset refresh rate of the shadowMap
  43511. _this._mainTexture.resetRefreshCounter();
  43512. }
  43513. };
  43514. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  43515. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  43516. var index;
  43517. for (index = 0; index < opaqueSubMeshes.length; index++) {
  43518. renderSubMesh(opaqueSubMeshes.data[index]);
  43519. }
  43520. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  43521. renderSubMesh(alphaTestSubMeshes.data[index]);
  43522. }
  43523. for (index = 0; index < transparentSubMeshes.length; index++) {
  43524. renderSubMesh(transparentSubMeshes.data[index]);
  43525. }
  43526. };
  43527. this._mainTexture.onClearObservable.add(function (engine) {
  43528. engine.clear(HighlightLayer.neutralColor, true, true, true);
  43529. });
  43530. };
  43531. /**
  43532. * Checks for the readiness of the element composing the layer.
  43533. * @param subMesh the mesh to check for
  43534. * @param useInstances specify wether or not to use instances to render the mesh
  43535. * @param emissiveTexture the associated emissive texture used to generate the glow
  43536. * @return true if ready otherwise, false
  43537. */
  43538. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  43539. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  43540. return false;
  43541. }
  43542. var defines = [];
  43543. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43544. var mesh = subMesh.getMesh();
  43545. var material = subMesh.getMaterial();
  43546. var uv1 = false;
  43547. var uv2 = false;
  43548. // Alpha test
  43549. if (material && material.needAlphaTesting()) {
  43550. var alphaTexture = material.getAlphaTestTexture();
  43551. if (alphaTexture) {
  43552. defines.push("#define ALPHATEST");
  43553. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  43554. alphaTexture.coordinatesIndex === 1) {
  43555. defines.push("#define DIFFUSEUV2");
  43556. uv2 = true;
  43557. }
  43558. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43559. defines.push("#define DIFFUSEUV1");
  43560. uv1 = true;
  43561. }
  43562. }
  43563. }
  43564. // Emissive
  43565. if (emissiveTexture) {
  43566. defines.push("#define EMISSIVE");
  43567. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  43568. emissiveTexture.coordinatesIndex === 1) {
  43569. defines.push("#define EMISSIVEUV2");
  43570. uv2 = true;
  43571. }
  43572. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43573. defines.push("#define EMISSIVEUV1");
  43574. uv1 = true;
  43575. }
  43576. }
  43577. if (uv1) {
  43578. attribs.push(BABYLON.VertexBuffer.UVKind);
  43579. defines.push("#define UV1");
  43580. }
  43581. if (uv2) {
  43582. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43583. defines.push("#define UV2");
  43584. }
  43585. // Bones
  43586. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43587. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43588. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43589. if (mesh.numBoneInfluencers > 4) {
  43590. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43591. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43592. }
  43593. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43594. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43595. }
  43596. else {
  43597. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43598. }
  43599. // Instances
  43600. if (useInstances) {
  43601. defines.push("#define INSTANCES");
  43602. attribs.push("world0");
  43603. attribs.push("world1");
  43604. attribs.push("world2");
  43605. attribs.push("world3");
  43606. }
  43607. // Get correct effect
  43608. var join = defines.join("\n");
  43609. if (this._cachedDefines !== join) {
  43610. this._cachedDefines = join;
  43611. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  43612. }
  43613. return this._glowMapGenerationEffect.isReady();
  43614. };
  43615. /**
  43616. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  43617. */
  43618. HighlightLayer.prototype.render = function () {
  43619. var currentEffect = this._glowMapMergeEffect;
  43620. // Check
  43621. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  43622. return;
  43623. var engine = this._scene.getEngine();
  43624. this.onBeforeComposeObservable.notifyObservers(this);
  43625. // Render
  43626. engine.enableEffect(currentEffect);
  43627. engine.setState(false);
  43628. // Cache
  43629. var previousStencilBuffer = engine.getStencilBuffer();
  43630. var previousStencilFunction = engine.getStencilFunction();
  43631. var previousStencilMask = engine.getStencilMask();
  43632. var previousAlphaMode = engine.getAlphaMode();
  43633. // Texture
  43634. currentEffect.setTexture("textureSampler", this._blurTexture);
  43635. // VBOs
  43636. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  43637. // Draw order
  43638. engine.setAlphaMode(this._options.alphaBlendingMode);
  43639. engine.setStencilMask(0x00);
  43640. engine.setStencilBuffer(true);
  43641. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  43642. if (this.outerGlow) {
  43643. currentEffect.setFloat("offset", 0);
  43644. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  43645. engine.draw(true, 0, 6);
  43646. }
  43647. if (this.innerGlow) {
  43648. currentEffect.setFloat("offset", 1);
  43649. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  43650. engine.draw(true, 0, 6);
  43651. }
  43652. // Restore Cache
  43653. engine.setStencilFunction(previousStencilFunction);
  43654. engine.setStencilMask(previousStencilMask);
  43655. engine.setAlphaMode(previousAlphaMode);
  43656. engine.setStencilBuffer(previousStencilBuffer);
  43657. this.onAfterComposeObservable.notifyObservers(this);
  43658. // Handle size changes.
  43659. var size = this._mainTexture.getSize();
  43660. this.setMainTextureSize();
  43661. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  43662. // Recreate RTT and post processes on size change.
  43663. this.onSizeChangedObservable.notifyObservers(this);
  43664. this.disposeTextureAndPostProcesses();
  43665. this.createTextureAndPostProcesses();
  43666. }
  43667. };
  43668. /**
  43669. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  43670. * @param mesh The mesh to exclude from the highlight layer
  43671. */
  43672. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  43673. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  43674. if (!meshExcluded) {
  43675. this._excludedMeshes[mesh.uniqueId] = {
  43676. mesh: mesh,
  43677. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  43678. mesh.getEngine().setStencilBuffer(false);
  43679. }),
  43680. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  43681. mesh.getEngine().setStencilBuffer(true);
  43682. }),
  43683. };
  43684. }
  43685. };
  43686. /**
  43687. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  43688. * @param mesh The mesh to highlight
  43689. */
  43690. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  43691. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  43692. if (meshExcluded) {
  43693. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  43694. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  43695. }
  43696. this._excludedMeshes[mesh.uniqueId] = undefined;
  43697. };
  43698. /**
  43699. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  43700. * @param mesh The mesh to highlight
  43701. * @param color The color of the highlight
  43702. * @param glowEmissiveOnly Extract the glow from the emissive texture
  43703. */
  43704. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  43705. var _this = this;
  43706. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  43707. var meshHighlight = this._meshes[mesh.uniqueId];
  43708. if (meshHighlight) {
  43709. meshHighlight.color = color;
  43710. }
  43711. else {
  43712. this._meshes[mesh.uniqueId] = {
  43713. mesh: mesh,
  43714. color: color,
  43715. // Lambda required for capture due to Observable this context
  43716. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  43717. if (_this._excludedMeshes[mesh.uniqueId]) {
  43718. _this.defaultStencilReference(mesh);
  43719. }
  43720. else {
  43721. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  43722. }
  43723. }),
  43724. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  43725. glowEmissiveOnly: glowEmissiveOnly
  43726. };
  43727. }
  43728. this._shouldRender = true;
  43729. };
  43730. /**
  43731. * Remove a mesh from the highlight layer in order to make it stop glowing.
  43732. * @param mesh The mesh to highlight
  43733. */
  43734. HighlightLayer.prototype.removeMesh = function (mesh) {
  43735. var meshHighlight = this._meshes[mesh.uniqueId];
  43736. if (meshHighlight) {
  43737. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  43738. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  43739. }
  43740. this._meshes[mesh.uniqueId] = undefined;
  43741. this._shouldRender = false;
  43742. for (var meshHighlightToCheck in this._meshes) {
  43743. if (meshHighlightToCheck) {
  43744. this._shouldRender = true;
  43745. break;
  43746. }
  43747. }
  43748. };
  43749. /**
  43750. * Returns true if the layer contains information to display, otherwise false.
  43751. */
  43752. HighlightLayer.prototype.shouldRender = function () {
  43753. return this.isEnabled && this._shouldRender;
  43754. };
  43755. /**
  43756. * Sets the main texture desired size which is the closest power of two
  43757. * of the engine canvas size.
  43758. */
  43759. HighlightLayer.prototype.setMainTextureSize = function () {
  43760. if (this._options.mainTextureFixedSize) {
  43761. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  43762. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  43763. }
  43764. else {
  43765. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  43766. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  43767. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  43768. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  43769. }
  43770. };
  43771. /**
  43772. * Force the stencil to the normal expected value for none glowing parts
  43773. */
  43774. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  43775. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  43776. };
  43777. /**
  43778. * Dispose only the render target textures and post process.
  43779. */
  43780. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  43781. this._blurTexture.dispose();
  43782. this._mainTexture.dispose();
  43783. this._downSamplePostprocess.dispose();
  43784. this._horizontalBlurPostprocess.dispose();
  43785. this._verticalBlurPostprocess.dispose();
  43786. };
  43787. /**
  43788. * Dispose the highlight layer and free resources.
  43789. */
  43790. HighlightLayer.prototype.dispose = function () {
  43791. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  43792. if (vertexBuffer) {
  43793. vertexBuffer.dispose();
  43794. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  43795. }
  43796. if (this._indexBuffer) {
  43797. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43798. this._indexBuffer = null;
  43799. }
  43800. // Clean textures and post processes
  43801. this.disposeTextureAndPostProcesses();
  43802. // Clean mesh references
  43803. for (var id in this._meshes) {
  43804. var meshHighlight = this._meshes[id];
  43805. if (meshHighlight && meshHighlight.mesh) {
  43806. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  43807. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  43808. }
  43809. }
  43810. this._meshes = null;
  43811. for (var id in this._excludedMeshes) {
  43812. var meshHighlight = this._excludedMeshes[id];
  43813. if (meshHighlight) {
  43814. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  43815. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  43816. }
  43817. }
  43818. this._excludedMeshes = null;
  43819. // Remove from scene
  43820. var index = this._scene.highlightLayers.indexOf(this, 0);
  43821. if (index > -1) {
  43822. this._scene.highlightLayers.splice(index, 1);
  43823. }
  43824. // Callback
  43825. this.onDisposeObservable.notifyObservers(this);
  43826. this.onDisposeObservable.clear();
  43827. this.onBeforeRenderMainTextureObservable.clear();
  43828. this.onBeforeBlurObservable.clear();
  43829. this.onBeforeComposeObservable.clear();
  43830. this.onAfterComposeObservable.clear();
  43831. this.onSizeChangedObservable.clear();
  43832. };
  43833. return HighlightLayer;
  43834. }());
  43835. /**
  43836. * The neutral color used during the preparation of the glow effect.
  43837. * This is black by default as the blend operation is a blend operation.
  43838. */
  43839. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  43840. /**
  43841. * Stencil value used for glowing meshes.
  43842. */
  43843. HighlightLayer.glowingMeshStencilReference = 0x02;
  43844. /**
  43845. * Stencil value used for the other meshes in the scene.
  43846. */
  43847. HighlightLayer.normalMeshStencilReference = 0x01;
  43848. BABYLON.HighlightLayer = HighlightLayer;
  43849. })(BABYLON || (BABYLON = {}));
  43850. //# sourceMappingURL=babylon.highlightlayer.js.map
  43851. var BABYLON;
  43852. (function (BABYLON) {
  43853. var SIMDVector3 = (function () {
  43854. function SIMDVector3() {
  43855. }
  43856. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  43857. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  43858. };
  43859. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  43860. var m = transformation.m;
  43861. var m0 = SIMD.Float32x4.load(m, 0);
  43862. var m1 = SIMD.Float32x4.load(m, 4);
  43863. var m2 = SIMD.Float32x4.load(m, 8);
  43864. var m3 = SIMD.Float32x4.load(m, 12);
  43865. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  43866. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  43867. result.x = SIMD.Float32x4.extractLane(r, 0);
  43868. result.y = SIMD.Float32x4.extractLane(r, 1);
  43869. result.z = SIMD.Float32x4.extractLane(r, 2);
  43870. };
  43871. return SIMDVector3;
  43872. }());
  43873. var SIMDMatrix = (function () {
  43874. function SIMDMatrix() {
  43875. }
  43876. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  43877. var tm = this.m;
  43878. var om = other.m;
  43879. var m0 = SIMD.Float32x4.load(om, 0);
  43880. var m1 = SIMD.Float32x4.load(om, 4);
  43881. var m2 = SIMD.Float32x4.load(om, 8);
  43882. var m3 = SIMD.Float32x4.load(om, 12);
  43883. for (var i = 0; i < 16; i += 4) {
  43884. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  43885. }
  43886. return this;
  43887. };
  43888. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  43889. var src = this.m;
  43890. var dest = other.m;
  43891. // Load the 4 rows
  43892. var src0 = SIMD.Float32x4.load(src, 0);
  43893. var src1 = SIMD.Float32x4.load(src, 4);
  43894. var src2 = SIMD.Float32x4.load(src, 8);
  43895. var src3 = SIMD.Float32x4.load(src, 12);
  43896. // Transpose the source matrix. Sort of. Not a true transpose operation
  43897. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  43898. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  43899. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  43900. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  43901. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  43902. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  43903. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  43904. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  43905. // This is a true transposition, but it will lead to an incorrect result
  43906. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  43907. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  43908. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  43909. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  43910. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  43911. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  43912. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  43913. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  43914. // ----
  43915. tmp1 = SIMD.Float32x4.mul(row2, row3);
  43916. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43917. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  43918. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  43919. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43920. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  43921. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  43922. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  43923. // ----
  43924. tmp1 = SIMD.Float32x4.mul(row1, row2);
  43925. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43926. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  43927. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  43928. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43929. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  43930. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  43931. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  43932. // ----
  43933. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  43934. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43935. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  43936. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  43937. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  43938. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43939. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  43940. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  43941. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  43942. // ----
  43943. tmp1 = SIMD.Float32x4.mul(row0, row1);
  43944. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43945. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  43946. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  43947. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43948. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  43949. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  43950. // ----
  43951. tmp1 = SIMD.Float32x4.mul(row0, row3);
  43952. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43953. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  43954. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  43955. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43956. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  43957. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  43958. // ----
  43959. tmp1 = SIMD.Float32x4.mul(row0, row2);
  43960. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43961. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  43962. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  43963. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43964. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  43965. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  43966. // Compute determinant
  43967. var det = SIMD.Float32x4.mul(row0, minor0);
  43968. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  43969. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  43970. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  43971. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  43972. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  43973. // These shuffles aren't necessary if the faulty transposition is done
  43974. // up at the top of this function.
  43975. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  43976. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  43977. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  43978. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  43979. // Compute final values by multiplying with 1/det
  43980. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  43981. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  43982. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  43983. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  43984. return this;
  43985. };
  43986. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  43987. var out = result.m;
  43988. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  43989. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  43990. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  43991. // cc.kmVec3Subtract(f, pCenter, pEye);
  43992. var f = SIMD.Float32x4.sub(center, eye);
  43993. // cc.kmVec3Normalize(f, f);
  43994. var tmp = SIMD.Float32x4.mul(f, f);
  43995. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  43996. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  43997. // cc.kmVec3Assign(up, pUp);
  43998. // cc.kmVec3Normalize(up, up);
  43999. tmp = SIMD.Float32x4.mul(up, up);
  44000. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44001. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44002. // cc.kmVec3Cross(s, f, up);
  44003. 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)));
  44004. // cc.kmVec3Normalize(s, s);
  44005. tmp = SIMD.Float32x4.mul(s, s);
  44006. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44007. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44008. // cc.kmVec3Cross(u, s, f);
  44009. 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)));
  44010. // cc.kmVec3Normalize(s, s);
  44011. tmp = SIMD.Float32x4.mul(s, s);
  44012. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44013. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44014. var zero = SIMD.Float32x4.splat(0.0);
  44015. s = SIMD.Float32x4.neg(s);
  44016. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  44017. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  44018. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  44019. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  44020. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  44021. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  44022. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  44023. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  44024. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  44025. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  44026. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  44027. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  44028. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  44029. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  44030. };
  44031. return SIMDMatrix;
  44032. }());
  44033. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  44034. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  44035. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  44036. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  44037. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  44038. var SIMDHelper = (function () {
  44039. function SIMDHelper() {
  44040. }
  44041. Object.defineProperty(SIMDHelper, "IsEnabled", {
  44042. get: function () {
  44043. return SIMDHelper._isEnabled;
  44044. },
  44045. enumerable: true,
  44046. configurable: true
  44047. });
  44048. SIMDHelper.DisableSIMD = function () {
  44049. // Replace functions
  44050. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  44051. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  44052. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  44053. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  44054. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  44055. SIMDHelper._isEnabled = false;
  44056. };
  44057. SIMDHelper.EnableSIMD = function () {
  44058. if (self.SIMD === undefined) {
  44059. return;
  44060. }
  44061. // check if polyfills needed
  44062. if (!self.Math.fround) {
  44063. self.Math.fround = (function (array) { return function (x) {
  44064. return array[0] = x, array[0];
  44065. }; })(new Float32Array(1));
  44066. }
  44067. if (!self.Math.imul) {
  44068. self.Math.imul = function (a, b) {
  44069. var ah = (a >>> 16) & 0xffff;
  44070. var al = a & 0xffff;
  44071. var bh = (b >>> 16) & 0xffff;
  44072. var bl = b & 0xffff;
  44073. // the shift by 0 fixes the sign on the high part
  44074. // the final |0 converts the unsigned value into a signed value
  44075. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  44076. };
  44077. }
  44078. // Replace functions
  44079. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  44080. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  44081. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  44082. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  44083. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  44084. SIMDHelper._isEnabled = true;
  44085. };
  44086. return SIMDHelper;
  44087. }());
  44088. SIMDHelper._isEnabled = false;
  44089. BABYLON.SIMDHelper = SIMDHelper;
  44090. })(BABYLON || (BABYLON = {}));
  44091. //# sourceMappingURL=babylon.math.SIMD.js.map
  44092. var BABYLON;
  44093. (function (BABYLON) {
  44094. /**
  44095. * This class describe a rectangle that were added to the map.
  44096. * You have access to its coordinates either in pixel or normalized (UV)
  44097. */
  44098. var PackedRect = (function () {
  44099. function PackedRect(root, parent, pos, size) {
  44100. this._pos = pos;
  44101. this._size = size;
  44102. this._root = root;
  44103. this._parent = parent;
  44104. this._contentSize = null;
  44105. this._bottomNode = null;
  44106. this._leftNode = null;
  44107. this._initialSize = null;
  44108. this._rightNode = null;
  44109. }
  44110. Object.defineProperty(PackedRect.prototype, "pos", {
  44111. /**
  44112. * @returns the position of this node into the map
  44113. */
  44114. get: function () {
  44115. return this._pos;
  44116. },
  44117. enumerable: true,
  44118. configurable: true
  44119. });
  44120. Object.defineProperty(PackedRect.prototype, "contentSize", {
  44121. /**
  44122. * @returns the size of the rectangle this node handles
  44123. */
  44124. get: function () {
  44125. return this._contentSize;
  44126. },
  44127. enumerable: true,
  44128. configurable: true
  44129. });
  44130. /**
  44131. * Retrieve the inner position (considering the margin) and stores it into the res object
  44132. * @param res must be a valid Vector2 that will contain the inner position after this call
  44133. */
  44134. PackedRect.prototype.getInnerPosToRef = function (res) {
  44135. var m = this._root._margin;
  44136. res.x = this._pos.x + m;
  44137. res.y = this._pos.y + m;
  44138. };
  44139. /**
  44140. * Retrieve the inner size (considering the margin) and stores it into the res object
  44141. * @param res must be a valid Size that will contain the inner size after this call
  44142. */
  44143. PackedRect.prototype.getInnerSizeToRef = function (res) {
  44144. var m = this._root._margin;
  44145. res.width = this._contentSize.width - (m * 2);
  44146. res.height = this._contentSize.height - (m * 2);
  44147. };
  44148. Object.defineProperty(PackedRect.prototype, "UVs", {
  44149. /**
  44150. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  44151. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  44152. */
  44153. get: function () {
  44154. if (!this._contentSize) {
  44155. throw new Error("Can't compute UVs for this object because it's nor allocated");
  44156. }
  44157. return this.getUVsForCustomSize(this._contentSize);
  44158. },
  44159. enumerable: true,
  44160. configurable: true
  44161. });
  44162. /**
  44163. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  44164. * and then using only a part of the PackRect.
  44165. * This method will return the UVs for this part by given the custom size of what you really use
  44166. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  44167. */
  44168. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  44169. var mainWidth = this._root._size.width;
  44170. var mainHeight = this._root._size.height;
  44171. var margin = this._root._margin;
  44172. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  44173. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  44174. var uvs = new Array();
  44175. uvs.push(topLeft);
  44176. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  44177. uvs.push(rightBottom);
  44178. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  44179. return uvs;
  44180. };
  44181. /**
  44182. * Free this rectangle from the map.
  44183. * Call this method when you no longer need the rectangle to be in the map.
  44184. */
  44185. PackedRect.prototype.freeContent = function () {
  44186. if (!this.contentSize) {
  44187. return;
  44188. }
  44189. this._contentSize = null;
  44190. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  44191. this.attemptDefrag();
  44192. };
  44193. Object.defineProperty(PackedRect.prototype, "isUsed", {
  44194. get: function () {
  44195. return this._contentSize != null || this._leftNode != null;
  44196. },
  44197. enumerable: true,
  44198. configurable: true
  44199. });
  44200. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  44201. var node = this.findNode(contentSize);
  44202. // Not enough space...
  44203. if (!node) {
  44204. return null;
  44205. }
  44206. node.splitNode(contentSize);
  44207. return node;
  44208. };
  44209. PackedRect.prototype.findNode = function (size) {
  44210. var resNode = null;
  44211. var margin = this._root._margin * 2;
  44212. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  44213. if (this.isUsed) {
  44214. if (this._leftNode) {
  44215. resNode = this._leftNode.findNode(size);
  44216. }
  44217. if (!resNode && this._rightNode) {
  44218. resNode = this._rightNode.findNode(size);
  44219. }
  44220. if (!resNode && this._bottomNode) {
  44221. resNode = this._bottomNode.findNode(size);
  44222. }
  44223. }
  44224. else if (this._initialSize) {
  44225. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  44226. resNode = this;
  44227. }
  44228. else {
  44229. return null;
  44230. }
  44231. }
  44232. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  44233. resNode = this;
  44234. }
  44235. return resNode;
  44236. };
  44237. PackedRect.prototype.splitNode = function (contentSize) {
  44238. var cs = PackedRect.TpsSize;
  44239. var margin = this._root._margin * 2;
  44240. cs.copyFrom(contentSize);
  44241. cs.width += margin;
  44242. cs.height += margin;
  44243. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  44244. if (!this._contentSize && this._initialSize) {
  44245. this._contentSize = cs.clone();
  44246. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  44247. return this._leftNode.splitNode(contentSize);
  44248. }
  44249. else {
  44250. this._contentSize = cs.clone();
  44251. this._initialSize = cs.clone();
  44252. if (cs.width !== this._size.width) {
  44253. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + cs.width, this._pos.y), new BABYLON.Size(this._size.width - cs.width, cs.height));
  44254. }
  44255. if (cs.height !== this._size.height) {
  44256. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + cs.height), new BABYLON.Size(this._size.width, this._size.height - cs.height));
  44257. }
  44258. return this;
  44259. }
  44260. };
  44261. PackedRect.prototype.attemptDefrag = function () {
  44262. if (!this.isUsed && this.isRecursiveFree) {
  44263. this.clearNode();
  44264. if (this._parent) {
  44265. this._parent.attemptDefrag();
  44266. }
  44267. }
  44268. };
  44269. PackedRect.prototype.clearNode = function () {
  44270. this._initialSize = null;
  44271. this._rightNode = null;
  44272. this._bottomNode = null;
  44273. };
  44274. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  44275. get: function () {
  44276. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  44277. },
  44278. enumerable: true,
  44279. configurable: true
  44280. });
  44281. PackedRect.prototype.evalFreeSize = function (size) {
  44282. var levelSize = 0;
  44283. if (!this.isUsed) {
  44284. var margin = this._root._margin;
  44285. var is = this._initialSize;
  44286. if (is) {
  44287. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  44288. }
  44289. else {
  44290. var size_1 = this._size;
  44291. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  44292. }
  44293. }
  44294. if (this._rightNode) {
  44295. levelSize += this._rightNode.evalFreeSize(0);
  44296. }
  44297. if (this._bottomNode) {
  44298. levelSize += this._bottomNode.evalFreeSize(0);
  44299. }
  44300. return levelSize + size;
  44301. };
  44302. return PackedRect;
  44303. }());
  44304. PackedRect.TpsSize = BABYLON.Size.Zero();
  44305. BABYLON.PackedRect = PackedRect;
  44306. /**
  44307. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  44308. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  44309. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
  44310. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  44311. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  44312. */
  44313. var RectPackingMap = (function (_super) {
  44314. __extends(RectPackingMap, _super);
  44315. /**
  44316. * Create an instance of the object with a dimension using the given size
  44317. * @param size The dimension of the rectangle that will contain all the sub ones.
  44318. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  44319. */
  44320. function RectPackingMap(size, margin) {
  44321. if (margin === void 0) { margin = 0; }
  44322. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  44323. _this._margin = margin;
  44324. _this._root = _this;
  44325. return _this;
  44326. }
  44327. /**
  44328. * Add a rectangle, finding the best location to store it into the map
  44329. * @param size the dimension of the rectangle to store
  44330. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  44331. */
  44332. RectPackingMap.prototype.addRect = function (size) {
  44333. var node = this.findAndSplitNode(size);
  44334. return node;
  44335. };
  44336. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  44337. /**
  44338. * Return the current space free normalized between [0;1]
  44339. * @returns {}
  44340. */
  44341. get: function () {
  44342. var freeSize = 0;
  44343. freeSize = this.evalFreeSize(freeSize);
  44344. return freeSize / (this._size.width * this._size.height);
  44345. },
  44346. enumerable: true,
  44347. configurable: true
  44348. });
  44349. return RectPackingMap;
  44350. }(PackedRect));
  44351. BABYLON.RectPackingMap = RectPackingMap;
  44352. })(BABYLON || (BABYLON = {}));
  44353. //# sourceMappingURL=babylon.rectPackingMap.js.map
  44354. var BABYLON;
  44355. (function (BABYLON) {
  44356. var DynamicFloatArrayElementInfo = (function () {
  44357. function DynamicFloatArrayElementInfo() {
  44358. }
  44359. return DynamicFloatArrayElementInfo;
  44360. }());
  44361. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  44362. /**
  44363. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  44364. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  44365. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  44366. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  44367. * Beware, calling pack() may change the offset of some Entries because this method will defragment the Float32Array to replace empty elements by moving allocated ones at their location.
  44368. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there are no "free holes".
  44369. */
  44370. var DynamicFloatArray = (function () {
  44371. /**
  44372. * Construct an instance of the dynamic float array
  44373. * @param stride size of one element in float (i.e. not bytes!)
  44374. * @param initialElementCount the number of available entries at construction
  44375. */
  44376. function DynamicFloatArray(stride, initialElementCount) {
  44377. this.compareValueOffset = null;
  44378. this.sortingAscending = true;
  44379. this._stride = stride;
  44380. this.buffer = new Float32Array(stride * initialElementCount);
  44381. this._lastUsed = 0;
  44382. this._firstFree = 0;
  44383. this._allEntries = new Array(initialElementCount);
  44384. this._freeEntries = new Array(initialElementCount);
  44385. for (var i = 0; i < initialElementCount; i++) {
  44386. var element = new DynamicFloatArrayElementInfo();
  44387. element.offset = i * stride;
  44388. this._allEntries[i] = element;
  44389. this._freeEntries[initialElementCount - i - 1] = element;
  44390. }
  44391. }
  44392. /**
  44393. * Allocate an element in the array.
  44394. * @return the element info instance that contains the offset into the main buffer of the element's location.
  44395. * Beware, this offset may change when you call pack()
  44396. */
  44397. DynamicFloatArray.prototype.allocElement = function () {
  44398. if (this._freeEntries.length === 0) {
  44399. this._growBuffer();
  44400. }
  44401. var el = this._freeEntries.pop();
  44402. this._lastUsed = Math.max(el.offset, this._lastUsed);
  44403. if (el.offset === this._firstFree) {
  44404. if (this._freeEntries.length > 0) {
  44405. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  44406. }
  44407. else {
  44408. this._firstFree += this._stride;
  44409. }
  44410. }
  44411. return el;
  44412. };
  44413. /**
  44414. * Free the element corresponding to the given element info
  44415. * @param elInfo the element that describe the allocated element
  44416. */
  44417. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  44418. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  44419. this._freeEntries.push(elInfo);
  44420. };
  44421. /**
  44422. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  44423. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  44424. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  44425. */
  44426. DynamicFloatArray.prototype.pack = function () {
  44427. // no free slot? no need to pack
  44428. if (this._freeEntries.length === 0) {
  44429. return this.buffer;
  44430. }
  44431. // If the buffer is already packed the last used will always be lower than the first free
  44432. // The opposite may not be true, we can have a lastUsed greater than firstFree but the array still packed, because when an element is freed, lastUsed is not updated (for speed reason) so we may have a lastUsed of a freed element. But that's ok, well soon realize this case.
  44433. if (this._lastUsed < this._firstFree) {
  44434. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  44435. return elementsBuffer_1;
  44436. }
  44437. var s = this._stride;
  44438. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  44439. var lastFree = new DynamicFloatArrayElementInfo();
  44440. lastFree.offset = this.totalElementCount * s;
  44441. this._freeEntries.push(lastFree);
  44442. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  44443. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  44444. var firstFreeSlotOffset = sortedFree[0].offset;
  44445. var freeZoneSize = 1;
  44446. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  44447. var prevOffset = sortedFree[0].offset;
  44448. for (var i = 1; i < sortedFree.length; i++) {
  44449. // If the first free (which means everything before is occupied) is greater or equal the occupied zone size, it means everything is defragmented, we can quit
  44450. if (firstFreeSlotOffset >= occupiedZoneSize) {
  44451. break;
  44452. }
  44453. var curFree = sortedFree[i];
  44454. var curOffset = curFree.offset;
  44455. // Compute the distance between this offset and the previous
  44456. var distance = curOffset - prevOffset;
  44457. // If the distance is the stride size, they are adjacent, it good, move to the next
  44458. if (distance === s) {
  44459. // Free zone is one element bigger
  44460. ++freeZoneSize;
  44461. // as we're about to iterate to the next, the cur becomes the previous...
  44462. prevOffset = curOffset;
  44463. continue;
  44464. }
  44465. // Distance is bigger, which means there's x element between the previous free and this one
  44466. var usedRange = (distance / s) - 1;
  44467. // Two cases the free zone is smaller than the data to move or bigger
  44468. // Copy what can fit in the free zone
  44469. var curMoveOffset = curOffset - s;
  44470. var copyCount = Math.min(freeZoneSize, usedRange);
  44471. for (var j = 0; j < copyCount; j++) {
  44472. var freeI = firstFreeSlotOffset / s;
  44473. var curI = curMoveOffset / s;
  44474. var moveEl = sortedAll[curI];
  44475. this._moveElement(moveEl, firstFreeSlotOffset);
  44476. var replacedEl = sortedAll[freeI];
  44477. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  44478. replacedEl.offset = curMoveOffset;
  44479. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  44480. sortedAll[freeI] = moveEl;
  44481. sortedAll[curI] = replacedEl;
  44482. curMoveOffset -= s;
  44483. firstFreeSlotOffset += s;
  44484. }
  44485. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  44486. if (freeZoneSize <= usedRange) {
  44487. firstFreeSlotOffset = curMoveOffset + s;
  44488. freeZoneSize = 1 + copyCount;
  44489. }
  44490. else {
  44491. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  44492. }
  44493. // as we're about to iterate to the next, the cur becomes the previous...
  44494. prevOffset = curOffset;
  44495. }
  44496. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  44497. this._lastUsed = firstFreeSlotOffset - s;
  44498. this._firstFree = firstFreeSlotOffset;
  44499. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  44500. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  44501. this._allEntries = sortedAll;
  44502. return elementsBuffer;
  44503. };
  44504. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  44505. for (var i = 0; i < this._stride; i++) {
  44506. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  44507. }
  44508. element.offset = destOffset;
  44509. };
  44510. DynamicFloatArray.prototype._growBuffer = function () {
  44511. // Allocate the new buffer with 50% more entries, copy the content of the current one
  44512. var newElCount = Math.floor(this.totalElementCount * 1.5);
  44513. var newBuffer = new Float32Array(newElCount * this._stride);
  44514. newBuffer.set(this.buffer);
  44515. var curCount = this.totalElementCount;
  44516. var addedCount = newElCount - this.totalElementCount;
  44517. for (var i = 0; i < addedCount; i++) {
  44518. var element = new DynamicFloatArrayElementInfo();
  44519. element.offset = (curCount + i) * this.stride;
  44520. this._allEntries.push(element);
  44521. this._freeEntries[addedCount - i - 1] = element;
  44522. }
  44523. this._firstFree = curCount * this.stride;
  44524. this.buffer = newBuffer;
  44525. };
  44526. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  44527. /**
  44528. * Get the total count of entries that can fit in the current buffer
  44529. * @returns the elements count
  44530. */
  44531. get: function () {
  44532. return this._allEntries.length;
  44533. },
  44534. enumerable: true,
  44535. configurable: true
  44536. });
  44537. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  44538. /**
  44539. * Get the count of free entries that can still be allocated without resizing the buffer
  44540. * @returns the free elements count
  44541. */
  44542. get: function () {
  44543. return this._freeEntries.length;
  44544. },
  44545. enumerable: true,
  44546. configurable: true
  44547. });
  44548. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  44549. /**
  44550. * Get the count of allocated elements
  44551. * @returns the allocated elements count
  44552. */
  44553. get: function () {
  44554. return this._allEntries.length - this._freeEntries.length;
  44555. },
  44556. enumerable: true,
  44557. configurable: true
  44558. });
  44559. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  44560. /**
  44561. * Return the size of one element in float
  44562. * @returns the size in float
  44563. */
  44564. get: function () {
  44565. return this._stride;
  44566. },
  44567. enumerable: true,
  44568. configurable: true
  44569. });
  44570. DynamicFloatArray.prototype.sort = function () {
  44571. var _this = this;
  44572. if (!this.compareValueOffset) {
  44573. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  44574. }
  44575. var count = this.usedElementCount;
  44576. // Do we have to (re)create the sort table?
  44577. if (!this._sortTable || this._sortTable.length < count) {
  44578. // Small heuristic... We don't want to allocate totalElementCount right away because it may have 50 for 3 used elements, but on the other side we don't want to allocate just 3 when we just need 2, so double this value to give us some air to breath...
  44579. var newCount = Math.min(this.totalElementCount, count * 2);
  44580. this._sortTable = new Array(newCount);
  44581. }
  44582. if (!this._sortedTable || this._sortedTable.length !== count) {
  44583. this._sortedTable = new Array(count);
  44584. }
  44585. // Because, you know...
  44586. this.pack();
  44587. //let stride = this.stride;
  44588. //for (let i = 0; i < count; i++) {
  44589. // let si = this._sortTable[i];
  44590. // if (!si) {
  44591. // si = new SortInfo();
  44592. // this._sortTable[i] = si;
  44593. // }
  44594. // si.entry = this._allEntries[i];
  44595. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  44596. // si.swapedOffset = null;
  44597. // this._sortedTable[i] = si;
  44598. //}
  44599. var curOffset = 0;
  44600. var stride = this.stride;
  44601. for (var i = 0; i < count; i++, curOffset += stride) {
  44602. var si = this._sortTable[i];
  44603. if (!si) {
  44604. si = new SortInfo();
  44605. this._sortTable[i] = si;
  44606. }
  44607. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  44608. si.offset = curOffset;
  44609. si.swapedOffset = null;
  44610. this._sortedTable[i] = si;
  44611. }
  44612. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  44613. if (this.sortingAscending) {
  44614. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  44615. }
  44616. else {
  44617. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  44618. }
  44619. var swapElements = function (src, dst) {
  44620. for (var i = 0; i < stride; i++) {
  44621. var tps = _this.buffer[dst + i];
  44622. _this.buffer[dst + i] = _this.buffer[src + i];
  44623. _this.buffer[src + i] = tps;
  44624. }
  44625. };
  44626. // The fun part begin, sortedTable give us the ordered layout to obtain, to get that we have to move elements, but when we move an element:
  44627. // it replaces an existing one.I don't want to allocate a new Float32Array and do a raw copy, because it's awful (GC - wise),
  44628. // and I still want something with a good algorithm complexity.
  44629. // So here's the deal: we are going to swap elements, but we have to track the change of location of the element being replaced,
  44630. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  44631. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  44632. // When we'll look for and element, we'll check if its swapedOffset is set, if so we reiterate the operation with the one there
  44633. // until we find a SortInfo object without a swapedOffset which means we got the right location
  44634. // Yes, we may have to do multiple iterations to find the right location, but hey, it won't be huge: <3 in most cases, and it's better
  44635. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  44636. for (var i = 0; i < count; i++) {
  44637. // Get the element to move
  44638. var sourceSI = this._sortedTable[i];
  44639. var destSI = this._sortTable[i];
  44640. var sourceOff = sourceSI.offset;
  44641. // If the source changed location, find the new one
  44642. if (sourceSI.swapedOffset) {
  44643. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  44644. var curSI = sourceSI;
  44645. while (curSI.swapedOffset) {
  44646. curSI = this._sortTable[curSI.swapedOffset / stride];
  44647. }
  44648. // Finally get the right location
  44649. sourceOff = curSI.offset;
  44650. }
  44651. // Tag the element being replaced with its new location
  44652. destSI.swapedOffset = sourceOff;
  44653. // Swap elements (only if needed)
  44654. if (sourceOff !== destSI.offset) {
  44655. swapElements(sourceOff, destSI.offset);
  44656. }
  44657. // Update the offset in the corresponding DFAE
  44658. //sourceSI.entry.offset = destSI.entry.offset;
  44659. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  44660. }
  44661. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  44662. return true;
  44663. };
  44664. return DynamicFloatArray;
  44665. }());
  44666. BABYLON.DynamicFloatArray = DynamicFloatArray;
  44667. var SortInfo = (function () {
  44668. function SortInfo() {
  44669. this.compareData = this.offset = this.swapedOffset = null;
  44670. }
  44671. return SortInfo;
  44672. }());
  44673. })(BABYLON || (BABYLON = {}));
  44674. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  44675. var BABYLON;
  44676. (function (BABYLON) {
  44677. var MapTexture = (function (_super) {
  44678. __extends(MapTexture, _super);
  44679. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  44680. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44681. if (useMipMap === void 0) { useMipMap = false; }
  44682. if (margin === void 0) { margin = 0; }
  44683. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  44684. _this.name = name;
  44685. _this._size = size;
  44686. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44687. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44688. // Create the rectPackMap that will allocate portion of the texture
  44689. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  44690. // Create the texture that will store the content
  44691. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  44692. return _this;
  44693. }
  44694. /**
  44695. * Allocate a rectangle of a given size in the texture map
  44696. * @param size the size of the rectangle to allocation
  44697. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  44698. */
  44699. MapTexture.prototype.allocateRect = function (size) {
  44700. return this._rectPackingMap.addRect(size);
  44701. };
  44702. /**
  44703. * Free a given rectangle from the texture map
  44704. * @param rectInfo the instance corresponding to the rect to free.
  44705. */
  44706. MapTexture.prototype.freeRect = function (rectInfo) {
  44707. if (rectInfo) {
  44708. rectInfo.freeContent();
  44709. }
  44710. };
  44711. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  44712. /**
  44713. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  44714. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  44715. * @returns {}
  44716. */
  44717. get: function () {
  44718. return this._rectPackingMap.freeSpace;
  44719. },
  44720. enumerable: true,
  44721. configurable: true
  44722. });
  44723. /**
  44724. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  44725. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  44726. * Don't forget to call unbindTexture when you're done rendering
  44727. * @param rect the zone to render to
  44728. * @param clear true to clear the portion's color/depth data
  44729. */
  44730. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  44731. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  44732. };
  44733. /**
  44734. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  44735. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  44736. * Don't forget to call unbindTexture when you're done rendering
  44737. * @param pos the position into the texture
  44738. * @param size the portion to fit the clip space to
  44739. * @param clear true to clear the portion's color/depth data
  44740. */
  44741. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  44742. var engine = this.getScene().getEngine();
  44743. engine.bindFramebuffer(this._texture);
  44744. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  44745. if (clear) {
  44746. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  44747. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  44748. }
  44749. };
  44750. /**
  44751. * Unbind the texture map from the rendering engine.
  44752. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  44753. * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
  44754. */
  44755. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  44756. // Dump ?
  44757. if (dumpForDebug) {
  44758. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  44759. }
  44760. var engine = this.getScene().getEngine();
  44761. if (this._replacedViewport) {
  44762. engine.setViewport(this._replacedViewport);
  44763. this._replacedViewport = null;
  44764. }
  44765. engine.unBindFramebuffer(this._texture);
  44766. };
  44767. Object.defineProperty(MapTexture.prototype, "canRescale", {
  44768. get: function () {
  44769. return false;
  44770. },
  44771. enumerable: true,
  44772. configurable: true
  44773. });
  44774. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  44775. // Anyway, there's not much point to use this method for this kind of texture I guess
  44776. MapTexture.prototype.clone = function () {
  44777. return null;
  44778. };
  44779. return MapTexture;
  44780. }(BABYLON.Texture));
  44781. BABYLON.MapTexture = MapTexture;
  44782. })(BABYLON || (BABYLON = {}));
  44783. //# sourceMappingURL=babylon.mapTexture.js.map
  44784. var BABYLON;
  44785. (function (BABYLON) {
  44786. var ShaderMaterial = (function (_super) {
  44787. __extends(ShaderMaterial, _super);
  44788. function ShaderMaterial(name, scene, shaderPath, options) {
  44789. var _this = _super.call(this, name, scene) || this;
  44790. _this._textures = {};
  44791. _this._textureArrays = {};
  44792. _this._floats = {};
  44793. _this._floatsArrays = {};
  44794. _this._colors3 = {};
  44795. _this._colors4 = {};
  44796. _this._vectors2 = {};
  44797. _this._vectors3 = {};
  44798. _this._vectors4 = {};
  44799. _this._matrices = {};
  44800. _this._matrices3x3 = {};
  44801. _this._matrices2x2 = {};
  44802. _this._vectors3Arrays = {};
  44803. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  44804. _this._shaderPath = shaderPath;
  44805. options.needAlphaBlending = options.needAlphaBlending || false;
  44806. options.needAlphaTesting = options.needAlphaTesting || false;
  44807. options.attributes = options.attributes || ["position", "normal", "uv"];
  44808. options.uniforms = options.uniforms || ["worldViewProjection"];
  44809. options.samplers = options.samplers || [];
  44810. options.defines = options.defines || [];
  44811. _this._options = options;
  44812. return _this;
  44813. }
  44814. ShaderMaterial.prototype.getClassName = function () {
  44815. return "ShaderMaterial";
  44816. };
  44817. ShaderMaterial.prototype.needAlphaBlending = function () {
  44818. return this._options.needAlphaBlending;
  44819. };
  44820. ShaderMaterial.prototype.needAlphaTesting = function () {
  44821. return this._options.needAlphaTesting;
  44822. };
  44823. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  44824. if (this._options.uniforms.indexOf(uniformName) === -1) {
  44825. this._options.uniforms.push(uniformName);
  44826. }
  44827. };
  44828. ShaderMaterial.prototype.setTexture = function (name, texture) {
  44829. if (this._options.samplers.indexOf(name) === -1) {
  44830. this._options.samplers.push(name);
  44831. }
  44832. this._textures[name] = texture;
  44833. return this;
  44834. };
  44835. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  44836. if (this._options.samplers.indexOf(name) === -1) {
  44837. this._options.samplers.push(name);
  44838. }
  44839. this._checkUniform(name);
  44840. this._textureArrays[name] = textures;
  44841. return this;
  44842. };
  44843. ShaderMaterial.prototype.setFloat = function (name, value) {
  44844. this._checkUniform(name);
  44845. this._floats[name] = value;
  44846. return this;
  44847. };
  44848. ShaderMaterial.prototype.setFloats = function (name, value) {
  44849. this._checkUniform(name);
  44850. this._floatsArrays[name] = value;
  44851. return this;
  44852. };
  44853. ShaderMaterial.prototype.setColor3 = function (name, value) {
  44854. this._checkUniform(name);
  44855. this._colors3[name] = value;
  44856. return this;
  44857. };
  44858. ShaderMaterial.prototype.setColor4 = function (name, value) {
  44859. this._checkUniform(name);
  44860. this._colors4[name] = value;
  44861. return this;
  44862. };
  44863. ShaderMaterial.prototype.setVector2 = function (name, value) {
  44864. this._checkUniform(name);
  44865. this._vectors2[name] = value;
  44866. return this;
  44867. };
  44868. ShaderMaterial.prototype.setVector3 = function (name, value) {
  44869. this._checkUniform(name);
  44870. this._vectors3[name] = value;
  44871. return this;
  44872. };
  44873. ShaderMaterial.prototype.setVector4 = function (name, value) {
  44874. this._checkUniform(name);
  44875. this._vectors4[name] = value;
  44876. return this;
  44877. };
  44878. ShaderMaterial.prototype.setMatrix = function (name, value) {
  44879. this._checkUniform(name);
  44880. this._matrices[name] = value;
  44881. return this;
  44882. };
  44883. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  44884. this._checkUniform(name);
  44885. this._matrices3x3[name] = value;
  44886. return this;
  44887. };
  44888. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  44889. this._checkUniform(name);
  44890. this._matrices2x2[name] = value;
  44891. return this;
  44892. };
  44893. ShaderMaterial.prototype.setArray3 = function (name, value) {
  44894. this._checkUniform(name);
  44895. this._vectors3Arrays[name] = value;
  44896. return this;
  44897. };
  44898. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  44899. if (!mesh) {
  44900. return true;
  44901. }
  44902. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  44903. return false;
  44904. }
  44905. return false;
  44906. };
  44907. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  44908. var scene = this.getScene();
  44909. var engine = scene.getEngine();
  44910. if (!this.checkReadyOnEveryCall) {
  44911. if (this._renderId === scene.getRenderId()) {
  44912. if (this._checkCache(scene, mesh, useInstances)) {
  44913. return true;
  44914. }
  44915. }
  44916. }
  44917. // Instances
  44918. var defines = [];
  44919. var fallbacks = new BABYLON.EffectFallbacks();
  44920. if (useInstances) {
  44921. defines.push("#define INSTANCES");
  44922. }
  44923. for (var index = 0; index < this._options.defines.length; index++) {
  44924. defines.push(this._options.defines[index]);
  44925. }
  44926. // Bones
  44927. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  44928. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44929. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44930. fallbacks.addCPUSkinningFallback(0, mesh);
  44931. }
  44932. // Alpha test
  44933. if (engine.getAlphaTesting()) {
  44934. defines.push("#define ALPHATEST");
  44935. }
  44936. var previousEffect = this._effect;
  44937. var join = defines.join("\n");
  44938. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  44939. if (!this._effect.isReady()) {
  44940. return false;
  44941. }
  44942. if (previousEffect !== this._effect) {
  44943. scene.resetCachedMaterial();
  44944. }
  44945. this._renderId = scene.getRenderId();
  44946. return true;
  44947. };
  44948. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  44949. var scene = this.getScene();
  44950. if (this._options.uniforms.indexOf("world") !== -1) {
  44951. this._effect.setMatrix("world", world);
  44952. }
  44953. if (this._options.uniforms.indexOf("worldView") !== -1) {
  44954. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  44955. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  44956. }
  44957. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  44958. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  44959. }
  44960. };
  44961. ShaderMaterial.prototype.bind = function (world, mesh) {
  44962. // Std values
  44963. this.bindOnlyWorldMatrix(world);
  44964. if (this.getScene().getCachedMaterial() !== this) {
  44965. if (this._options.uniforms.indexOf("view") !== -1) {
  44966. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  44967. }
  44968. if (this._options.uniforms.indexOf("projection") !== -1) {
  44969. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  44970. }
  44971. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  44972. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  44973. }
  44974. // Bones
  44975. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  44976. var name;
  44977. // Texture
  44978. for (name in this._textures) {
  44979. this._effect.setTexture(name, this._textures[name]);
  44980. }
  44981. // Texture arrays
  44982. for (name in this._textureArrays) {
  44983. this._effect.setTextureArray(name, this._textureArrays[name]);
  44984. }
  44985. // Float
  44986. for (name in this._floats) {
  44987. this._effect.setFloat(name, this._floats[name]);
  44988. }
  44989. // Float s
  44990. for (name in this._floatsArrays) {
  44991. this._effect.setArray(name, this._floatsArrays[name]);
  44992. }
  44993. // Color3
  44994. for (name in this._colors3) {
  44995. this._effect.setColor3(name, this._colors3[name]);
  44996. }
  44997. // Color4
  44998. for (name in this._colors4) {
  44999. var color = this._colors4[name];
  45000. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  45001. }
  45002. // Vector2
  45003. for (name in this._vectors2) {
  45004. this._effect.setVector2(name, this._vectors2[name]);
  45005. }
  45006. // Vector3
  45007. for (name in this._vectors3) {
  45008. this._effect.setVector3(name, this._vectors3[name]);
  45009. }
  45010. // Vector4
  45011. for (name in this._vectors4) {
  45012. this._effect.setVector4(name, this._vectors4[name]);
  45013. }
  45014. // Matrix
  45015. for (name in this._matrices) {
  45016. this._effect.setMatrix(name, this._matrices[name]);
  45017. }
  45018. // Matrix 3x3
  45019. for (name in this._matrices3x3) {
  45020. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  45021. }
  45022. // Matrix 2x2
  45023. for (name in this._matrices2x2) {
  45024. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  45025. }
  45026. // Vector3Array
  45027. for (name in this._vectors3Arrays) {
  45028. this._effect.setArray3(name, this._vectors3Arrays[name]);
  45029. }
  45030. }
  45031. _super.prototype.bind.call(this, world, mesh);
  45032. };
  45033. ShaderMaterial.prototype.clone = function (name) {
  45034. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  45035. return newShaderMaterial;
  45036. };
  45037. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45038. if (forceDisposeTextures) {
  45039. var name;
  45040. for (name in this._textures) {
  45041. this._textures[name].dispose();
  45042. }
  45043. for (name in this._textureArrays) {
  45044. var array = this._textureArrays[name];
  45045. for (var index = 0; index < array.length; index++) {
  45046. array[index].dispose();
  45047. }
  45048. }
  45049. }
  45050. this._textures = {};
  45051. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45052. };
  45053. ShaderMaterial.prototype.serialize = function () {
  45054. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45055. serializationObject.customType = "BABYLON.ShaderMaterial";
  45056. serializationObject.options = this._options;
  45057. serializationObject.shaderPath = this._shaderPath;
  45058. var name;
  45059. // Texture
  45060. serializationObject.textures = {};
  45061. for (name in this._textures) {
  45062. serializationObject.textures[name] = this._textures[name].serialize();
  45063. }
  45064. // Texture arrays
  45065. serializationObject.textureArrays = {};
  45066. for (name in this._textureArrays) {
  45067. serializationObject.textureArrays[name] = [];
  45068. var array = this._textureArrays[name];
  45069. for (var index = 0; index < array.length; index++) {
  45070. serializationObject.textureArrays[name].push(array[index].serialize());
  45071. }
  45072. }
  45073. // Float
  45074. serializationObject.floats = {};
  45075. for (name in this._floats) {
  45076. serializationObject.floats[name] = this._floats[name];
  45077. }
  45078. // Float s
  45079. serializationObject.floatArrays = {};
  45080. for (name in this._floatsArrays) {
  45081. serializationObject.floatArrays[name] = this._floatsArrays[name];
  45082. }
  45083. // Color3
  45084. serializationObject.colors3 = {};
  45085. for (name in this._colors3) {
  45086. serializationObject.colors3[name] = this._colors3[name].asArray();
  45087. }
  45088. // Color4
  45089. serializationObject.colors4 = {};
  45090. for (name in this._colors4) {
  45091. serializationObject.colors4[name] = this._colors4[name].asArray();
  45092. }
  45093. // Vector2
  45094. serializationObject.vectors2 = {};
  45095. for (name in this._vectors2) {
  45096. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  45097. }
  45098. // Vector3
  45099. serializationObject.vectors3 = {};
  45100. for (name in this._vectors3) {
  45101. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  45102. }
  45103. // Vector4
  45104. serializationObject.vectors4 = {};
  45105. for (name in this._vectors4) {
  45106. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  45107. }
  45108. // Matrix
  45109. serializationObject.matrices = {};
  45110. for (name in this._matrices) {
  45111. serializationObject.matrices[name] = this._matrices[name].asArray();
  45112. }
  45113. // Matrix 3x3
  45114. serializationObject.matrices3x3 = {};
  45115. for (name in this._matrices3x3) {
  45116. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  45117. }
  45118. // Matrix 2x2
  45119. serializationObject.matrices2x2 = {};
  45120. for (name in this._matrices2x2) {
  45121. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  45122. }
  45123. // Vector3Array
  45124. serializationObject.vectors3Arrays = {};
  45125. for (name in this._vectors3Arrays) {
  45126. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  45127. }
  45128. return serializationObject;
  45129. };
  45130. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  45131. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  45132. var name;
  45133. // Texture
  45134. for (name in source.textures) {
  45135. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  45136. }
  45137. // Texture arrays
  45138. for (name in source.textureArrays) {
  45139. var array = source.textureArrays[name];
  45140. var textureArray = new Array();
  45141. for (var index = 0; index < array.length; index++) {
  45142. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  45143. }
  45144. material.setTextureArray(name, textureArray);
  45145. }
  45146. // Float
  45147. for (name in source.floats) {
  45148. material.setFloat(name, source.floats[name]);
  45149. }
  45150. // Float s
  45151. for (name in source.floatsArrays) {
  45152. material.setFloats(name, source.floatsArrays[name]);
  45153. }
  45154. // Color3
  45155. for (name in source.colors3) {
  45156. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  45157. }
  45158. // Color4
  45159. for (name in source.colors4) {
  45160. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  45161. }
  45162. // Vector2
  45163. for (name in source.vectors2) {
  45164. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  45165. }
  45166. // Vector3
  45167. for (name in source.vectors3) {
  45168. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  45169. }
  45170. // Vector4
  45171. for (name in source.vectors4) {
  45172. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  45173. }
  45174. // Matrix
  45175. for (name in source.matrices) {
  45176. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  45177. }
  45178. // Matrix 3x3
  45179. for (name in source.matrices3x3) {
  45180. material.setMatrix3x3(name, source.matrices3x3[name]);
  45181. }
  45182. // Matrix 2x2
  45183. for (name in source.matrices2x2) {
  45184. material.setMatrix2x2(name, source.matrices2x2[name]);
  45185. }
  45186. // Vector3Array
  45187. for (name in source.vectors3Arrays) {
  45188. material.setArray3(name, source.vectors3Arrays[name]);
  45189. }
  45190. return material;
  45191. };
  45192. return ShaderMaterial;
  45193. }(BABYLON.Material));
  45194. BABYLON.ShaderMaterial = ShaderMaterial;
  45195. })(BABYLON || (BABYLON = {}));
  45196. //# sourceMappingURL=babylon.shaderMaterial.js.map
  45197. var BABYLON;
  45198. (function (BABYLON) {
  45199. var Internals;
  45200. (function (Internals) {
  45201. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  45202. // All values and structures referenced from:
  45203. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  45204. var DDS_MAGIC = 0x20534444;
  45205. 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;
  45206. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  45207. 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;
  45208. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  45209. function FourCCToInt32(value) {
  45210. return value.charCodeAt(0) +
  45211. (value.charCodeAt(1) << 8) +
  45212. (value.charCodeAt(2) << 16) +
  45213. (value.charCodeAt(3) << 24);
  45214. }
  45215. function Int32ToFourCC(value) {
  45216. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  45217. }
  45218. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  45219. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  45220. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  45221. var headerLengthInt = 31; // The header length in 32 bit ints
  45222. // Offsets into the header array
  45223. var off_magic = 0;
  45224. var off_size = 1;
  45225. var off_flags = 2;
  45226. var off_height = 3;
  45227. var off_width = 4;
  45228. var off_mipmapCount = 7;
  45229. var off_pfFlags = 20;
  45230. var off_pfFourCC = 21;
  45231. var off_RGBbpp = 22;
  45232. var off_RMask = 23;
  45233. var off_GMask = 24;
  45234. var off_BMask = 25;
  45235. var off_AMask = 26;
  45236. var off_caps1 = 27;
  45237. var off_caps2 = 28;
  45238. ;
  45239. var DDSTools = (function () {
  45240. function DDSTools() {
  45241. }
  45242. DDSTools.GetDDSInfo = function (arrayBuffer) {
  45243. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  45244. var mipmapCount = 1;
  45245. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  45246. mipmapCount = Math.max(1, header[off_mipmapCount]);
  45247. }
  45248. return {
  45249. width: header[off_width],
  45250. height: header[off_height],
  45251. mipmapCount: mipmapCount,
  45252. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  45253. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  45254. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  45255. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  45256. };
  45257. };
  45258. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45259. var byteArray = new Uint8Array(dataLength);
  45260. var srcData = new Uint8Array(arrayBuffer);
  45261. var index = 0;
  45262. for (var y = height - 1; y >= 0; y--) {
  45263. for (var x = 0; x < width; x++) {
  45264. var srcPos = dataOffset + (x + y * width) * 4;
  45265. byteArray[index + 2] = srcData[srcPos];
  45266. byteArray[index + 1] = srcData[srcPos + 1];
  45267. byteArray[index] = srcData[srcPos + 2];
  45268. byteArray[index + 3] = srcData[srcPos + 3];
  45269. index += 4;
  45270. }
  45271. }
  45272. return byteArray;
  45273. };
  45274. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45275. var byteArray = new Uint8Array(dataLength);
  45276. var srcData = new Uint8Array(arrayBuffer);
  45277. var index = 0;
  45278. for (var y = height - 1; y >= 0; y--) {
  45279. for (var x = 0; x < width; x++) {
  45280. var srcPos = dataOffset + (x + y * width) * 3;
  45281. byteArray[index + 2] = srcData[srcPos];
  45282. byteArray[index + 1] = srcData[srcPos + 1];
  45283. byteArray[index] = srcData[srcPos + 2];
  45284. index += 3;
  45285. }
  45286. }
  45287. return byteArray;
  45288. };
  45289. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45290. var byteArray = new Uint8Array(dataLength);
  45291. var srcData = new Uint8Array(arrayBuffer);
  45292. var index = 0;
  45293. for (var y = height - 1; y >= 0; y--) {
  45294. for (var x = 0; x < width; x++) {
  45295. var srcPos = dataOffset + (x + y * width);
  45296. byteArray[index] = srcData[srcPos];
  45297. index++;
  45298. }
  45299. }
  45300. return byteArray;
  45301. };
  45302. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  45303. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  45304. if (header[off_magic] != DDS_MAGIC) {
  45305. BABYLON.Tools.Error("Invalid magic number in DDS header");
  45306. return;
  45307. }
  45308. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  45309. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  45310. return;
  45311. }
  45312. if (info.isFourCC) {
  45313. fourCC = header[off_pfFourCC];
  45314. switch (fourCC) {
  45315. case FOURCC_DXT1:
  45316. blockBytes = 8;
  45317. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45318. break;
  45319. case FOURCC_DXT3:
  45320. blockBytes = 16;
  45321. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45322. break;
  45323. case FOURCC_DXT5:
  45324. blockBytes = 16;
  45325. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45326. break;
  45327. default:
  45328. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  45329. return;
  45330. }
  45331. }
  45332. mipmapCount = 1;
  45333. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  45334. mipmapCount = Math.max(1, header[off_mipmapCount]);
  45335. }
  45336. var bpp = header[off_RGBbpp];
  45337. for (var face = 0; face < faces; face++) {
  45338. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  45339. width = header[off_width];
  45340. height = header[off_height];
  45341. dataOffset = header[off_size] + 4;
  45342. for (i = 0; i < mipmapCount; ++i) {
  45343. if (info.isRGB) {
  45344. if (bpp === 24) {
  45345. dataLength = width * height * 3;
  45346. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45347. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  45348. }
  45349. else {
  45350. dataLength = width * height * 4;
  45351. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45352. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  45353. }
  45354. }
  45355. else if (info.isLuminance) {
  45356. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  45357. var unpaddedRowSize = width;
  45358. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  45359. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  45360. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45361. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  45362. }
  45363. else {
  45364. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  45365. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  45366. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  45367. }
  45368. dataOffset += dataLength;
  45369. width *= 0.5;
  45370. height *= 0.5;
  45371. width = Math.max(1.0, width);
  45372. height = Math.max(1.0, height);
  45373. }
  45374. }
  45375. };
  45376. return DDSTools;
  45377. }());
  45378. Internals.DDSTools = DDSTools;
  45379. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45380. })(BABYLON || (BABYLON = {}));
  45381. //# sourceMappingURL=babylon.tools.dds.js.map
  45382. var BABYLON;
  45383. (function (BABYLON) {
  45384. var Internals;
  45385. (function (Internals) {
  45386. /**
  45387. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  45388. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  45389. */
  45390. var KhronosTextureContainer = (function () {
  45391. /**
  45392. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  45393. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  45394. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  45395. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  45396. */
  45397. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  45398. this.arrayBuffer = arrayBuffer;
  45399. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  45400. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  45401. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  45402. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  45403. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  45404. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  45405. BABYLON.Tools.Error("texture missing KTX identifier");
  45406. return;
  45407. }
  45408. // load the reset of the header in native 32 bit int
  45409. var header = new Int32Array(this.arrayBuffer, 12, 13);
  45410. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  45411. var oppositeEndianess = header[0] === 0x01020304;
  45412. // read all the header elements in order they exist in the file, without modification (sans endainness)
  45413. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  45414. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  45415. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  45416. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  45417. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  45418. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  45419. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  45420. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  45421. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  45422. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  45423. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  45424. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  45425. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  45426. if (this.glType !== 0) {
  45427. BABYLON.Tools.Error("only compressed formats currently supported");
  45428. return;
  45429. }
  45430. else {
  45431. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  45432. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  45433. }
  45434. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  45435. BABYLON.Tools.Error("only 2D textures currently supported");
  45436. return;
  45437. }
  45438. if (this.numberOfArrayElements !== 0) {
  45439. BABYLON.Tools.Error("texture arrays not currently supported");
  45440. return;
  45441. }
  45442. if (this.numberOfFaces !== facesExpected) {
  45443. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  45444. return;
  45445. }
  45446. // we now have a completely validated file, so could use existence of loadType as success
  45447. // would need to make this more elaborate & adjust checks above to support more than one load type
  45448. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  45449. }
  45450. // not as fast hardware based, but will probably never need to use
  45451. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  45452. return ((val & 0xFF) << 24)
  45453. | ((val & 0xFF00) << 8)
  45454. | ((val >> 8) & 0xFF00)
  45455. | ((val >> 24) & 0xFF);
  45456. };
  45457. /**
  45458. * It is assumed that the texture has already been created & is currently bound
  45459. */
  45460. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  45461. switch (this.loadType) {
  45462. case KhronosTextureContainer.COMPRESSED_2D:
  45463. this._upload2DCompressedLevels(gl, loadMipmaps);
  45464. break;
  45465. case KhronosTextureContainer.TEX_2D:
  45466. case KhronosTextureContainer.COMPRESSED_3D:
  45467. case KhronosTextureContainer.TEX_3D:
  45468. }
  45469. };
  45470. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  45471. // initialize width & height for level 1
  45472. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  45473. var width = this.pixelWidth;
  45474. var height = this.pixelHeight;
  45475. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  45476. for (var level = 0; level < mipmapCount; level++) {
  45477. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  45478. for (var face = 0; face < this.numberOfFaces; face++) {
  45479. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  45480. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  45481. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  45482. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  45483. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  45484. }
  45485. width = Math.max(1.0, width * 0.5);
  45486. height = Math.max(1.0, height * 0.5);
  45487. }
  45488. };
  45489. return KhronosTextureContainer;
  45490. }());
  45491. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  45492. // load types
  45493. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  45494. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  45495. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  45496. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  45497. Internals.KhronosTextureContainer = KhronosTextureContainer;
  45498. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45499. })(BABYLON || (BABYLON = {}));
  45500. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  45501. var BABYLON;
  45502. (function (BABYLON) {
  45503. var CannonJSPlugin = (function () {
  45504. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  45505. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  45506. if (iterations === void 0) { iterations = 10; }
  45507. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  45508. this.name = "CannonJSPlugin";
  45509. this._physicsMaterials = [];
  45510. this._fixedTimeStep = 1 / 60;
  45511. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  45512. this._currentCollisionGroup = 2;
  45513. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  45514. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  45515. this._tmpPosition = BABYLON.Vector3.Zero();
  45516. this._tmpQuaternion = new BABYLON.Quaternion();
  45517. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  45518. this._tmpDeltaRotation = new BABYLON.Quaternion();
  45519. this._tmpUnityRotation = new BABYLON.Quaternion();
  45520. if (!this.isSupported()) {
  45521. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  45522. return;
  45523. }
  45524. this.world = new CANNON.World();
  45525. this.world.broadphase = new CANNON.NaiveBroadphase();
  45526. this.world.solver.iterations = iterations;
  45527. }
  45528. CannonJSPlugin.prototype.setGravity = function (gravity) {
  45529. this.world.gravity.copy(gravity);
  45530. };
  45531. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  45532. this._fixedTimeStep = timeStep;
  45533. };
  45534. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  45535. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  45536. };
  45537. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  45538. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  45539. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  45540. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  45541. };
  45542. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  45543. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  45544. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  45545. impostor.physicsBody.applyForce(impulse, worldPoint);
  45546. };
  45547. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  45548. //parent-child relationship. Does this impostor has a parent impostor?
  45549. if (impostor.parent) {
  45550. if (impostor.physicsBody) {
  45551. this.removePhysicsBody(impostor);
  45552. //TODO is that needed?
  45553. impostor.forceUpdate();
  45554. }
  45555. return;
  45556. }
  45557. //should a new body be created for this impostor?
  45558. if (impostor.isBodyInitRequired()) {
  45559. var shape = this._createShape(impostor);
  45560. //unregister events, if body is being changed
  45561. var oldBody = impostor.physicsBody;
  45562. if (oldBody) {
  45563. this.removePhysicsBody(impostor);
  45564. }
  45565. //create the body and material
  45566. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  45567. var bodyCreationObject = {
  45568. mass: impostor.getParam("mass"),
  45569. material: material
  45570. };
  45571. // A simple extend, in case native options were used.
  45572. var nativeOptions = impostor.getParam("nativeOptions");
  45573. for (var key in nativeOptions) {
  45574. if (nativeOptions.hasOwnProperty(key)) {
  45575. bodyCreationObject[key] = nativeOptions[key];
  45576. }
  45577. }
  45578. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  45579. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  45580. this.world.addEventListener("preStep", impostor.beforeStep);
  45581. this.world.addEventListener("postStep", impostor.afterStep);
  45582. impostor.physicsBody.addShape(shape);
  45583. this.world.add(impostor.physicsBody);
  45584. //try to keep the body moving in the right direction by taking old properties.
  45585. //Should be tested!
  45586. if (oldBody) {
  45587. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  45588. impostor.physicsBody[param].copy(oldBody[param]);
  45589. });
  45590. }
  45591. this._processChildMeshes(impostor);
  45592. }
  45593. //now update the body's transformation
  45594. this._updatePhysicsBodyTransformation(impostor);
  45595. };
  45596. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  45597. var _this = this;
  45598. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  45599. if (meshChildren.length) {
  45600. var processMesh = function (localPosition, mesh) {
  45601. var childImpostor = mesh.getPhysicsImpostor();
  45602. if (childImpostor) {
  45603. var parent = childImpostor.parent;
  45604. if (parent !== mainImpostor) {
  45605. var localPosition = mesh.position;
  45606. if (childImpostor.physicsBody) {
  45607. _this.removePhysicsBody(childImpostor);
  45608. childImpostor.physicsBody = null;
  45609. }
  45610. childImpostor.parent = mainImpostor;
  45611. childImpostor.resetUpdateFlags();
  45612. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  45613. //Add the mass of the children.
  45614. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  45615. }
  45616. }
  45617. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  45618. };
  45619. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  45620. }
  45621. };
  45622. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  45623. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  45624. this.world.removeEventListener("preStep", impostor.beforeStep);
  45625. this.world.removeEventListener("postStep", impostor.afterStep);
  45626. this.world.remove(impostor.physicsBody);
  45627. };
  45628. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  45629. var mainBody = impostorJoint.mainImpostor.physicsBody;
  45630. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  45631. if (!mainBody || !connectedBody) {
  45632. return;
  45633. }
  45634. var constraint;
  45635. var jointData = impostorJoint.joint.jointData;
  45636. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  45637. var constraintData = {
  45638. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  45639. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  45640. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  45641. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  45642. maxForce: jointData.nativeParams.maxForce,
  45643. collideConnected: !!jointData.collision
  45644. };
  45645. switch (impostorJoint.joint.type) {
  45646. case BABYLON.PhysicsJoint.HingeJoint:
  45647. case BABYLON.PhysicsJoint.Hinge2Joint:
  45648. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  45649. break;
  45650. case BABYLON.PhysicsJoint.DistanceJoint:
  45651. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  45652. break;
  45653. case BABYLON.PhysicsJoint.SpringJoint:
  45654. var springData = jointData;
  45655. constraint = new CANNON.Spring(mainBody, connectedBody, {
  45656. restLength: springData.length,
  45657. stiffness: springData.stiffness,
  45658. damping: springData.damping,
  45659. localAnchorA: constraintData.pivotA,
  45660. localAnchorB: constraintData.pivotB
  45661. });
  45662. break;
  45663. case BABYLON.PhysicsJoint.LockJoint:
  45664. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  45665. break;
  45666. case BABYLON.PhysicsJoint.PointToPointJoint:
  45667. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  45668. default:
  45669. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  45670. break;
  45671. }
  45672. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  45673. constraint.collideConnected = !!jointData.collision;
  45674. impostorJoint.joint.physicsJoint = constraint;
  45675. //don't add spring as constraint, as it is not one.
  45676. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  45677. this.world.addConstraint(constraint);
  45678. }
  45679. else {
  45680. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  45681. constraint.applyForce();
  45682. });
  45683. }
  45684. };
  45685. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  45686. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  45687. };
  45688. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  45689. var index;
  45690. var mat;
  45691. for (index = 0; index < this._physicsMaterials.length; index++) {
  45692. mat = this._physicsMaterials[index];
  45693. if (mat.friction === friction && mat.restitution === restitution) {
  45694. return mat;
  45695. }
  45696. }
  45697. var currentMat = new CANNON.Material(name);
  45698. currentMat.friction = friction;
  45699. currentMat.restitution = restitution;
  45700. this._physicsMaterials.push(currentMat);
  45701. return currentMat;
  45702. };
  45703. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  45704. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  45705. };
  45706. CannonJSPlugin.prototype._createShape = function (impostor) {
  45707. var object = impostor.object;
  45708. var returnValue;
  45709. var extendSize = impostor.getObjectExtendSize();
  45710. switch (impostor.type) {
  45711. case BABYLON.PhysicsImpostor.SphereImpostor:
  45712. var radiusX = extendSize.x;
  45713. var radiusY = extendSize.y;
  45714. var radiusZ = extendSize.z;
  45715. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  45716. break;
  45717. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  45718. case BABYLON.PhysicsImpostor.CylinderImpostor:
  45719. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  45720. break;
  45721. case BABYLON.PhysicsImpostor.BoxImpostor:
  45722. var box = extendSize.scale(0.5);
  45723. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  45724. break;
  45725. case BABYLON.PhysicsImpostor.PlaneImpostor:
  45726. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  45727. returnValue = new CANNON.Plane();
  45728. break;
  45729. case BABYLON.PhysicsImpostor.MeshImpostor:
  45730. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  45731. var rawFaces = object.getIndices ? object.getIndices() : [];
  45732. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  45733. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  45734. break;
  45735. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  45736. returnValue = this._createHeightmap(object);
  45737. break;
  45738. case BABYLON.PhysicsImpostor.ParticleImpostor:
  45739. returnValue = new CANNON.Particle();
  45740. break;
  45741. }
  45742. return returnValue;
  45743. };
  45744. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  45745. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45746. var matrix = [];
  45747. //For now pointDepth will not be used and will be automatically calculated.
  45748. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  45749. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  45750. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  45751. var elementSize = dim * 2 / arraySize;
  45752. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  45753. for (var i = 0; i < pos.length; i = i + 3) {
  45754. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  45755. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  45756. var y = pos[i + 1] + minY;
  45757. if (!matrix[x]) {
  45758. matrix[x] = [];
  45759. }
  45760. if (!matrix[x][z]) {
  45761. matrix[x][z] = y;
  45762. }
  45763. matrix[x][z] = Math.max(y, matrix[x][z]);
  45764. }
  45765. for (var x = 0; x <= arraySize; ++x) {
  45766. if (!matrix[x]) {
  45767. var loc = 1;
  45768. while (!matrix[(x + loc) % arraySize]) {
  45769. loc++;
  45770. }
  45771. matrix[x] = matrix[(x + loc) % arraySize].slice();
  45772. }
  45773. for (var z = 0; z <= arraySize; ++z) {
  45774. if (!matrix[x][z]) {
  45775. var loc = 1;
  45776. var newValue;
  45777. while (newValue === undefined) {
  45778. newValue = matrix[x][(z + loc++) % arraySize];
  45779. }
  45780. matrix[x][z] = newValue;
  45781. }
  45782. }
  45783. }
  45784. var shape = new CANNON.Heightfield(matrix, {
  45785. elementSize: elementSize
  45786. });
  45787. //For future reference, needed for body transformation
  45788. shape.minY = minY;
  45789. return shape;
  45790. };
  45791. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  45792. var object = impostor.object;
  45793. //make sure it is updated...
  45794. object.computeWorldMatrix && object.computeWorldMatrix(true);
  45795. // The delta between the mesh position and the mesh bounding box center
  45796. var center = impostor.getObjectCenter();
  45797. var extendSize = impostor.getObjectExtendSize();
  45798. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  45799. this._tmpPosition.copyFrom(center);
  45800. var quaternion = object.rotationQuaternion;
  45801. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  45802. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  45803. //-90 DEG in X, precalculated
  45804. quaternion = quaternion.multiply(this._minus90X);
  45805. //Invert! (Precalculated, 90 deg in X)
  45806. //No need to clone. this will never change.
  45807. impostor.setDeltaRotation(this._plus90X);
  45808. }
  45809. //If it is a heightfield, if should be centered.
  45810. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  45811. var mesh = object;
  45812. //calculate the correct body position:
  45813. var rotationQuaternion = mesh.rotationQuaternion;
  45814. mesh.rotationQuaternion = this._tmpUnityRotation;
  45815. mesh.computeWorldMatrix(true);
  45816. //get original center with no rotation
  45817. var c = center.clone();
  45818. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  45819. //rotation is back
  45820. mesh.rotationQuaternion = rotationQuaternion;
  45821. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  45822. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  45823. mesh.setPivotMatrix(p);
  45824. mesh.computeWorldMatrix(true);
  45825. //calculate the translation
  45826. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  45827. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  45828. //add it inverted to the delta
  45829. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  45830. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  45831. mesh.setPivotMatrix(oldPivot);
  45832. mesh.computeWorldMatrix(true);
  45833. }
  45834. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  45835. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  45836. this._tmpPosition.copyFrom(object.position);
  45837. }
  45838. impostor.setDeltaPosition(this._tmpDeltaPosition);
  45839. //Now update the impostor object
  45840. impostor.physicsBody.position.copy(this._tmpPosition);
  45841. impostor.physicsBody.quaternion.copy(quaternion);
  45842. };
  45843. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  45844. impostor.object.position.copyFrom(impostor.physicsBody.position);
  45845. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  45846. };
  45847. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  45848. impostor.physicsBody.position.copy(newPosition);
  45849. impostor.physicsBody.quaternion.copy(newRotation);
  45850. };
  45851. CannonJSPlugin.prototype.isSupported = function () {
  45852. return window.CANNON !== undefined;
  45853. };
  45854. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  45855. impostor.physicsBody.velocity.copy(velocity);
  45856. };
  45857. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  45858. impostor.physicsBody.angularVelocity.copy(velocity);
  45859. };
  45860. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  45861. var v = impostor.physicsBody.velocity;
  45862. if (!v)
  45863. return null;
  45864. return new BABYLON.Vector3(v.x, v.y, v.z);
  45865. };
  45866. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  45867. var v = impostor.physicsBody.angularVelocity;
  45868. if (!v)
  45869. return null;
  45870. return new BABYLON.Vector3(v.x, v.y, v.z);
  45871. };
  45872. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  45873. impostor.physicsBody.mass = mass;
  45874. impostor.physicsBody.updateMassProperties();
  45875. };
  45876. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  45877. impostor.physicsBody.sleep();
  45878. };
  45879. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  45880. impostor.physicsBody.wakeUp();
  45881. };
  45882. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  45883. joint.physicsJoint.distance = maxDistance;
  45884. };
  45885. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  45886. if (!motorIndex) {
  45887. joint.physicsJoint.enableMotor();
  45888. }
  45889. };
  45890. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  45891. if (!motorIndex) {
  45892. joint.physicsJoint.disableMotor();
  45893. }
  45894. };
  45895. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  45896. if (!motorIndex) {
  45897. joint.physicsJoint.enableMotor();
  45898. joint.physicsJoint.setMotorSpeed(speed);
  45899. if (maxForce) {
  45900. this.setLimit(joint, maxForce);
  45901. }
  45902. }
  45903. };
  45904. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  45905. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  45906. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  45907. };
  45908. CannonJSPlugin.prototype.dispose = function () {
  45909. //nothing to do, actually.
  45910. };
  45911. return CannonJSPlugin;
  45912. }());
  45913. BABYLON.CannonJSPlugin = CannonJSPlugin;
  45914. })(BABYLON || (BABYLON = {}));
  45915. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  45916. var BABYLON;
  45917. (function (BABYLON) {
  45918. var OimoJSPlugin = (function () {
  45919. function OimoJSPlugin(iterations) {
  45920. this.name = "OimoJSPlugin";
  45921. this._tmpImpostorsArray = [];
  45922. this._tmpPositionVector = BABYLON.Vector3.Zero();
  45923. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  45924. this.world.worldscale(1);
  45925. this.world.clear();
  45926. //making sure no stats are calculated
  45927. this.world.isNoStat = true;
  45928. }
  45929. OimoJSPlugin.prototype.setGravity = function (gravity) {
  45930. this.world.gravity.copy(gravity);
  45931. };
  45932. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  45933. this.world.timeStep = timeStep;
  45934. };
  45935. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  45936. var _this = this;
  45937. impostors.forEach(function (impostor) {
  45938. impostor.beforeStep();
  45939. });
  45940. this.world.step();
  45941. impostors.forEach(function (impostor) {
  45942. impostor.afterStep();
  45943. //update the ordered impostors array
  45944. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  45945. });
  45946. //check for collisions
  45947. var contact = this.world.contacts;
  45948. while (contact !== null) {
  45949. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  45950. contact = contact.next;
  45951. continue;
  45952. }
  45953. //is this body colliding with any other? get the impostor
  45954. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  45955. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  45956. if (!mainImpostor || !collidingImpostor) {
  45957. contact = contact.next;
  45958. continue;
  45959. }
  45960. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  45961. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  45962. contact = contact.next;
  45963. }
  45964. };
  45965. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  45966. var mass = impostor.physicsBody.massInfo.mass;
  45967. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  45968. };
  45969. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  45970. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  45971. this.applyImpulse(impostor, force, contactPoint);
  45972. };
  45973. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  45974. var _this = this;
  45975. //parent-child relationship. Does this impostor has a parent impostor?
  45976. if (impostor.parent) {
  45977. if (impostor.physicsBody) {
  45978. this.removePhysicsBody(impostor);
  45979. //TODO is that needed?
  45980. impostor.forceUpdate();
  45981. }
  45982. return;
  45983. }
  45984. if (impostor.isBodyInitRequired()) {
  45985. var bodyConfig = {
  45986. name: impostor.uniqueId,
  45987. //Oimo must have mass, also for static objects.
  45988. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  45989. size: [],
  45990. type: [],
  45991. pos: [],
  45992. rot: [],
  45993. move: impostor.getParam("mass") !== 0,
  45994. //Supporting older versions of Oimo
  45995. world: this.world
  45996. };
  45997. var impostors = [impostor];
  45998. var addToArray = function (parent) {
  45999. if (!parent.getChildMeshes)
  46000. return;
  46001. parent.getChildMeshes().forEach(function (m) {
  46002. if (m.physicsImpostor) {
  46003. impostors.push(m.physicsImpostor);
  46004. m.physicsImpostor._init();
  46005. }
  46006. });
  46007. };
  46008. addToArray(impostor.object);
  46009. var checkWithEpsilon_1 = function (value) {
  46010. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  46011. };
  46012. impostors.forEach(function (i) {
  46013. //get the correct bounding box
  46014. var oldQuaternion = i.object.rotationQuaternion;
  46015. var rot = new OIMO.Euler().setFromQuaternion({
  46016. x: impostor.object.rotationQuaternion.x,
  46017. y: impostor.object.rotationQuaternion.y,
  46018. z: impostor.object.rotationQuaternion.z,
  46019. s: impostor.object.rotationQuaternion.w
  46020. });
  46021. var extendSize = i.getObjectExtendSize();
  46022. if (i === impostor) {
  46023. var center = impostor.getObjectCenter();
  46024. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  46025. //Can also use Array.prototype.push.apply
  46026. bodyConfig.pos.push(center.x);
  46027. bodyConfig.pos.push(center.y);
  46028. bodyConfig.pos.push(center.z);
  46029. //tmp solution
  46030. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  46031. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  46032. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  46033. }
  46034. else {
  46035. bodyConfig.pos.push(i.object.position.x);
  46036. bodyConfig.pos.push(i.object.position.y);
  46037. bodyConfig.pos.push(i.object.position.z);
  46038. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  46039. bodyConfig.rot.push(0);
  46040. bodyConfig.rot.push(0);
  46041. bodyConfig.rot.push(0);
  46042. }
  46043. // register mesh
  46044. switch (i.type) {
  46045. case BABYLON.PhysicsImpostor.ParticleImpostor:
  46046. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  46047. case BABYLON.PhysicsImpostor.SphereImpostor:
  46048. var radiusX = extendSize.x;
  46049. var radiusY = extendSize.y;
  46050. var radiusZ = extendSize.z;
  46051. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  46052. bodyConfig.type.push('sphere');
  46053. //due to the way oimo works with compounds, add 3 times
  46054. bodyConfig.size.push(size);
  46055. bodyConfig.size.push(size);
  46056. bodyConfig.size.push(size);
  46057. break;
  46058. case BABYLON.PhysicsImpostor.CylinderImpostor:
  46059. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  46060. var sizeY = checkWithEpsilon_1(extendSize.y);
  46061. bodyConfig.type.push('cylinder');
  46062. bodyConfig.size.push(sizeX);
  46063. bodyConfig.size.push(sizeY);
  46064. //due to the way oimo works with compounds, add one more value.
  46065. bodyConfig.size.push(sizeY);
  46066. break;
  46067. case BABYLON.PhysicsImpostor.PlaneImpostor:
  46068. case BABYLON.PhysicsImpostor.BoxImpostor:
  46069. default:
  46070. var sizeX = checkWithEpsilon_1(extendSize.x);
  46071. var sizeY = checkWithEpsilon_1(extendSize.y);
  46072. var sizeZ = checkWithEpsilon_1(extendSize.z);
  46073. bodyConfig.type.push('box');
  46074. bodyConfig.size.push(sizeX);
  46075. bodyConfig.size.push(sizeY);
  46076. bodyConfig.size.push(sizeZ);
  46077. break;
  46078. }
  46079. //actually not needed, but hey...
  46080. i.object.rotationQuaternion = oldQuaternion;
  46081. });
  46082. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  46083. }
  46084. else {
  46085. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  46086. }
  46087. impostor.setDeltaPosition(this._tmpPositionVector);
  46088. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  46089. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  46090. };
  46091. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  46092. //impostor.physicsBody.dispose();
  46093. //Same as : (older oimo versions)
  46094. this.world.removeRigidBody(impostor.physicsBody);
  46095. };
  46096. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  46097. var mainBody = impostorJoint.mainImpostor.physicsBody;
  46098. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  46099. if (!mainBody || !connectedBody) {
  46100. return;
  46101. }
  46102. var jointData = impostorJoint.joint.jointData;
  46103. var options = jointData.nativeParams || {};
  46104. var type;
  46105. var nativeJointData = {
  46106. body1: mainBody,
  46107. body2: connectedBody,
  46108. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  46109. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  46110. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  46111. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  46112. min: options.min,
  46113. max: options.max,
  46114. collision: options.collision || jointData.collision,
  46115. spring: options.spring,
  46116. //supporting older version of Oimo
  46117. world: this.world
  46118. };
  46119. switch (impostorJoint.joint.type) {
  46120. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  46121. type = "jointBall";
  46122. break;
  46123. case BABYLON.PhysicsJoint.SpringJoint:
  46124. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  46125. var springData = jointData;
  46126. nativeJointData.min = springData.length || nativeJointData.min;
  46127. //Max should also be set, just make sure it is at least min
  46128. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  46129. case BABYLON.PhysicsJoint.DistanceJoint:
  46130. type = "jointDistance";
  46131. nativeJointData.max = jointData.maxDistance;
  46132. break;
  46133. case BABYLON.PhysicsJoint.PrismaticJoint:
  46134. type = "jointPrisme";
  46135. break;
  46136. case BABYLON.PhysicsJoint.SliderJoint:
  46137. type = "jointSlide";
  46138. break;
  46139. case BABYLON.PhysicsJoint.WheelJoint:
  46140. type = "jointWheel";
  46141. break;
  46142. case BABYLON.PhysicsJoint.HingeJoint:
  46143. default:
  46144. type = "jointHinge";
  46145. break;
  46146. }
  46147. nativeJointData.type = type;
  46148. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  46149. };
  46150. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  46151. //Bug in Oimo prevents us from disposing a joint in the playground
  46152. //joint.joint.physicsJoint.dispose();
  46153. //So we will bruteforce it!
  46154. try {
  46155. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  46156. }
  46157. catch (e) {
  46158. BABYLON.Tools.Warn(e);
  46159. }
  46160. };
  46161. OimoJSPlugin.prototype.isSupported = function () {
  46162. return OIMO !== undefined;
  46163. };
  46164. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  46165. if (!impostor.physicsBody.sleeping) {
  46166. //TODO check that
  46167. if (impostor.physicsBody.shapes.next) {
  46168. var parentShape = this._getLastShape(impostor.physicsBody);
  46169. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  46170. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  46171. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  46172. }
  46173. else {
  46174. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  46175. }
  46176. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  46177. impostor.object.rotationQuaternion.normalize();
  46178. }
  46179. };
  46180. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  46181. var body = impostor.physicsBody;
  46182. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  46183. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  46184. body.syncShapes();
  46185. body.awake();
  46186. };
  46187. OimoJSPlugin.prototype._getLastShape = function (body) {
  46188. var lastShape = body.shapes;
  46189. while (lastShape.next) {
  46190. lastShape = lastShape.next;
  46191. }
  46192. return lastShape;
  46193. };
  46194. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  46195. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  46196. };
  46197. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  46198. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  46199. };
  46200. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  46201. var v = impostor.physicsBody.linearVelocity;
  46202. if (!v)
  46203. return null;
  46204. return new BABYLON.Vector3(v.x, v.y, v.z);
  46205. };
  46206. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  46207. var v = impostor.physicsBody.angularVelocity;
  46208. if (!v)
  46209. return null;
  46210. return new BABYLON.Vector3(v.x, v.y, v.z);
  46211. };
  46212. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  46213. var staticBody = mass === 0;
  46214. //this will actually set the body's density and not its mass.
  46215. //But this is how oimo treats the mass variable.
  46216. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  46217. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  46218. };
  46219. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  46220. impostor.physicsBody.sleep();
  46221. };
  46222. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  46223. impostor.physicsBody.awake();
  46224. };
  46225. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  46226. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  46227. if (minDistance !== void 0) {
  46228. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  46229. }
  46230. };
  46231. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  46232. //TODO separate rotational and transational motors.
  46233. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  46234. if (motor) {
  46235. motor.setMotor(speed, maxForce);
  46236. }
  46237. };
  46238. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  46239. //TODO separate rotational and transational motors.
  46240. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  46241. if (motor) {
  46242. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  46243. }
  46244. };
  46245. OimoJSPlugin.prototype.dispose = function () {
  46246. this.world.clear();
  46247. };
  46248. return OimoJSPlugin;
  46249. }());
  46250. BABYLON.OimoJSPlugin = OimoJSPlugin;
  46251. })(BABYLON || (BABYLON = {}));
  46252. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  46253. var BABYLON;
  46254. (function (BABYLON) {
  46255. var DisplayPassPostProcess = (function (_super) {
  46256. __extends(DisplayPassPostProcess, _super);
  46257. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46258. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  46259. }
  46260. return DisplayPassPostProcess;
  46261. }(BABYLON.PostProcess));
  46262. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  46263. })(BABYLON || (BABYLON = {}));
  46264. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  46265. var BABYLON;
  46266. (function (BABYLON) {
  46267. var SimplificationSettings = (function () {
  46268. function SimplificationSettings(quality, distance, optimizeMesh) {
  46269. this.quality = quality;
  46270. this.distance = distance;
  46271. this.optimizeMesh = optimizeMesh;
  46272. }
  46273. return SimplificationSettings;
  46274. }());
  46275. BABYLON.SimplificationSettings = SimplificationSettings;
  46276. var SimplificationQueue = (function () {
  46277. function SimplificationQueue() {
  46278. this.running = false;
  46279. this._simplificationArray = [];
  46280. }
  46281. SimplificationQueue.prototype.addTask = function (task) {
  46282. this._simplificationArray.push(task);
  46283. };
  46284. SimplificationQueue.prototype.executeNext = function () {
  46285. var task = this._simplificationArray.pop();
  46286. if (task) {
  46287. this.running = true;
  46288. this.runSimplification(task);
  46289. }
  46290. else {
  46291. this.running = false;
  46292. }
  46293. };
  46294. SimplificationQueue.prototype.runSimplification = function (task) {
  46295. var _this = this;
  46296. if (task.parallelProcessing) {
  46297. //parallel simplifier
  46298. task.settings.forEach(function (setting) {
  46299. var simplifier = _this.getSimplifier(task);
  46300. simplifier.simplify(setting, function (newMesh) {
  46301. task.mesh.addLODLevel(setting.distance, newMesh);
  46302. newMesh.isVisible = true;
  46303. //check if it is the last
  46304. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  46305. //all done, run the success callback.
  46306. task.successCallback();
  46307. }
  46308. _this.executeNext();
  46309. });
  46310. });
  46311. }
  46312. else {
  46313. //single simplifier.
  46314. var simplifier = this.getSimplifier(task);
  46315. var runDecimation = function (setting, callback) {
  46316. simplifier.simplify(setting, function (newMesh) {
  46317. task.mesh.addLODLevel(setting.distance, newMesh);
  46318. newMesh.isVisible = true;
  46319. //run the next quality level
  46320. callback();
  46321. });
  46322. };
  46323. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  46324. runDecimation(task.settings[loop.index], function () {
  46325. loop.executeNext();
  46326. });
  46327. }, function () {
  46328. //execution ended, run the success callback.
  46329. if (task.successCallback) {
  46330. task.successCallback();
  46331. }
  46332. _this.executeNext();
  46333. });
  46334. }
  46335. };
  46336. SimplificationQueue.prototype.getSimplifier = function (task) {
  46337. switch (task.simplificationType) {
  46338. case SimplificationType.QUADRATIC:
  46339. default:
  46340. return new QuadraticErrorSimplification(task.mesh);
  46341. }
  46342. };
  46343. return SimplificationQueue;
  46344. }());
  46345. BABYLON.SimplificationQueue = SimplificationQueue;
  46346. /**
  46347. * The implemented types of simplification.
  46348. * At the moment only Quadratic Error Decimation is implemented.
  46349. */
  46350. var SimplificationType;
  46351. (function (SimplificationType) {
  46352. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  46353. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  46354. var DecimationTriangle = (function () {
  46355. function DecimationTriangle(vertices) {
  46356. this.vertices = vertices;
  46357. this.error = new Array(4);
  46358. this.deleted = false;
  46359. this.isDirty = false;
  46360. this.deletePending = false;
  46361. this.borderFactor = 0;
  46362. }
  46363. return DecimationTriangle;
  46364. }());
  46365. BABYLON.DecimationTriangle = DecimationTriangle;
  46366. var DecimationVertex = (function () {
  46367. function DecimationVertex(position, id) {
  46368. this.position = position;
  46369. this.id = id;
  46370. this.isBorder = true;
  46371. this.q = new QuadraticMatrix();
  46372. this.triangleCount = 0;
  46373. this.triangleStart = 0;
  46374. this.originalOffsets = [];
  46375. }
  46376. DecimationVertex.prototype.updatePosition = function (newPosition) {
  46377. this.position.copyFrom(newPosition);
  46378. };
  46379. return DecimationVertex;
  46380. }());
  46381. BABYLON.DecimationVertex = DecimationVertex;
  46382. var QuadraticMatrix = (function () {
  46383. function QuadraticMatrix(data) {
  46384. this.data = new Array(10);
  46385. for (var i = 0; i < 10; ++i) {
  46386. if (data && data[i]) {
  46387. this.data[i] = data[i];
  46388. }
  46389. else {
  46390. this.data[i] = 0;
  46391. }
  46392. }
  46393. }
  46394. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  46395. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  46396. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  46397. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  46398. return det;
  46399. };
  46400. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  46401. for (var i = 0; i < 10; ++i) {
  46402. this.data[i] += matrix.data[i];
  46403. }
  46404. };
  46405. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  46406. for (var i = 0; i < 10; ++i) {
  46407. this.data[i] += data[i];
  46408. }
  46409. };
  46410. QuadraticMatrix.prototype.add = function (matrix) {
  46411. var m = new QuadraticMatrix();
  46412. for (var i = 0; i < 10; ++i) {
  46413. m.data[i] = this.data[i] + matrix.data[i];
  46414. }
  46415. return m;
  46416. };
  46417. QuadraticMatrix.FromData = function (a, b, c, d) {
  46418. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  46419. };
  46420. //returning an array to avoid garbage collection
  46421. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  46422. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  46423. };
  46424. return QuadraticMatrix;
  46425. }());
  46426. BABYLON.QuadraticMatrix = QuadraticMatrix;
  46427. var Reference = (function () {
  46428. function Reference(vertexId, triangleId) {
  46429. this.vertexId = vertexId;
  46430. this.triangleId = triangleId;
  46431. }
  46432. return Reference;
  46433. }());
  46434. BABYLON.Reference = Reference;
  46435. /**
  46436. * An implementation of the Quadratic Error simplification algorithm.
  46437. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  46438. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  46439. * @author RaananW
  46440. */
  46441. var QuadraticErrorSimplification = (function () {
  46442. function QuadraticErrorSimplification(_mesh) {
  46443. this._mesh = _mesh;
  46444. this.initialized = false;
  46445. this.syncIterations = 5000;
  46446. this.aggressiveness = 7;
  46447. this.decimationIterations = 100;
  46448. this.boundingBoxEpsilon = BABYLON.Epsilon;
  46449. }
  46450. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  46451. var _this = this;
  46452. this.initDecimatedMesh();
  46453. //iterating through the submeshes array, one after the other.
  46454. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  46455. _this.initWithMesh(loop.index, function () {
  46456. _this.runDecimation(settings, loop.index, function () {
  46457. loop.executeNext();
  46458. });
  46459. }, settings.optimizeMesh);
  46460. }, function () {
  46461. setTimeout(function () {
  46462. successCallback(_this._reconstructedMesh);
  46463. }, 0);
  46464. });
  46465. };
  46466. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  46467. var _this = this;
  46468. var gCount = 0;
  46469. triangle.vertices.forEach(function (vertex) {
  46470. var count = 0;
  46471. var vPos = vertex.position;
  46472. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  46473. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  46474. ++count;
  46475. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  46476. ++count;
  46477. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  46478. ++count;
  46479. if (count > 1) {
  46480. ++gCount;
  46481. }
  46482. ;
  46483. });
  46484. if (gCount > 1) {
  46485. console.log(triangle, gCount);
  46486. }
  46487. return gCount > 1;
  46488. };
  46489. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  46490. var _this = this;
  46491. var targetCount = ~~(this.triangles.length * settings.quality);
  46492. var deletedTriangles = 0;
  46493. var triangleCount = this.triangles.length;
  46494. var iterationFunction = function (iteration, callback) {
  46495. setTimeout(function () {
  46496. if (iteration % 5 === 0) {
  46497. _this.updateMesh(iteration === 0);
  46498. }
  46499. for (var i = 0; i < _this.triangles.length; ++i) {
  46500. _this.triangles[i].isDirty = false;
  46501. }
  46502. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  46503. var trianglesIterator = function (i) {
  46504. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  46505. var t = _this.triangles[tIdx];
  46506. if (!t)
  46507. return;
  46508. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  46509. return;
  46510. }
  46511. for (var j = 0; j < 3; ++j) {
  46512. if (t.error[j] < threshold) {
  46513. var deleted0 = [];
  46514. var deleted1 = [];
  46515. var v0 = t.vertices[j];
  46516. var v1 = t.vertices[(j + 1) % 3];
  46517. if (v0.isBorder || v1.isBorder)
  46518. continue;
  46519. var p = BABYLON.Vector3.Zero();
  46520. var n = BABYLON.Vector3.Zero();
  46521. var uv = BABYLON.Vector2.Zero();
  46522. var color = new BABYLON.Color4(0, 0, 0, 1);
  46523. _this.calculateError(v0, v1, p, n, uv, color);
  46524. var delTr = [];
  46525. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  46526. continue;
  46527. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  46528. continue;
  46529. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  46530. continue;
  46531. var uniqueArray = [];
  46532. delTr.forEach(function (deletedT) {
  46533. if (uniqueArray.indexOf(deletedT) === -1) {
  46534. deletedT.deletePending = true;
  46535. uniqueArray.push(deletedT);
  46536. }
  46537. });
  46538. if (uniqueArray.length % 2 !== 0) {
  46539. continue;
  46540. }
  46541. v0.q = v1.q.add(v0.q);
  46542. v0.updatePosition(p);
  46543. var tStart = _this.references.length;
  46544. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  46545. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  46546. var tCount = _this.references.length - tStart;
  46547. if (tCount <= v0.triangleCount) {
  46548. if (tCount) {
  46549. for (var c = 0; c < tCount; c++) {
  46550. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  46551. }
  46552. }
  46553. }
  46554. else {
  46555. v0.triangleStart = tStart;
  46556. }
  46557. v0.triangleCount = tCount;
  46558. break;
  46559. }
  46560. }
  46561. };
  46562. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  46563. }, 0);
  46564. };
  46565. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  46566. if (triangleCount - deletedTriangles <= targetCount)
  46567. loop.breakLoop();
  46568. else {
  46569. iterationFunction(loop.index, function () {
  46570. loop.executeNext();
  46571. });
  46572. }
  46573. }, function () {
  46574. setTimeout(function () {
  46575. //reconstruct this part of the mesh
  46576. _this.reconstructMesh(submeshIndex);
  46577. successCallback();
  46578. }, 0);
  46579. });
  46580. };
  46581. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  46582. var _this = this;
  46583. this.vertices = [];
  46584. this.triangles = [];
  46585. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46586. var indices = this._mesh.getIndices();
  46587. var submesh = this._mesh.subMeshes[submeshIndex];
  46588. var findInVertices = function (positionToSearch) {
  46589. if (optimizeMesh) {
  46590. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  46591. if (_this.vertices[ii].position.equals(positionToSearch)) {
  46592. return _this.vertices[ii];
  46593. }
  46594. }
  46595. }
  46596. return null;
  46597. };
  46598. var vertexReferences = [];
  46599. var vertexInit = function (i) {
  46600. var offset = i + submesh.verticesStart;
  46601. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  46602. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  46603. vertex.originalOffsets.push(offset);
  46604. if (vertex.id === _this.vertices.length) {
  46605. _this.vertices.push(vertex);
  46606. }
  46607. vertexReferences.push(vertex.id);
  46608. };
  46609. //var totalVertices = mesh.getTotalVertices();
  46610. var totalVertices = submesh.verticesCount;
  46611. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  46612. var indicesInit = function (i) {
  46613. var offset = (submesh.indexStart / 3) + i;
  46614. var pos = (offset * 3);
  46615. var i0 = indices[pos + 0];
  46616. var i1 = indices[pos + 1];
  46617. var i2 = indices[pos + 2];
  46618. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  46619. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  46620. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  46621. var triangle = new DecimationTriangle([v0, v1, v2]);
  46622. triangle.originalOffset = pos;
  46623. _this.triangles.push(triangle);
  46624. };
  46625. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  46626. _this.init(callback);
  46627. });
  46628. });
  46629. };
  46630. QuadraticErrorSimplification.prototype.init = function (callback) {
  46631. var _this = this;
  46632. var triangleInit1 = function (i) {
  46633. var t = _this.triangles[i];
  46634. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  46635. for (var j = 0; j < 3; j++) {
  46636. 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))));
  46637. }
  46638. };
  46639. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  46640. var triangleInit2 = function (i) {
  46641. var t = _this.triangles[i];
  46642. for (var j = 0; j < 3; ++j) {
  46643. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  46644. }
  46645. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  46646. };
  46647. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  46648. _this.initialized = true;
  46649. callback();
  46650. });
  46651. });
  46652. };
  46653. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  46654. var newTriangles = [];
  46655. var i;
  46656. for (i = 0; i < this.vertices.length; ++i) {
  46657. this.vertices[i].triangleCount = 0;
  46658. }
  46659. var t;
  46660. var j;
  46661. for (i = 0; i < this.triangles.length; ++i) {
  46662. if (!this.triangles[i].deleted) {
  46663. t = this.triangles[i];
  46664. for (j = 0; j < 3; ++j) {
  46665. t.vertices[j].triangleCount = 1;
  46666. }
  46667. newTriangles.push(t);
  46668. }
  46669. }
  46670. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  46671. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  46672. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  46673. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  46674. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46675. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46676. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46677. var vertexCount = 0;
  46678. for (i = 0; i < this.vertices.length; ++i) {
  46679. var vertex = this.vertices[i];
  46680. vertex.id = vertexCount;
  46681. if (vertex.triangleCount) {
  46682. vertex.originalOffsets.forEach(function (originalOffset) {
  46683. newPositionData.push(vertex.position.x);
  46684. newPositionData.push(vertex.position.y);
  46685. newPositionData.push(vertex.position.z);
  46686. newNormalData.push(normalData[originalOffset * 3]);
  46687. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  46688. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  46689. if (uvs && uvs.length) {
  46690. newUVsData.push(uvs[(originalOffset * 2)]);
  46691. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  46692. }
  46693. else if (colorsData && colorsData.length) {
  46694. newColorsData.push(colorsData[(originalOffset * 4)]);
  46695. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  46696. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  46697. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  46698. }
  46699. ++vertexCount;
  46700. });
  46701. }
  46702. }
  46703. var startingIndex = this._reconstructedMesh.getTotalIndices();
  46704. var startingVertex = this._reconstructedMesh.getTotalVertices();
  46705. var submeshesArray = this._reconstructedMesh.subMeshes;
  46706. this._reconstructedMesh.subMeshes = [];
  46707. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  46708. var originalIndices = this._mesh.getIndices();
  46709. for (i = 0; i < newTriangles.length; ++i) {
  46710. t = newTriangles[i]; //now get the new referencing point for each vertex
  46711. [0, 1, 2].forEach(function (idx) {
  46712. var id = originalIndices[t.originalOffset + idx];
  46713. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  46714. if (offset < 0)
  46715. offset = 0;
  46716. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  46717. });
  46718. }
  46719. //overwriting the old vertex buffers and indices.
  46720. this._reconstructedMesh.setIndices(newIndicesArray);
  46721. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  46722. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  46723. if (newUVsData.length > 0)
  46724. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  46725. if (newColorsData.length > 0)
  46726. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  46727. //create submesh
  46728. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  46729. if (submeshIndex > 0) {
  46730. this._reconstructedMesh.subMeshes = [];
  46731. submeshesArray.forEach(function (submesh) {
  46732. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  46733. });
  46734. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  46735. }
  46736. };
  46737. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  46738. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  46739. this._reconstructedMesh.material = this._mesh.material;
  46740. this._reconstructedMesh.parent = this._mesh.parent;
  46741. this._reconstructedMesh.isVisible = false;
  46742. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  46743. };
  46744. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  46745. for (var i = 0; i < vertex1.triangleCount; ++i) {
  46746. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  46747. if (t.deleted)
  46748. continue;
  46749. var s = this.references[vertex1.triangleStart + i].vertexId;
  46750. var v1 = t.vertices[(s + 1) % 3];
  46751. var v2 = t.vertices[(s + 2) % 3];
  46752. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  46753. deletedArray[i] = true;
  46754. delTr.push(t);
  46755. continue;
  46756. }
  46757. var d1 = v1.position.subtract(point);
  46758. d1 = d1.normalize();
  46759. var d2 = v2.position.subtract(point);
  46760. d2 = d2.normalize();
  46761. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  46762. return true;
  46763. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  46764. deletedArray[i] = false;
  46765. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  46766. return true;
  46767. }
  46768. return false;
  46769. };
  46770. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  46771. var newDeleted = deletedTriangles;
  46772. for (var i = 0; i < vertex.triangleCount; ++i) {
  46773. var ref = this.references[vertex.triangleStart + i];
  46774. var t = this.triangles[ref.triangleId];
  46775. if (t.deleted)
  46776. continue;
  46777. if (deletedArray[i] && t.deletePending) {
  46778. t.deleted = true;
  46779. newDeleted++;
  46780. continue;
  46781. }
  46782. t.vertices[ref.vertexId] = origVertex;
  46783. t.isDirty = true;
  46784. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  46785. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  46786. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  46787. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  46788. this.references.push(ref);
  46789. }
  46790. return newDeleted;
  46791. };
  46792. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  46793. for (var i = 0; i < this.vertices.length; ++i) {
  46794. var vCount = [];
  46795. var vId = [];
  46796. var v = this.vertices[i];
  46797. var j;
  46798. for (j = 0; j < v.triangleCount; ++j) {
  46799. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  46800. for (var ii = 0; ii < 3; ii++) {
  46801. var ofs = 0;
  46802. var vv = triangle.vertices[ii];
  46803. while (ofs < vCount.length) {
  46804. if (vId[ofs] === vv.id)
  46805. break;
  46806. ++ofs;
  46807. }
  46808. if (ofs === vCount.length) {
  46809. vCount.push(1);
  46810. vId.push(vv.id);
  46811. }
  46812. else {
  46813. vCount[ofs]++;
  46814. }
  46815. }
  46816. }
  46817. for (j = 0; j < vCount.length; ++j) {
  46818. if (vCount[j] === 1) {
  46819. this.vertices[vId[j]].isBorder = true;
  46820. }
  46821. else {
  46822. this.vertices[vId[j]].isBorder = false;
  46823. }
  46824. }
  46825. }
  46826. };
  46827. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  46828. if (identifyBorders === void 0) { identifyBorders = false; }
  46829. var i;
  46830. if (!identifyBorders) {
  46831. var newTrianglesVector = [];
  46832. for (i = 0; i < this.triangles.length; ++i) {
  46833. if (!this.triangles[i].deleted) {
  46834. newTrianglesVector.push(this.triangles[i]);
  46835. }
  46836. }
  46837. this.triangles = newTrianglesVector;
  46838. }
  46839. for (i = 0; i < this.vertices.length; ++i) {
  46840. this.vertices[i].triangleCount = 0;
  46841. this.vertices[i].triangleStart = 0;
  46842. }
  46843. var t;
  46844. var j;
  46845. var v;
  46846. for (i = 0; i < this.triangles.length; ++i) {
  46847. t = this.triangles[i];
  46848. for (j = 0; j < 3; ++j) {
  46849. v = t.vertices[j];
  46850. v.triangleCount++;
  46851. }
  46852. }
  46853. var tStart = 0;
  46854. for (i = 0; i < this.vertices.length; ++i) {
  46855. this.vertices[i].triangleStart = tStart;
  46856. tStart += this.vertices[i].triangleCount;
  46857. this.vertices[i].triangleCount = 0;
  46858. }
  46859. var newReferences = new Array(this.triangles.length * 3);
  46860. for (i = 0; i < this.triangles.length; ++i) {
  46861. t = this.triangles[i];
  46862. for (j = 0; j < 3; ++j) {
  46863. v = t.vertices[j];
  46864. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  46865. v.triangleCount++;
  46866. }
  46867. }
  46868. this.references = newReferences;
  46869. if (identifyBorders) {
  46870. this.identifyBorder();
  46871. }
  46872. };
  46873. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  46874. var x = point.x;
  46875. var y = point.y;
  46876. var z = point.z;
  46877. 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
  46878. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  46879. };
  46880. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  46881. var q = vertex1.q.add(vertex2.q);
  46882. var border = vertex1.isBorder && vertex2.isBorder;
  46883. var error = 0;
  46884. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  46885. if (qDet !== 0 && !border) {
  46886. if (!pointResult) {
  46887. pointResult = BABYLON.Vector3.Zero();
  46888. }
  46889. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  46890. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  46891. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  46892. error = this.vertexError(q, pointResult);
  46893. }
  46894. else {
  46895. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  46896. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  46897. var error1 = this.vertexError(q, vertex1.position);
  46898. var error2 = this.vertexError(q, vertex2.position);
  46899. var error3 = this.vertexError(q, p3);
  46900. error = Math.min(error1, error2, error3);
  46901. if (error === error1) {
  46902. if (pointResult) {
  46903. pointResult.copyFrom(vertex1.position);
  46904. }
  46905. }
  46906. else if (error === error2) {
  46907. if (pointResult) {
  46908. pointResult.copyFrom(vertex2.position);
  46909. }
  46910. }
  46911. else {
  46912. if (pointResult) {
  46913. pointResult.copyFrom(p3);
  46914. }
  46915. }
  46916. }
  46917. return error;
  46918. };
  46919. return QuadraticErrorSimplification;
  46920. }());
  46921. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  46922. })(BABYLON || (BABYLON = {}));
  46923. //# sourceMappingURL=babylon.meshSimplification.js.map
  46924. var BABYLON;
  46925. (function (BABYLON) {
  46926. var serializedGeometries = [];
  46927. var serializeGeometry = function (geometry, serializationGeometries) {
  46928. if (serializedGeometries[geometry.id]) {
  46929. return;
  46930. }
  46931. if (geometry.doNotSerialize) {
  46932. return;
  46933. }
  46934. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  46935. serializationGeometries.boxes.push(geometry.serialize());
  46936. }
  46937. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  46938. serializationGeometries.spheres.push(geometry.serialize());
  46939. }
  46940. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  46941. serializationGeometries.cylinders.push(geometry.serialize());
  46942. }
  46943. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  46944. serializationGeometries.toruses.push(geometry.serialize());
  46945. }
  46946. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  46947. serializationGeometries.grounds.push(geometry.serialize());
  46948. }
  46949. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  46950. serializationGeometries.planes.push(geometry.serialize());
  46951. }
  46952. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  46953. serializationGeometries.torusKnots.push(geometry.serialize());
  46954. }
  46955. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  46956. throw new Error("Unknown primitive type");
  46957. }
  46958. else {
  46959. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  46960. }
  46961. serializedGeometries[geometry.id] = true;
  46962. };
  46963. var serializeMesh = function (mesh, serializationScene) {
  46964. var serializationObject = {};
  46965. // Geometry
  46966. var geometry = mesh._geometry;
  46967. if (geometry) {
  46968. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  46969. // 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
  46970. serializeGeometry(geometry, serializationScene.geometries);
  46971. }
  46972. }
  46973. // Custom
  46974. if (mesh.serialize) {
  46975. mesh.serialize(serializationObject);
  46976. }
  46977. return serializationObject;
  46978. };
  46979. var finalizeSingleMesh = function (mesh, serializationObject) {
  46980. //only works if the mesh is already loaded
  46981. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  46982. //serialize material
  46983. if (mesh.material) {
  46984. if (mesh.material instanceof BABYLON.StandardMaterial) {
  46985. serializationObject.materials = serializationObject.materials || [];
  46986. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  46987. serializationObject.materials.push(mesh.material.serialize());
  46988. }
  46989. }
  46990. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  46991. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  46992. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  46993. serializationObject.multiMaterials.push(mesh.material.serialize());
  46994. }
  46995. }
  46996. }
  46997. //serialize geometry
  46998. var geometry = mesh._geometry;
  46999. if (geometry) {
  47000. if (!serializationObject.geometries) {
  47001. serializationObject.geometries = {};
  47002. serializationObject.geometries.boxes = [];
  47003. serializationObject.geometries.spheres = [];
  47004. serializationObject.geometries.cylinders = [];
  47005. serializationObject.geometries.toruses = [];
  47006. serializationObject.geometries.grounds = [];
  47007. serializationObject.geometries.planes = [];
  47008. serializationObject.geometries.torusKnots = [];
  47009. serializationObject.geometries.vertexData = [];
  47010. }
  47011. serializeGeometry(geometry, serializationObject.geometries);
  47012. }
  47013. // Skeletons
  47014. if (mesh.skeleton) {
  47015. serializationObject.skeletons = serializationObject.skeletons || [];
  47016. serializationObject.skeletons.push(mesh.skeleton.serialize());
  47017. }
  47018. //serialize the actual mesh
  47019. serializationObject.meshes = serializationObject.meshes || [];
  47020. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  47021. }
  47022. };
  47023. var SceneSerializer = (function () {
  47024. function SceneSerializer() {
  47025. }
  47026. SceneSerializer.ClearCache = function () {
  47027. serializedGeometries = [];
  47028. };
  47029. SceneSerializer.Serialize = function (scene) {
  47030. var serializationObject = {};
  47031. SceneSerializer.ClearCache();
  47032. // Scene
  47033. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  47034. serializationObject.autoClear = scene.autoClear;
  47035. serializationObject.clearColor = scene.clearColor.asArray();
  47036. serializationObject.ambientColor = scene.ambientColor.asArray();
  47037. serializationObject.gravity = scene.gravity.asArray();
  47038. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  47039. serializationObject.workerCollisions = scene.workerCollisions;
  47040. // Fog
  47041. if (scene.fogMode && scene.fogMode !== 0) {
  47042. serializationObject.fogMode = scene.fogMode;
  47043. serializationObject.fogColor = scene.fogColor.asArray();
  47044. serializationObject.fogStart = scene.fogStart;
  47045. serializationObject.fogEnd = scene.fogEnd;
  47046. serializationObject.fogDensity = scene.fogDensity;
  47047. }
  47048. //Physics
  47049. if (scene.isPhysicsEnabled()) {
  47050. serializationObject.physicsEnabled = true;
  47051. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  47052. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  47053. }
  47054. // Metadata
  47055. if (scene.metadata) {
  47056. serializationObject.metadata = scene.metadata;
  47057. }
  47058. // Lights
  47059. serializationObject.lights = [];
  47060. var index;
  47061. var light;
  47062. for (index = 0; index < scene.lights.length; index++) {
  47063. light = scene.lights[index];
  47064. if (!light.doNotSerialize) {
  47065. serializationObject.lights.push(light.serialize());
  47066. }
  47067. }
  47068. // Cameras
  47069. serializationObject.cameras = [];
  47070. for (index = 0; index < scene.cameras.length; index++) {
  47071. var camera = scene.cameras[index];
  47072. if (!camera.doNotSerialize) {
  47073. serializationObject.cameras.push(camera.serialize());
  47074. }
  47075. }
  47076. if (scene.activeCamera) {
  47077. serializationObject.activeCameraID = scene.activeCamera.id;
  47078. }
  47079. // Animations
  47080. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  47081. // Materials
  47082. serializationObject.materials = [];
  47083. serializationObject.multiMaterials = [];
  47084. var material;
  47085. for (index = 0; index < scene.materials.length; index++) {
  47086. material = scene.materials[index];
  47087. if (!material.doNotSerialize) {
  47088. serializationObject.materials.push(material.serialize());
  47089. }
  47090. }
  47091. // MultiMaterials
  47092. serializationObject.multiMaterials = [];
  47093. for (index = 0; index < scene.multiMaterials.length; index++) {
  47094. var multiMaterial = scene.multiMaterials[index];
  47095. serializationObject.multiMaterials.push(multiMaterial.serialize());
  47096. }
  47097. // Skeletons
  47098. serializationObject.skeletons = [];
  47099. for (index = 0; index < scene.skeletons.length; index++) {
  47100. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  47101. }
  47102. // Geometries
  47103. serializationObject.geometries = {};
  47104. serializationObject.geometries.boxes = [];
  47105. serializationObject.geometries.spheres = [];
  47106. serializationObject.geometries.cylinders = [];
  47107. serializationObject.geometries.toruses = [];
  47108. serializationObject.geometries.grounds = [];
  47109. serializationObject.geometries.planes = [];
  47110. serializationObject.geometries.torusKnots = [];
  47111. serializationObject.geometries.vertexData = [];
  47112. serializedGeometries = [];
  47113. var geometries = scene.getGeometries();
  47114. for (index = 0; index < geometries.length; index++) {
  47115. var geometry = geometries[index];
  47116. if (geometry.isReady()) {
  47117. serializeGeometry(geometry, serializationObject.geometries);
  47118. }
  47119. }
  47120. // Meshes
  47121. serializationObject.meshes = [];
  47122. for (index = 0; index < scene.meshes.length; index++) {
  47123. var abstractMesh = scene.meshes[index];
  47124. if (abstractMesh instanceof BABYLON.Mesh) {
  47125. var mesh = abstractMesh;
  47126. if (!mesh.doNotSerialize) {
  47127. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  47128. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  47129. }
  47130. }
  47131. }
  47132. }
  47133. // Particles Systems
  47134. serializationObject.particleSystems = [];
  47135. for (index = 0; index < scene.particleSystems.length; index++) {
  47136. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  47137. }
  47138. // Lens flares
  47139. serializationObject.lensFlareSystems = [];
  47140. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  47141. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  47142. }
  47143. // Shadows
  47144. serializationObject.shadowGenerators = [];
  47145. for (index = 0; index < scene.lights.length; index++) {
  47146. light = scene.lights[index];
  47147. var shadowGenerator = light.getShadowGenerator();
  47148. // Only support serialization for official generator so far.
  47149. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  47150. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  47151. }
  47152. }
  47153. // Action Manager
  47154. if (scene.actionManager) {
  47155. serializationObject.actions = scene.actionManager.serialize("scene");
  47156. }
  47157. // Audio
  47158. serializationObject.sounds = [];
  47159. for (index = 0; index < scene.soundTracks.length; index++) {
  47160. var soundtrack = scene.soundTracks[index];
  47161. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  47162. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  47163. }
  47164. }
  47165. return serializationObject;
  47166. };
  47167. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  47168. if (withParents === void 0) { withParents = false; }
  47169. if (withChildren === void 0) { withChildren = false; }
  47170. var serializationObject = {};
  47171. SceneSerializer.ClearCache();
  47172. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  47173. if (withParents || withChildren) {
  47174. //deliberate for loop! not for each, appended should be processed as well.
  47175. for (var i = 0; i < toSerialize.length; ++i) {
  47176. if (withChildren) {
  47177. toSerialize[i].getDescendants().forEach(function (node) {
  47178. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  47179. toSerialize.push(node);
  47180. }
  47181. });
  47182. }
  47183. //make sure the array doesn't contain the object already
  47184. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  47185. toSerialize.push(toSerialize[i].parent);
  47186. }
  47187. }
  47188. }
  47189. toSerialize.forEach(function (mesh) {
  47190. finalizeSingleMesh(mesh, serializationObject);
  47191. });
  47192. return serializationObject;
  47193. };
  47194. return SceneSerializer;
  47195. }());
  47196. BABYLON.SceneSerializer = SceneSerializer;
  47197. })(BABYLON || (BABYLON = {}));
  47198. //# sourceMappingURL=babylon.sceneSerializer.js.map
  47199. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  47200. // Huge respect for a such great lib.
  47201. // Earcut license:
  47202. // Copyright (c) 2016, Mapbox
  47203. //
  47204. // Permission to use, copy, modify, and/or distribute this software for any purpose
  47205. // with or without fee is hereby granted, provided that the above copyright notice
  47206. // and this permission notice appear in all copies.
  47207. //
  47208. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  47209. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  47210. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  47211. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  47212. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  47213. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  47214. // THIS SOFTWARE.
  47215. var Earcut;
  47216. (function (Earcut) {
  47217. /**
  47218. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  47219. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  47220. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  47221. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  47222. */
  47223. function earcut(data, holeIndices, dim) {
  47224. dim = dim || 2;
  47225. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  47226. if (!outerNode)
  47227. return triangles;
  47228. var minX, minY, maxX, maxY, x, y, size;
  47229. if (hasHoles)
  47230. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  47231. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  47232. if (data.length > 80 * dim) {
  47233. minX = maxX = data[0];
  47234. minY = maxY = data[1];
  47235. for (var i = dim; i < outerLen; i += dim) {
  47236. x = data[i];
  47237. y = data[i + 1];
  47238. if (x < minX)
  47239. minX = x;
  47240. if (y < minY)
  47241. minY = y;
  47242. if (x > maxX)
  47243. maxX = x;
  47244. if (y > maxY)
  47245. maxY = y;
  47246. }
  47247. // minX, minY and size are later used to transform coords into integers for z-order calculation
  47248. size = Math.max(maxX - minX, maxY - minY);
  47249. }
  47250. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  47251. return triangles;
  47252. }
  47253. Earcut.earcut = earcut;
  47254. // create a circular doubly linked list from polygon points in the specified winding order
  47255. function linkedList(data, start, end, dim, clockwise) {
  47256. var i, last;
  47257. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  47258. for (i = start; i < end; i += dim)
  47259. last = insertNode(i, data[i], data[i + 1], last);
  47260. }
  47261. else {
  47262. for (i = end - dim; i >= start; i -= dim)
  47263. last = insertNode(i, data[i], data[i + 1], last);
  47264. }
  47265. if (last && equals(last, last.next)) {
  47266. removeNode(last);
  47267. last = last.next;
  47268. }
  47269. return last;
  47270. }
  47271. // eliminate colinear or duplicate points
  47272. function filterPoints(start, end) {
  47273. if (!start)
  47274. return start;
  47275. if (!end)
  47276. end = start;
  47277. var p = start, again;
  47278. do {
  47279. again = false;
  47280. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  47281. removeNode(p);
  47282. p = end = p.prev;
  47283. if (p === p.next)
  47284. return null;
  47285. again = true;
  47286. }
  47287. else {
  47288. p = p.next;
  47289. }
  47290. } while (again || p !== end);
  47291. return end;
  47292. }
  47293. // main ear slicing loop which triangulates a polygon (given as a linked list)
  47294. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  47295. if (!ear)
  47296. return;
  47297. // interlink polygon nodes in z-order
  47298. if (!pass && size)
  47299. indexCurve(ear, minX, minY, size);
  47300. var stop = ear, prev, next;
  47301. // iterate through ears, slicing them one by one
  47302. while (ear.prev !== ear.next) {
  47303. prev = ear.prev;
  47304. next = ear.next;
  47305. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  47306. // cut off the triangle
  47307. triangles.push(prev.i / dim);
  47308. triangles.push(ear.i / dim);
  47309. triangles.push(next.i / dim);
  47310. removeNode(ear);
  47311. // skipping the next vertice leads to less sliver triangles
  47312. ear = next.next;
  47313. stop = next.next;
  47314. continue;
  47315. }
  47316. ear = next;
  47317. // if we looped through the whole remaining polygon and can't find any more ears
  47318. if (ear === stop) {
  47319. // try filtering points and slicing again
  47320. if (!pass) {
  47321. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  47322. }
  47323. else if (pass === 1) {
  47324. ear = cureLocalIntersections(ear, triangles, dim);
  47325. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  47326. }
  47327. else if (pass === 2) {
  47328. splitEarcut(ear, triangles, dim, minX, minY, size);
  47329. }
  47330. break;
  47331. }
  47332. }
  47333. }
  47334. // check whether a polygon node forms a valid ear with adjacent nodes
  47335. function isEar(ear) {
  47336. var a = ear.prev, b = ear, c = ear.next;
  47337. if (area(a, b, c) >= 0)
  47338. return false; // reflex, can't be an ear
  47339. // now make sure we don't have other points inside the potential ear
  47340. var p = ear.next.next;
  47341. while (p !== ear.prev) {
  47342. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47343. area(p.prev, p, p.next) >= 0)
  47344. return false;
  47345. p = p.next;
  47346. }
  47347. return true;
  47348. }
  47349. function isEarHashed(ear, minX, minY, size) {
  47350. var a = ear.prev, b = ear, c = ear.next;
  47351. if (area(a, b, c) >= 0)
  47352. return false; // reflex, can't be an ear
  47353. // triangle bbox; min & max are calculated like this for speed
  47354. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  47355. // z-order range for the current triangle bbox;
  47356. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  47357. // first look for points inside the triangle in increasing z-order
  47358. var p = ear.nextZ;
  47359. while (p && p.z <= maxZ) {
  47360. if (p !== ear.prev &&
  47361. p !== ear.next &&
  47362. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47363. area(p.prev, p, p.next) >= 0)
  47364. return false;
  47365. p = p.nextZ;
  47366. }
  47367. // then look for points in decreasing z-order
  47368. p = ear.prevZ;
  47369. while (p && p.z >= minZ) {
  47370. if (p !== ear.prev &&
  47371. p !== ear.next &&
  47372. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47373. area(p.prev, p, p.next) >= 0)
  47374. return false;
  47375. p = p.prevZ;
  47376. }
  47377. return true;
  47378. }
  47379. // go through all polygon nodes and cure small local self-intersections
  47380. function cureLocalIntersections(start, triangles, dim) {
  47381. var p = start;
  47382. do {
  47383. var a = p.prev, b = p.next.next;
  47384. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  47385. triangles.push(a.i / dim);
  47386. triangles.push(p.i / dim);
  47387. triangles.push(b.i / dim);
  47388. // remove two nodes involved
  47389. removeNode(p);
  47390. removeNode(p.next);
  47391. p = start = b;
  47392. }
  47393. p = p.next;
  47394. } while (p !== start);
  47395. return p;
  47396. }
  47397. // try splitting polygon into two and triangulate them independently
  47398. function splitEarcut(start, triangles, dim, minX, minY, size) {
  47399. // look for a valid diagonal that divides the polygon into two
  47400. var a = start;
  47401. do {
  47402. var b = a.next.next;
  47403. while (b !== a.prev) {
  47404. if (a.i !== b.i && isValidDiagonal(a, b)) {
  47405. // split the polygon in two by the diagonal
  47406. var c = splitPolygon(a, b);
  47407. // filter colinear points around the cuts
  47408. a = filterPoints(a, a.next);
  47409. c = filterPoints(c, c.next);
  47410. // run earcut on each half
  47411. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  47412. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  47413. return;
  47414. }
  47415. b = b.next;
  47416. }
  47417. a = a.next;
  47418. } while (a !== start);
  47419. }
  47420. // link every hole into the outer loop, producing a single-ring polygon without holes
  47421. function eliminateHoles(data, holeIndices, outerNode, dim) {
  47422. var queue = [], i, len, start, end, list;
  47423. for (i = 0, len = holeIndices.length; i < len; i++) {
  47424. start = holeIndices[i] * dim;
  47425. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  47426. list = linkedList(data, start, end, dim, false);
  47427. if (list === list.next)
  47428. list.steiner = true;
  47429. queue.push(getLeftmost(list));
  47430. }
  47431. queue.sort(compareX);
  47432. // process holes from left to right
  47433. for (i = 0; i < queue.length; i++) {
  47434. eliminateHole(queue[i], outerNode);
  47435. outerNode = filterPoints(outerNode, outerNode.next);
  47436. }
  47437. return outerNode;
  47438. }
  47439. function compareX(a, b) {
  47440. return a.x - b.x;
  47441. }
  47442. // find a bridge between vertices that connects hole with an outer ring and and link it
  47443. function eliminateHole(hole, outerNode) {
  47444. outerNode = findHoleBridge(hole, outerNode);
  47445. if (outerNode) {
  47446. var b = splitPolygon(outerNode, hole);
  47447. filterPoints(b, b.next);
  47448. }
  47449. }
  47450. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  47451. function findHoleBridge(hole, outerNode) {
  47452. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  47453. // find a segment intersected by a ray from the hole's leftmost point to the left;
  47454. // segment's endpoint with lesser x will be potential connection point
  47455. do {
  47456. if (hy <= p.y && hy >= p.next.y) {
  47457. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  47458. if (x <= hx && x > qx) {
  47459. qx = x;
  47460. if (x === hx) {
  47461. if (hy === p.y)
  47462. return p;
  47463. if (hy === p.next.y)
  47464. return p.next;
  47465. }
  47466. m = p.x < p.next.x ? p : p.next;
  47467. }
  47468. }
  47469. p = p.next;
  47470. } while (p !== outerNode);
  47471. if (!m)
  47472. return null;
  47473. if (hx === qx)
  47474. return m.prev; // hole touches outer segment; pick lower endpoint
  47475. // look for points inside the triangle of hole point, segment intersection and endpoint;
  47476. // if there are no points found, we have a valid connection;
  47477. // otherwise choose the point of the minimum angle with the ray as connection point
  47478. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  47479. p = m.next;
  47480. while (p !== stop) {
  47481. if (hx >= p.x &&
  47482. p.x >= mx &&
  47483. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  47484. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  47485. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  47486. m = p;
  47487. tanMin = tan;
  47488. }
  47489. }
  47490. p = p.next;
  47491. }
  47492. return m;
  47493. }
  47494. // interlink polygon nodes in z-order
  47495. function indexCurve(start, minX, minY, size) {
  47496. var p = start;
  47497. do {
  47498. if (p.z === null)
  47499. p.z = zOrder(p.x, p.y, minX, minY, size);
  47500. p.prevZ = p.prev;
  47501. p.nextZ = p.next;
  47502. p = p.next;
  47503. } while (p !== start);
  47504. p.prevZ.nextZ = null;
  47505. p.prevZ = null;
  47506. sortLinked(p);
  47507. }
  47508. // Simon Tatham's linked list merge sort algorithm
  47509. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  47510. function sortLinked(list) {
  47511. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  47512. do {
  47513. p = list;
  47514. list = null;
  47515. tail = null;
  47516. numMerges = 0;
  47517. while (p) {
  47518. numMerges++;
  47519. q = p;
  47520. pSize = 0;
  47521. for (i = 0; i < inSize; i++) {
  47522. pSize++;
  47523. q = q.nextZ;
  47524. if (!q)
  47525. break;
  47526. }
  47527. qSize = inSize;
  47528. while (pSize > 0 || (qSize > 0 && q)) {
  47529. if (pSize === 0) {
  47530. e = q;
  47531. q = q.nextZ;
  47532. qSize--;
  47533. }
  47534. else if (qSize === 0 || !q) {
  47535. e = p;
  47536. p = p.nextZ;
  47537. pSize--;
  47538. }
  47539. else if (p.z <= q.z) {
  47540. e = p;
  47541. p = p.nextZ;
  47542. pSize--;
  47543. }
  47544. else {
  47545. e = q;
  47546. q = q.nextZ;
  47547. qSize--;
  47548. }
  47549. if (tail)
  47550. tail.nextZ = e;
  47551. else
  47552. list = e;
  47553. e.prevZ = tail;
  47554. tail = e;
  47555. }
  47556. p = q;
  47557. }
  47558. tail.nextZ = null;
  47559. inSize *= 2;
  47560. } while (numMerges > 1);
  47561. return list;
  47562. }
  47563. // z-order of a point given coords and size of the data bounding box
  47564. function zOrder(x, y, minX, minY, size) {
  47565. // coords are transformed into non-negative 15-bit integer range
  47566. x = 32767 * (x - minX) / size;
  47567. y = 32767 * (y - minY) / size;
  47568. x = (x | (x << 8)) & 0x00FF00FF;
  47569. x = (x | (x << 4)) & 0x0F0F0F0F;
  47570. x = (x | (x << 2)) & 0x33333333;
  47571. x = (x | (x << 1)) & 0x55555555;
  47572. y = (y | (y << 8)) & 0x00FF00FF;
  47573. y = (y | (y << 4)) & 0x0F0F0F0F;
  47574. y = (y | (y << 2)) & 0x33333333;
  47575. y = (y | (y << 1)) & 0x55555555;
  47576. return x | (y << 1);
  47577. }
  47578. // find the leftmost node of a polygon ring
  47579. function getLeftmost(start) {
  47580. var p = start, leftmost = start;
  47581. do {
  47582. if (p.x < leftmost.x)
  47583. leftmost = p;
  47584. p = p.next;
  47585. } while (p !== start);
  47586. return leftmost;
  47587. }
  47588. // check if a point lies within a convex triangle
  47589. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  47590. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  47591. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  47592. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  47593. }
  47594. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  47595. function isValidDiagonal(a, b) {
  47596. return a.next.i !== b.i &&
  47597. a.prev.i !== b.i &&
  47598. !intersectsPolygon(a, b) &&
  47599. locallyInside(a, b) &&
  47600. locallyInside(b, a) &&
  47601. middleInside(a, b);
  47602. }
  47603. // signed area of a triangle
  47604. function area(p, q, r) {
  47605. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  47606. }
  47607. // check if two points are equal
  47608. function equals(p1, p2) {
  47609. return p1.x === p2.x && p1.y === p2.y;
  47610. }
  47611. // check if two segments intersect
  47612. function intersects(p1, q1, p2, q2) {
  47613. if ((equals(p1, q1) && equals(p2, q2)) ||
  47614. (equals(p1, q2) && equals(p2, q1)))
  47615. return true;
  47616. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  47617. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  47618. }
  47619. // check if a polygon diagonal intersects any polygon segments
  47620. function intersectsPolygon(a, b) {
  47621. var p = a;
  47622. do {
  47623. if (p.i !== a.i &&
  47624. p.next.i !== a.i &&
  47625. p.i !== b.i &&
  47626. p.next.i !== b.i &&
  47627. intersects(p, p.next, a, b))
  47628. return true;
  47629. p = p.next;
  47630. } while (p !== a);
  47631. return false;
  47632. }
  47633. // check if a polygon diagonal is locally inside the polygon
  47634. function locallyInside(a, b) {
  47635. return area(a.prev, a, a.next) < 0
  47636. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  47637. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  47638. }
  47639. // check if the middle point of a polygon diagonal is inside the polygon
  47640. function middleInside(a, b) {
  47641. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  47642. do {
  47643. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  47644. inside = !inside;
  47645. p = p.next;
  47646. } while (p !== a);
  47647. return inside;
  47648. }
  47649. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  47650. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  47651. function splitPolygon(a, b) {
  47652. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  47653. a.next = b;
  47654. b.prev = a;
  47655. a2.next = an;
  47656. an.prev = a2;
  47657. b2.next = a2;
  47658. a2.prev = b2;
  47659. bp.next = b2;
  47660. b2.prev = bp;
  47661. return b2;
  47662. }
  47663. // create a node and optionally link it with previous one (in a circular doubly linked list)
  47664. function insertNode(i, x, y, last) {
  47665. var p = new Node(i, x, y);
  47666. if (!last) {
  47667. p.prev = p;
  47668. p.next = p;
  47669. }
  47670. else {
  47671. p.next = last.next;
  47672. p.prev = last;
  47673. last.next.prev = p;
  47674. last.next = p;
  47675. }
  47676. return p;
  47677. }
  47678. function removeNode(p) {
  47679. p.next.prev = p.prev;
  47680. p.prev.next = p.next;
  47681. if (p.prevZ)
  47682. p.prevZ.nextZ = p.nextZ;
  47683. if (p.nextZ)
  47684. p.nextZ.prevZ = p.prevZ;
  47685. }
  47686. function Node(i, x, y) {
  47687. // vertice index in coordinates array
  47688. this.i = i;
  47689. // vertex coordinates
  47690. this.x = x;
  47691. this.y = y;
  47692. // previous and next vertice nodes in a polygon ring
  47693. this.prev = null;
  47694. this.next = null;
  47695. // z-order curve value
  47696. this.z = null;
  47697. // previous and next nodes in z-order
  47698. this.prevZ = null;
  47699. this.nextZ = null;
  47700. // indicates whether this is a steiner point
  47701. this.steiner = false;
  47702. }
  47703. /**
  47704. * return a percentage difference between the polygon area and its triangulation area;
  47705. * used to verify correctness of triangulation
  47706. */
  47707. function deviation(data, holeIndices, dim, triangles) {
  47708. var hasHoles = holeIndices && holeIndices.length;
  47709. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  47710. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  47711. if (hasHoles) {
  47712. for (var i = 0, len = holeIndices.length; i < len; i++) {
  47713. var start = holeIndices[i] * dim;
  47714. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  47715. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  47716. }
  47717. }
  47718. var trianglesArea = 0;
  47719. for (i = 0; i < triangles.length; i += 3) {
  47720. var a = triangles[i] * dim;
  47721. var b = triangles[i + 1] * dim;
  47722. var c = triangles[i + 2] * dim;
  47723. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  47724. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  47725. }
  47726. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  47727. }
  47728. Earcut.deviation = deviation;
  47729. ;
  47730. function signedArea(data, start, end, dim) {
  47731. var sum = 0;
  47732. for (var i = start, j = end - dim; i < end; i += dim) {
  47733. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  47734. j = i;
  47735. }
  47736. return sum;
  47737. }
  47738. /**
  47739. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  47740. */
  47741. function flatten(data) {
  47742. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  47743. for (var i = 0; i < data.length; i++) {
  47744. for (var j = 0; j < data[i].length; j++) {
  47745. for (var d = 0; d < dim; d++)
  47746. result.vertices.push(data[i][j][d]);
  47747. }
  47748. if (i > 0) {
  47749. holeIndex += data[i - 1].length;
  47750. result.holes.push(holeIndex);
  47751. }
  47752. }
  47753. return result;
  47754. }
  47755. Earcut.flatten = flatten;
  47756. ;
  47757. })(Earcut || (Earcut = {}));
  47758. //# sourceMappingURL=babylon.earcut.js.map
  47759. var BABYLON;
  47760. (function (BABYLON) {
  47761. // Unique ID when we import meshes from Babylon to CSG
  47762. var currentCSGMeshId = 0;
  47763. // # class Vertex
  47764. // Represents a vertex of a polygon. Use your own vertex class instead of this
  47765. // one to provide additional features like texture coordinates and vertex
  47766. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  47767. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  47768. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  47769. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  47770. // is not used anywhere else.
  47771. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  47772. var Vertex = (function () {
  47773. function Vertex(pos, normal, uv) {
  47774. this.pos = pos;
  47775. this.normal = normal;
  47776. this.uv = uv;
  47777. }
  47778. Vertex.prototype.clone = function () {
  47779. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  47780. };
  47781. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  47782. // orientation of a polygon is flipped.
  47783. Vertex.prototype.flip = function () {
  47784. this.normal = this.normal.scale(-1);
  47785. };
  47786. // Create a new vertex between this vertex and `other` by linearly
  47787. // interpolating all properties using a parameter of `t`. Subclasses should
  47788. // override this to interpolate additional properties.
  47789. Vertex.prototype.interpolate = function (other, t) {
  47790. 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));
  47791. };
  47792. return Vertex;
  47793. }());
  47794. // # class Plane
  47795. // Represents a plane in 3D space.
  47796. var Plane = (function () {
  47797. function Plane(normal, w) {
  47798. this.normal = normal;
  47799. this.w = w;
  47800. }
  47801. Plane.FromPoints = function (a, b, c) {
  47802. var v0 = c.subtract(a);
  47803. var v1 = b.subtract(a);
  47804. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  47805. return null;
  47806. }
  47807. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  47808. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  47809. };
  47810. Plane.prototype.clone = function () {
  47811. return new Plane(this.normal.clone(), this.w);
  47812. };
  47813. Plane.prototype.flip = function () {
  47814. this.normal.scaleInPlace(-1);
  47815. this.w = -this.w;
  47816. };
  47817. // Split `polygon` by this plane if needed, then put the polygon or polygon
  47818. // fragments in the appropriate lists. Coplanar polygons go into either
  47819. // `coplanarFront` or `coplanarBack` depending on their orientation with
  47820. // respect to this plane. Polygons in front or in back of this plane go into
  47821. // either `front` or `back`.
  47822. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  47823. var COPLANAR = 0;
  47824. var FRONT = 1;
  47825. var BACK = 2;
  47826. var SPANNING = 3;
  47827. // Classify each point as well as the entire polygon into one of the above
  47828. // four classes.
  47829. var polygonType = 0;
  47830. var types = [];
  47831. var i;
  47832. var t;
  47833. for (i = 0; i < polygon.vertices.length; i++) {
  47834. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  47835. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  47836. polygonType |= type;
  47837. types.push(type);
  47838. }
  47839. // Put the polygon in the correct list, splitting it when necessary.
  47840. switch (polygonType) {
  47841. case COPLANAR:
  47842. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  47843. break;
  47844. case FRONT:
  47845. front.push(polygon);
  47846. break;
  47847. case BACK:
  47848. back.push(polygon);
  47849. break;
  47850. case SPANNING:
  47851. var f = [], b = [];
  47852. for (i = 0; i < polygon.vertices.length; i++) {
  47853. var j = (i + 1) % polygon.vertices.length;
  47854. var ti = types[i], tj = types[j];
  47855. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  47856. if (ti !== BACK)
  47857. f.push(vi);
  47858. if (ti !== FRONT)
  47859. b.push(ti !== BACK ? vi.clone() : vi);
  47860. if ((ti | tj) === SPANNING) {
  47861. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  47862. var v = vi.interpolate(vj, t);
  47863. f.push(v);
  47864. b.push(v.clone());
  47865. }
  47866. }
  47867. var poly;
  47868. if (f.length >= 3) {
  47869. poly = new Polygon(f, polygon.shared);
  47870. if (poly.plane)
  47871. front.push(poly);
  47872. }
  47873. if (b.length >= 3) {
  47874. poly = new Polygon(b, polygon.shared);
  47875. if (poly.plane)
  47876. back.push(poly);
  47877. }
  47878. break;
  47879. }
  47880. };
  47881. return Plane;
  47882. }());
  47883. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  47884. // point is on the plane.
  47885. Plane.EPSILON = 1e-5;
  47886. // # class Polygon
  47887. // Represents a convex polygon. The vertices used to initialize a polygon must
  47888. // be coplanar and form a convex loop.
  47889. //
  47890. // Each convex polygon has a `shared` property, which is shared between all
  47891. // polygons that are clones of each other or were split from the same polygon.
  47892. // This can be used to define per-polygon properties (such as surface color).
  47893. var Polygon = (function () {
  47894. function Polygon(vertices, shared) {
  47895. this.vertices = vertices;
  47896. this.shared = shared;
  47897. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  47898. }
  47899. Polygon.prototype.clone = function () {
  47900. var vertices = this.vertices.map(function (v) { return v.clone(); });
  47901. return new Polygon(vertices, this.shared);
  47902. };
  47903. Polygon.prototype.flip = function () {
  47904. this.vertices.reverse().map(function (v) { v.flip(); });
  47905. this.plane.flip();
  47906. };
  47907. return Polygon;
  47908. }());
  47909. // # class Node
  47910. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  47911. // by picking a polygon to split along. That polygon (and all other coplanar
  47912. // polygons) are added directly to that node and the other polygons are added to
  47913. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  47914. // no distinction between internal and leaf nodes.
  47915. var Node = (function () {
  47916. function Node(polygons) {
  47917. this.plane = null;
  47918. this.front = null;
  47919. this.back = null;
  47920. this.polygons = [];
  47921. if (polygons) {
  47922. this.build(polygons);
  47923. }
  47924. }
  47925. Node.prototype.clone = function () {
  47926. var node = new Node();
  47927. node.plane = this.plane && this.plane.clone();
  47928. node.front = this.front && this.front.clone();
  47929. node.back = this.back && this.back.clone();
  47930. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  47931. return node;
  47932. };
  47933. // Convert solid space to empty space and empty space to solid space.
  47934. Node.prototype.invert = function () {
  47935. for (var i = 0; i < this.polygons.length; i++) {
  47936. this.polygons[i].flip();
  47937. }
  47938. if (this.plane) {
  47939. this.plane.flip();
  47940. }
  47941. if (this.front) {
  47942. this.front.invert();
  47943. }
  47944. if (this.back) {
  47945. this.back.invert();
  47946. }
  47947. var temp = this.front;
  47948. this.front = this.back;
  47949. this.back = temp;
  47950. };
  47951. // Recursively remove all polygons in `polygons` that are inside this BSP
  47952. // tree.
  47953. Node.prototype.clipPolygons = function (polygons) {
  47954. if (!this.plane)
  47955. return polygons.slice();
  47956. var front = [], back = [];
  47957. for (var i = 0; i < polygons.length; i++) {
  47958. this.plane.splitPolygon(polygons[i], front, back, front, back);
  47959. }
  47960. if (this.front) {
  47961. front = this.front.clipPolygons(front);
  47962. }
  47963. if (this.back) {
  47964. back = this.back.clipPolygons(back);
  47965. }
  47966. else {
  47967. back = [];
  47968. }
  47969. return front.concat(back);
  47970. };
  47971. // Remove all polygons in this BSP tree that are inside the other BSP tree
  47972. // `bsp`.
  47973. Node.prototype.clipTo = function (bsp) {
  47974. this.polygons = bsp.clipPolygons(this.polygons);
  47975. if (this.front)
  47976. this.front.clipTo(bsp);
  47977. if (this.back)
  47978. this.back.clipTo(bsp);
  47979. };
  47980. // Return a list of all polygons in this BSP tree.
  47981. Node.prototype.allPolygons = function () {
  47982. var polygons = this.polygons.slice();
  47983. if (this.front)
  47984. polygons = polygons.concat(this.front.allPolygons());
  47985. if (this.back)
  47986. polygons = polygons.concat(this.back.allPolygons());
  47987. return polygons;
  47988. };
  47989. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  47990. // new polygons are filtered down to the bottom of the tree and become new
  47991. // nodes there. Each set of polygons is partitioned using the first polygon
  47992. // (no heuristic is used to pick a good split).
  47993. Node.prototype.build = function (polygons) {
  47994. if (!polygons.length)
  47995. return;
  47996. if (!this.plane)
  47997. this.plane = polygons[0].plane.clone();
  47998. var front = [], back = [];
  47999. for (var i = 0; i < polygons.length; i++) {
  48000. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  48001. }
  48002. if (front.length) {
  48003. if (!this.front)
  48004. this.front = new Node();
  48005. this.front.build(front);
  48006. }
  48007. if (back.length) {
  48008. if (!this.back)
  48009. this.back = new Node();
  48010. this.back.build(back);
  48011. }
  48012. };
  48013. return Node;
  48014. }());
  48015. var CSG = (function () {
  48016. function CSG() {
  48017. this.polygons = new Array();
  48018. }
  48019. // Convert BABYLON.Mesh to BABYLON.CSG
  48020. CSG.FromMesh = function (mesh) {
  48021. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  48022. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  48023. if (mesh instanceof BABYLON.Mesh) {
  48024. mesh.computeWorldMatrix(true);
  48025. matrix = mesh.getWorldMatrix();
  48026. meshPosition = mesh.position.clone();
  48027. meshRotation = mesh.rotation.clone();
  48028. if (mesh.rotationQuaternion) {
  48029. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  48030. }
  48031. meshScaling = mesh.scaling.clone();
  48032. }
  48033. else {
  48034. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  48035. }
  48036. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48037. var subMeshes = mesh.subMeshes;
  48038. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  48039. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  48040. vertices = [];
  48041. for (var j = 0; j < 3; j++) {
  48042. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  48043. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  48044. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  48045. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  48046. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  48047. vertex = new Vertex(position, normal, uv);
  48048. vertices.push(vertex);
  48049. }
  48050. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  48051. // To handle the case of degenerated triangle
  48052. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  48053. if (polygon.plane)
  48054. polygons.push(polygon);
  48055. }
  48056. }
  48057. var csg = CSG.FromPolygons(polygons);
  48058. csg.matrix = matrix;
  48059. csg.position = meshPosition;
  48060. csg.rotation = meshRotation;
  48061. csg.scaling = meshScaling;
  48062. csg.rotationQuaternion = meshRotationQuaternion;
  48063. currentCSGMeshId++;
  48064. return csg;
  48065. };
  48066. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  48067. CSG.FromPolygons = function (polygons) {
  48068. var csg = new CSG();
  48069. csg.polygons = polygons;
  48070. return csg;
  48071. };
  48072. CSG.prototype.clone = function () {
  48073. var csg = new CSG();
  48074. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  48075. csg.copyTransformAttributes(this);
  48076. return csg;
  48077. };
  48078. CSG.prototype.toPolygons = function () {
  48079. return this.polygons;
  48080. };
  48081. CSG.prototype.union = function (csg) {
  48082. var a = new Node(this.clone().polygons);
  48083. var b = new Node(csg.clone().polygons);
  48084. a.clipTo(b);
  48085. b.clipTo(a);
  48086. b.invert();
  48087. b.clipTo(a);
  48088. b.invert();
  48089. a.build(b.allPolygons());
  48090. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48091. };
  48092. CSG.prototype.unionInPlace = function (csg) {
  48093. var a = new Node(this.polygons);
  48094. var b = new Node(csg.polygons);
  48095. a.clipTo(b);
  48096. b.clipTo(a);
  48097. b.invert();
  48098. b.clipTo(a);
  48099. b.invert();
  48100. a.build(b.allPolygons());
  48101. this.polygons = a.allPolygons();
  48102. };
  48103. CSG.prototype.subtract = function (csg) {
  48104. var a = new Node(this.clone().polygons);
  48105. var b = new Node(csg.clone().polygons);
  48106. a.invert();
  48107. a.clipTo(b);
  48108. b.clipTo(a);
  48109. b.invert();
  48110. b.clipTo(a);
  48111. b.invert();
  48112. a.build(b.allPolygons());
  48113. a.invert();
  48114. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48115. };
  48116. CSG.prototype.subtractInPlace = function (csg) {
  48117. var a = new Node(this.polygons);
  48118. var b = new Node(csg.polygons);
  48119. a.invert();
  48120. a.clipTo(b);
  48121. b.clipTo(a);
  48122. b.invert();
  48123. b.clipTo(a);
  48124. b.invert();
  48125. a.build(b.allPolygons());
  48126. a.invert();
  48127. this.polygons = a.allPolygons();
  48128. };
  48129. CSG.prototype.intersect = function (csg) {
  48130. var a = new Node(this.clone().polygons);
  48131. var b = new Node(csg.clone().polygons);
  48132. a.invert();
  48133. b.clipTo(a);
  48134. b.invert();
  48135. a.clipTo(b);
  48136. b.clipTo(a);
  48137. a.build(b.allPolygons());
  48138. a.invert();
  48139. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48140. };
  48141. CSG.prototype.intersectInPlace = function (csg) {
  48142. var a = new Node(this.polygons);
  48143. var b = new Node(csg.polygons);
  48144. a.invert();
  48145. b.clipTo(a);
  48146. b.invert();
  48147. a.clipTo(b);
  48148. b.clipTo(a);
  48149. a.build(b.allPolygons());
  48150. a.invert();
  48151. this.polygons = a.allPolygons();
  48152. };
  48153. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  48154. // not modified.
  48155. CSG.prototype.inverse = function () {
  48156. var csg = this.clone();
  48157. csg.inverseInPlace();
  48158. return csg;
  48159. };
  48160. CSG.prototype.inverseInPlace = function () {
  48161. this.polygons.map(function (p) { p.flip(); });
  48162. };
  48163. // This is used to keep meshes transformations so they can be restored
  48164. // when we build back a Babylon Mesh
  48165. // NB : All CSG operations are performed in world coordinates
  48166. CSG.prototype.copyTransformAttributes = function (csg) {
  48167. this.matrix = csg.matrix;
  48168. this.position = csg.position;
  48169. this.rotation = csg.rotation;
  48170. this.scaling = csg.scaling;
  48171. this.rotationQuaternion = csg.rotationQuaternion;
  48172. return this;
  48173. };
  48174. // Build Raw mesh from CSG
  48175. // Coordinates here are in world space
  48176. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  48177. var matrix = this.matrix.clone();
  48178. matrix.invert();
  48179. 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;
  48180. if (keepSubMeshes) {
  48181. // Sort Polygons, since subMeshes are indices range
  48182. polygons.sort(function (a, b) {
  48183. if (a.shared.meshId === b.shared.meshId) {
  48184. return a.shared.subMeshId - b.shared.subMeshId;
  48185. }
  48186. else {
  48187. return a.shared.meshId - b.shared.meshId;
  48188. }
  48189. });
  48190. }
  48191. for (var i = 0, il = polygons.length; i < il; i++) {
  48192. polygon = polygons[i];
  48193. // Building SubMeshes
  48194. if (!subMesh_dict[polygon.shared.meshId]) {
  48195. subMesh_dict[polygon.shared.meshId] = {};
  48196. }
  48197. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  48198. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  48199. indexStart: +Infinity,
  48200. indexEnd: -Infinity,
  48201. materialIndex: polygon.shared.materialIndex
  48202. };
  48203. }
  48204. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  48205. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  48206. polygonIndices[0] = 0;
  48207. polygonIndices[1] = j - 1;
  48208. polygonIndices[2] = j;
  48209. for (var k = 0; k < 3; k++) {
  48210. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  48211. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  48212. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  48213. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  48214. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  48215. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  48216. // Check if 2 points can be merged
  48217. if (!(typeof vertex_idx !== 'undefined' &&
  48218. normals[vertex_idx * 3] === localNormal.x &&
  48219. normals[vertex_idx * 3 + 1] === localNormal.y &&
  48220. normals[vertex_idx * 3 + 2] === localNormal.z &&
  48221. uvs[vertex_idx * 2] === uv.x &&
  48222. uvs[vertex_idx * 2 + 1] === uv.y)) {
  48223. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  48224. uvs.push(uv.x, uv.y);
  48225. normals.push(normal.x, normal.y, normal.z);
  48226. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  48227. }
  48228. indices.push(vertex_idx);
  48229. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  48230. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  48231. currentIndex++;
  48232. }
  48233. }
  48234. }
  48235. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  48236. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  48237. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  48238. mesh.setIndices(indices);
  48239. if (keepSubMeshes) {
  48240. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  48241. var materialIndexOffset = 0, materialMaxIndex;
  48242. mesh.subMeshes = new Array();
  48243. for (var m in subMesh_dict) {
  48244. materialMaxIndex = -1;
  48245. for (var sm in subMesh_dict[m]) {
  48246. subMesh_obj = subMesh_dict[m][sm];
  48247. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  48248. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  48249. }
  48250. materialIndexOffset += ++materialMaxIndex;
  48251. }
  48252. }
  48253. return mesh;
  48254. };
  48255. // Build Mesh from CSG taking material and transforms into account
  48256. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  48257. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  48258. mesh.material = material;
  48259. mesh.position.copyFrom(this.position);
  48260. mesh.rotation.copyFrom(this.rotation);
  48261. if (this.rotationQuaternion) {
  48262. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  48263. }
  48264. mesh.scaling.copyFrom(this.scaling);
  48265. mesh.computeWorldMatrix(true);
  48266. return mesh;
  48267. };
  48268. return CSG;
  48269. }());
  48270. BABYLON.CSG = CSG;
  48271. })(BABYLON || (BABYLON = {}));
  48272. //# sourceMappingURL=babylon.csg.js.map
  48273. var BABYLON;
  48274. (function (BABYLON) {
  48275. var VRDistortionCorrectionPostProcess = (function (_super) {
  48276. __extends(VRDistortionCorrectionPostProcess, _super);
  48277. //ANY
  48278. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  48279. var _this = _super.call(this, name, "vrDistortionCorrection", [
  48280. 'LensCenter',
  48281. 'Scale',
  48282. 'ScaleIn',
  48283. 'HmdWarpParam'
  48284. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  48285. _this._isRightEye = isRightEye;
  48286. _this._distortionFactors = vrMetrics.distortionK;
  48287. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  48288. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  48289. _this.onSizeChangedObservable.add(function () {
  48290. _this.aspectRatio = _this.width * .5 / _this.height;
  48291. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  48292. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  48293. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  48294. });
  48295. _this.onApplyObservable.add(function (effect) {
  48296. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  48297. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  48298. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  48299. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  48300. });
  48301. return _this;
  48302. }
  48303. return VRDistortionCorrectionPostProcess;
  48304. }(BABYLON.PostProcess));
  48305. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  48306. })(BABYLON || (BABYLON = {}));
  48307. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  48308. // Mainly based on these 2 articles :
  48309. // 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
  48310. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  48311. var BABYLON;
  48312. (function (BABYLON) {
  48313. var JoystickAxis;
  48314. (function (JoystickAxis) {
  48315. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  48316. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  48317. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  48318. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  48319. var VirtualJoystick = (function () {
  48320. function VirtualJoystick(leftJoystick) {
  48321. var _this = this;
  48322. if (leftJoystick) {
  48323. this._leftJoystick = true;
  48324. }
  48325. else {
  48326. this._leftJoystick = false;
  48327. }
  48328. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  48329. VirtualJoystick._globalJoystickIndex++;
  48330. // By default left & right arrow keys are moving the X
  48331. // and up & down keys are moving the Y
  48332. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  48333. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  48334. this.reverseLeftRight = false;
  48335. this.reverseUpDown = false;
  48336. // collections of pointers
  48337. this._touches = new BABYLON.StringDictionary();
  48338. this.deltaPosition = BABYLON.Vector3.Zero();
  48339. this._joystickSensibility = 25;
  48340. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  48341. this._rotationSpeed = 25;
  48342. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  48343. this._rotateOnAxisRelativeToMesh = false;
  48344. this._onResize = function (evt) {
  48345. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  48346. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  48347. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  48348. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  48349. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  48350. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  48351. };
  48352. // injecting a canvas element on top of the canvas 3D game
  48353. if (!VirtualJoystick.vjCanvas) {
  48354. window.addEventListener("resize", this._onResize, false);
  48355. VirtualJoystick.vjCanvas = document.createElement("canvas");
  48356. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  48357. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  48358. VirtualJoystick.vjCanvas.width = window.innerWidth;
  48359. VirtualJoystick.vjCanvas.height = window.innerHeight;
  48360. VirtualJoystick.vjCanvas.style.width = "100%";
  48361. VirtualJoystick.vjCanvas.style.height = "100%";
  48362. VirtualJoystick.vjCanvas.style.position = "absolute";
  48363. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  48364. VirtualJoystick.vjCanvas.style.top = "0px";
  48365. VirtualJoystick.vjCanvas.style.left = "0px";
  48366. VirtualJoystick.vjCanvas.style.zIndex = "5";
  48367. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  48368. // Support for jQuery PEP polyfill
  48369. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  48370. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  48371. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  48372. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  48373. document.body.appendChild(VirtualJoystick.vjCanvas);
  48374. }
  48375. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  48376. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  48377. this.pressed = false;
  48378. // default joystick color
  48379. this._joystickColor = "cyan";
  48380. this._joystickPointerID = -1;
  48381. // current joystick position
  48382. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  48383. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  48384. // origin joystick position
  48385. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  48386. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  48387. this._onPointerDownHandlerRef = function (evt) {
  48388. _this._onPointerDown(evt);
  48389. };
  48390. this._onPointerMoveHandlerRef = function (evt) {
  48391. _this._onPointerMove(evt);
  48392. };
  48393. this._onPointerOutHandlerRef = function (evt) {
  48394. _this._onPointerUp(evt);
  48395. };
  48396. this._onPointerUpHandlerRef = function (evt) {
  48397. _this._onPointerUp(evt);
  48398. };
  48399. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  48400. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  48401. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  48402. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  48403. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  48404. evt.preventDefault(); // Disables system menu
  48405. }, false);
  48406. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  48407. }
  48408. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  48409. this._joystickSensibility = newJoystickSensibility;
  48410. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  48411. };
  48412. VirtualJoystick.prototype._onPointerDown = function (e) {
  48413. var positionOnScreenCondition;
  48414. e.preventDefault();
  48415. if (this._leftJoystick === true) {
  48416. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  48417. }
  48418. else {
  48419. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  48420. }
  48421. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  48422. // First contact will be dedicated to the virtual joystick
  48423. this._joystickPointerID = e.pointerId;
  48424. this._joystickPointerStartPos.x = e.clientX;
  48425. this._joystickPointerStartPos.y = e.clientY;
  48426. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  48427. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  48428. this._deltaJoystickVector.x = 0;
  48429. this._deltaJoystickVector.y = 0;
  48430. this.pressed = true;
  48431. this._touches.add(e.pointerId.toString(), e);
  48432. }
  48433. else {
  48434. // You can only trigger the action buttons with a joystick declared
  48435. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  48436. this._action();
  48437. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  48438. }
  48439. }
  48440. };
  48441. VirtualJoystick.prototype._onPointerMove = function (e) {
  48442. // If the current pointer is the one associated to the joystick (first touch contact)
  48443. if (this._joystickPointerID == e.pointerId) {
  48444. this._joystickPointerPos.x = e.clientX;
  48445. this._joystickPointerPos.y = e.clientY;
  48446. this._deltaJoystickVector = this._joystickPointerPos.clone();
  48447. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  48448. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  48449. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  48450. switch (this._axisTargetedByLeftAndRight) {
  48451. case JoystickAxis.X:
  48452. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  48453. break;
  48454. case JoystickAxis.Y:
  48455. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  48456. break;
  48457. case JoystickAxis.Z:
  48458. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  48459. break;
  48460. }
  48461. var directionUpDown = this.reverseUpDown ? 1 : -1;
  48462. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  48463. switch (this._axisTargetedByUpAndDown) {
  48464. case JoystickAxis.X:
  48465. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  48466. break;
  48467. case JoystickAxis.Y:
  48468. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  48469. break;
  48470. case JoystickAxis.Z:
  48471. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  48472. break;
  48473. }
  48474. }
  48475. else {
  48476. var data = this._touches.get(e.pointerId.toString());
  48477. if (data) {
  48478. data.x = e.clientX;
  48479. data.y = e.clientY;
  48480. }
  48481. }
  48482. };
  48483. VirtualJoystick.prototype._onPointerUp = function (e) {
  48484. if (this._joystickPointerID == e.pointerId) {
  48485. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  48486. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  48487. this._joystickPointerID = -1;
  48488. this.pressed = false;
  48489. }
  48490. else {
  48491. var touch = this._touches.get(e.pointerId.toString());
  48492. if (touch) {
  48493. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  48494. }
  48495. }
  48496. this._deltaJoystickVector.x = 0;
  48497. this._deltaJoystickVector.y = 0;
  48498. this._touches.remove(e.pointerId.toString());
  48499. };
  48500. /**
  48501. * Change the color of the virtual joystick
  48502. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  48503. */
  48504. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  48505. this._joystickColor = newColor;
  48506. };
  48507. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  48508. this._action = action;
  48509. };
  48510. // Define which axis you'd like to control for left & right
  48511. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  48512. switch (axis) {
  48513. case JoystickAxis.X:
  48514. case JoystickAxis.Y:
  48515. case JoystickAxis.Z:
  48516. this._axisTargetedByLeftAndRight = axis;
  48517. break;
  48518. default:
  48519. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  48520. break;
  48521. }
  48522. };
  48523. // Define which axis you'd like to control for up & down
  48524. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  48525. switch (axis) {
  48526. case JoystickAxis.X:
  48527. case JoystickAxis.Y:
  48528. case JoystickAxis.Z:
  48529. this._axisTargetedByUpAndDown = axis;
  48530. break;
  48531. default:
  48532. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  48533. break;
  48534. }
  48535. };
  48536. VirtualJoystick.prototype._clearCanvas = function () {
  48537. if (this._leftJoystick) {
  48538. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  48539. }
  48540. else {
  48541. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  48542. }
  48543. };
  48544. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  48545. var _this = this;
  48546. if (this.pressed) {
  48547. this._touches.forEach(function (key, touch) {
  48548. if (touch.pointerId === _this._joystickPointerID) {
  48549. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  48550. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  48551. VirtualJoystick.vjCanvasContext.beginPath();
  48552. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  48553. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48554. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  48555. VirtualJoystick.vjCanvasContext.stroke();
  48556. VirtualJoystick.vjCanvasContext.closePath();
  48557. VirtualJoystick.vjCanvasContext.beginPath();
  48558. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48559. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  48560. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  48561. VirtualJoystick.vjCanvasContext.stroke();
  48562. VirtualJoystick.vjCanvasContext.closePath();
  48563. VirtualJoystick.vjCanvasContext.beginPath();
  48564. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48565. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  48566. VirtualJoystick.vjCanvasContext.stroke();
  48567. VirtualJoystick.vjCanvasContext.closePath();
  48568. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  48569. }
  48570. else {
  48571. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  48572. VirtualJoystick.vjCanvasContext.beginPath();
  48573. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  48574. VirtualJoystick.vjCanvasContext.beginPath();
  48575. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  48576. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  48577. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  48578. VirtualJoystick.vjCanvasContext.stroke();
  48579. VirtualJoystick.vjCanvasContext.closePath();
  48580. touch.prevX = touch.x;
  48581. touch.prevY = touch.y;
  48582. }
  48583. ;
  48584. });
  48585. }
  48586. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  48587. };
  48588. VirtualJoystick.prototype.releaseCanvas = function () {
  48589. if (VirtualJoystick.vjCanvas) {
  48590. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  48591. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  48592. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  48593. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  48594. window.removeEventListener("resize", this._onResize);
  48595. document.body.removeChild(VirtualJoystick.vjCanvas);
  48596. VirtualJoystick.vjCanvas = null;
  48597. }
  48598. };
  48599. return VirtualJoystick;
  48600. }());
  48601. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  48602. VirtualJoystick._globalJoystickIndex = 0;
  48603. BABYLON.VirtualJoystick = VirtualJoystick;
  48604. })(BABYLON || (BABYLON = {}));
  48605. //# sourceMappingURL=babylon.virtualJoystick.js.map
  48606. var BABYLON;
  48607. (function (BABYLON) {
  48608. // We're mainly based on the logic defined into the FreeCamera code
  48609. var VirtualJoysticksCamera = (function (_super) {
  48610. __extends(VirtualJoysticksCamera, _super);
  48611. function VirtualJoysticksCamera(name, position, scene) {
  48612. var _this = _super.call(this, name, position, scene) || this;
  48613. _this.inputs.addVirtualJoystick();
  48614. return _this;
  48615. }
  48616. VirtualJoysticksCamera.prototype.getClassName = function () {
  48617. return "VirtualJoysticksCamera";
  48618. };
  48619. return VirtualJoysticksCamera;
  48620. }(BABYLON.FreeCamera));
  48621. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  48622. })(BABYLON || (BABYLON = {}));
  48623. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  48624. var BABYLON;
  48625. (function (BABYLON) {
  48626. var FreeCameraVirtualJoystickInput = (function () {
  48627. function FreeCameraVirtualJoystickInput() {
  48628. }
  48629. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  48630. return this._leftjoystick;
  48631. };
  48632. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  48633. return this._rightjoystick;
  48634. };
  48635. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  48636. if (this._leftjoystick) {
  48637. var camera = this.camera;
  48638. var speed = camera._computeLocalCameraSpeed() * 50;
  48639. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  48640. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  48641. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  48642. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  48643. if (!this._leftjoystick.pressed) {
  48644. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  48645. }
  48646. if (!this._rightjoystick.pressed) {
  48647. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  48648. }
  48649. }
  48650. };
  48651. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  48652. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  48653. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  48654. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  48655. this._leftjoystick.setJoystickSensibility(0.15);
  48656. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  48657. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  48658. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  48659. this._rightjoystick.reverseUpDown = true;
  48660. this._rightjoystick.setJoystickSensibility(0.05);
  48661. this._rightjoystick.setJoystickColor("yellow");
  48662. };
  48663. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  48664. this._leftjoystick.releaseCanvas();
  48665. this._rightjoystick.releaseCanvas();
  48666. };
  48667. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  48668. return "FreeCameraVirtualJoystickInput";
  48669. };
  48670. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  48671. return "virtualJoystick";
  48672. };
  48673. return FreeCameraVirtualJoystickInput;
  48674. }());
  48675. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  48676. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  48677. })(BABYLON || (BABYLON = {}));
  48678. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  48679. var BABYLON;
  48680. (function (BABYLON) {
  48681. var AnaglyphPostProcess = (function (_super) {
  48682. __extends(AnaglyphPostProcess, _super);
  48683. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  48684. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  48685. _this._passedProcess = rigCameras[0]._rigPostProcess;
  48686. _this.onApplyObservable.add(function (effect) {
  48687. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  48688. });
  48689. return _this;
  48690. }
  48691. return AnaglyphPostProcess;
  48692. }(BABYLON.PostProcess));
  48693. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  48694. })(BABYLON || (BABYLON = {}));
  48695. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  48696. var BABYLON;
  48697. (function (BABYLON) {
  48698. var OutlineRenderer = (function () {
  48699. function OutlineRenderer(scene) {
  48700. this._scene = scene;
  48701. }
  48702. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  48703. var _this = this;
  48704. if (useOverlay === void 0) { useOverlay = false; }
  48705. var scene = this._scene;
  48706. var engine = this._scene.getEngine();
  48707. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  48708. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  48709. return;
  48710. }
  48711. var mesh = subMesh.getRenderingMesh();
  48712. var material = subMesh.getMaterial();
  48713. engine.enableEffect(this._effect);
  48714. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  48715. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  48716. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  48717. // Bones
  48718. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48719. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48720. }
  48721. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  48722. // Alpha test
  48723. if (material && material.needAlphaTesting()) {
  48724. var alphaTexture = material.getAlphaTestTexture();
  48725. this._effect.setTexture("diffuseSampler", alphaTexture);
  48726. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48727. }
  48728. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  48729. };
  48730. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  48731. var defines = [];
  48732. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  48733. var mesh = subMesh.getMesh();
  48734. var material = subMesh.getMaterial();
  48735. // Alpha test
  48736. if (material && material.needAlphaTesting()) {
  48737. defines.push("#define ALPHATEST");
  48738. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48739. attribs.push(BABYLON.VertexBuffer.UVKind);
  48740. defines.push("#define UV1");
  48741. }
  48742. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48743. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48744. defines.push("#define UV2");
  48745. }
  48746. }
  48747. // Bones
  48748. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48749. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48750. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48751. if (mesh.numBoneInfluencers > 4) {
  48752. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48753. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48754. }
  48755. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48756. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48757. }
  48758. else {
  48759. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48760. }
  48761. // Instances
  48762. if (useInstances) {
  48763. defines.push("#define INSTANCES");
  48764. attribs.push("world0");
  48765. attribs.push("world1");
  48766. attribs.push("world2");
  48767. attribs.push("world3");
  48768. }
  48769. // Get correct effect
  48770. var join = defines.join("\n");
  48771. if (this._cachedDefines !== join) {
  48772. this._cachedDefines = join;
  48773. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  48774. }
  48775. return this._effect.isReady();
  48776. };
  48777. return OutlineRenderer;
  48778. }());
  48779. BABYLON.OutlineRenderer = OutlineRenderer;
  48780. })(BABYLON || (BABYLON = {}));
  48781. //# sourceMappingURL=babylon.outlineRenderer.js.map
  48782. var BABYLON;
  48783. (function (BABYLON) {
  48784. var MeshAssetTask = (function () {
  48785. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  48786. this.name = name;
  48787. this.meshesNames = meshesNames;
  48788. this.rootUrl = rootUrl;
  48789. this.sceneFilename = sceneFilename;
  48790. this.isCompleted = false;
  48791. }
  48792. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48793. var _this = this;
  48794. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  48795. _this.loadedMeshes = meshes;
  48796. _this.loadedParticleSystems = particleSystems;
  48797. _this.loadedSkeletons = skeletons;
  48798. _this.isCompleted = true;
  48799. if (_this.onSuccess) {
  48800. _this.onSuccess(_this);
  48801. }
  48802. onSuccess();
  48803. }, null, function () {
  48804. if (_this.onError) {
  48805. _this.onError(_this);
  48806. }
  48807. onError();
  48808. });
  48809. };
  48810. return MeshAssetTask;
  48811. }());
  48812. BABYLON.MeshAssetTask = MeshAssetTask;
  48813. var TextFileAssetTask = (function () {
  48814. function TextFileAssetTask(name, url) {
  48815. this.name = name;
  48816. this.url = url;
  48817. this.isCompleted = false;
  48818. }
  48819. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48820. var _this = this;
  48821. BABYLON.Tools.LoadFile(this.url, function (data) {
  48822. _this.text = data;
  48823. _this.isCompleted = true;
  48824. if (_this.onSuccess) {
  48825. _this.onSuccess(_this);
  48826. }
  48827. onSuccess();
  48828. }, null, scene.database, false, function () {
  48829. if (_this.onError) {
  48830. _this.onError(_this);
  48831. }
  48832. onError();
  48833. });
  48834. };
  48835. return TextFileAssetTask;
  48836. }());
  48837. BABYLON.TextFileAssetTask = TextFileAssetTask;
  48838. var BinaryFileAssetTask = (function () {
  48839. function BinaryFileAssetTask(name, url) {
  48840. this.name = name;
  48841. this.url = url;
  48842. this.isCompleted = false;
  48843. }
  48844. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48845. var _this = this;
  48846. BABYLON.Tools.LoadFile(this.url, function (data) {
  48847. _this.data = data;
  48848. _this.isCompleted = true;
  48849. if (_this.onSuccess) {
  48850. _this.onSuccess(_this);
  48851. }
  48852. onSuccess();
  48853. }, null, scene.database, true, function () {
  48854. if (_this.onError) {
  48855. _this.onError(_this);
  48856. }
  48857. onError();
  48858. });
  48859. };
  48860. return BinaryFileAssetTask;
  48861. }());
  48862. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  48863. var ImageAssetTask = (function () {
  48864. function ImageAssetTask(name, url) {
  48865. this.name = name;
  48866. this.url = url;
  48867. this.isCompleted = false;
  48868. }
  48869. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48870. var _this = this;
  48871. var img = new Image();
  48872. BABYLON.Tools.SetCorsBehavior(this.url, img);
  48873. img.onload = function () {
  48874. _this.image = img;
  48875. _this.isCompleted = true;
  48876. if (_this.onSuccess) {
  48877. _this.onSuccess(_this);
  48878. }
  48879. onSuccess();
  48880. };
  48881. img.onerror = function () {
  48882. if (_this.onError) {
  48883. _this.onError(_this);
  48884. }
  48885. onError();
  48886. };
  48887. img.src = this.url;
  48888. };
  48889. return ImageAssetTask;
  48890. }());
  48891. BABYLON.ImageAssetTask = ImageAssetTask;
  48892. var TextureAssetTask = (function () {
  48893. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  48894. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48895. this.name = name;
  48896. this.url = url;
  48897. this.noMipmap = noMipmap;
  48898. this.invertY = invertY;
  48899. this.samplingMode = samplingMode;
  48900. this.isCompleted = false;
  48901. }
  48902. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48903. var _this = this;
  48904. var onload = function () {
  48905. _this.isCompleted = true;
  48906. if (_this.onSuccess) {
  48907. _this.onSuccess(_this);
  48908. }
  48909. onSuccess();
  48910. };
  48911. var onerror = function () {
  48912. if (_this.onError) {
  48913. _this.onError(_this);
  48914. }
  48915. onError();
  48916. };
  48917. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  48918. };
  48919. return TextureAssetTask;
  48920. }());
  48921. BABYLON.TextureAssetTask = TextureAssetTask;
  48922. var CubeTextureAssetTask = (function () {
  48923. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  48924. this.name = name;
  48925. this.url = url;
  48926. this.extensions = extensions;
  48927. this.noMipmap = noMipmap;
  48928. this.files = files;
  48929. this.isCompleted = false;
  48930. }
  48931. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48932. var _this = this;
  48933. var onload = function () {
  48934. _this.isCompleted = true;
  48935. if (_this.onSuccess) {
  48936. _this.onSuccess(_this);
  48937. }
  48938. onSuccess();
  48939. };
  48940. var onerror = function () {
  48941. if (_this.onError) {
  48942. _this.onError(_this);
  48943. }
  48944. onError();
  48945. };
  48946. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  48947. };
  48948. return CubeTextureAssetTask;
  48949. }());
  48950. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  48951. var HDRCubeTextureAssetTask = (function () {
  48952. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  48953. if (noMipmap === void 0) { noMipmap = false; }
  48954. if (generateHarmonics === void 0) { generateHarmonics = true; }
  48955. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  48956. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  48957. this.name = name;
  48958. this.url = url;
  48959. this.size = size;
  48960. this.noMipmap = noMipmap;
  48961. this.generateHarmonics = generateHarmonics;
  48962. this.useInGammaSpace = useInGammaSpace;
  48963. this.usePMREMGenerator = usePMREMGenerator;
  48964. this.isCompleted = false;
  48965. }
  48966. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48967. var _this = this;
  48968. var onload = function () {
  48969. _this.isCompleted = true;
  48970. if (_this.onSuccess) {
  48971. _this.onSuccess(_this);
  48972. }
  48973. onSuccess();
  48974. };
  48975. var onerror = function () {
  48976. if (_this.onError) {
  48977. _this.onError(_this);
  48978. }
  48979. onError();
  48980. };
  48981. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  48982. };
  48983. return HDRCubeTextureAssetTask;
  48984. }());
  48985. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  48986. var AssetsManager = (function () {
  48987. function AssetsManager(scene) {
  48988. this.tasks = new Array();
  48989. this.waitingTasksCount = 0;
  48990. this.useDefaultLoadingScreen = true;
  48991. this._scene = scene;
  48992. }
  48993. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  48994. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  48995. this.tasks.push(task);
  48996. return task;
  48997. };
  48998. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  48999. var task = new TextFileAssetTask(taskName, url);
  49000. this.tasks.push(task);
  49001. return task;
  49002. };
  49003. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  49004. var task = new BinaryFileAssetTask(taskName, url);
  49005. this.tasks.push(task);
  49006. return task;
  49007. };
  49008. AssetsManager.prototype.addImageTask = function (taskName, url) {
  49009. var task = new ImageAssetTask(taskName, url);
  49010. this.tasks.push(task);
  49011. return task;
  49012. };
  49013. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  49014. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49015. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  49016. this.tasks.push(task);
  49017. return task;
  49018. };
  49019. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  49020. this.waitingTasksCount--;
  49021. if (this.waitingTasksCount === 0) {
  49022. if (this.onFinish) {
  49023. this.onFinish(this.tasks);
  49024. }
  49025. this._scene.getEngine().hideLoadingUI();
  49026. }
  49027. };
  49028. AssetsManager.prototype._runTask = function (task) {
  49029. var _this = this;
  49030. task.run(this._scene, function () {
  49031. if (_this.onTaskSuccess) {
  49032. _this.onTaskSuccess(task);
  49033. }
  49034. _this._decreaseWaitingTasksCount();
  49035. }, function () {
  49036. if (_this.onTaskError) {
  49037. _this.onTaskError(task);
  49038. }
  49039. _this._decreaseWaitingTasksCount();
  49040. });
  49041. };
  49042. AssetsManager.prototype.reset = function () {
  49043. this.tasks = new Array();
  49044. return this;
  49045. };
  49046. AssetsManager.prototype.load = function () {
  49047. this.waitingTasksCount = this.tasks.length;
  49048. if (this.waitingTasksCount === 0) {
  49049. if (this.onFinish) {
  49050. this.onFinish(this.tasks);
  49051. }
  49052. return this;
  49053. }
  49054. if (this.useDefaultLoadingScreen) {
  49055. this._scene.getEngine().displayLoadingUI();
  49056. }
  49057. for (var index = 0; index < this.tasks.length; index++) {
  49058. var task = this.tasks[index];
  49059. this._runTask(task);
  49060. }
  49061. return this;
  49062. };
  49063. return AssetsManager;
  49064. }());
  49065. BABYLON.AssetsManager = AssetsManager;
  49066. })(BABYLON || (BABYLON = {}));
  49067. //# sourceMappingURL=babylon.assetsManager.js.map
  49068. var BABYLON;
  49069. (function (BABYLON) {
  49070. var VRCameraMetrics = (function () {
  49071. function VRCameraMetrics() {
  49072. this.compensateDistortion = true;
  49073. }
  49074. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  49075. get: function () {
  49076. return this.hResolution / (2 * this.vResolution);
  49077. },
  49078. enumerable: true,
  49079. configurable: true
  49080. });
  49081. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  49082. get: function () {
  49083. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  49084. },
  49085. enumerable: true,
  49086. configurable: true
  49087. });
  49088. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  49089. get: function () {
  49090. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  49091. var h = (4 * meters) / this.hScreenSize;
  49092. return BABYLON.Matrix.Translation(h, 0, 0);
  49093. },
  49094. enumerable: true,
  49095. configurable: true
  49096. });
  49097. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  49098. get: function () {
  49099. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  49100. var h = (4 * meters) / this.hScreenSize;
  49101. return BABYLON.Matrix.Translation(-h, 0, 0);
  49102. },
  49103. enumerable: true,
  49104. configurable: true
  49105. });
  49106. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  49107. get: function () {
  49108. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  49109. },
  49110. enumerable: true,
  49111. configurable: true
  49112. });
  49113. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  49114. get: function () {
  49115. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  49116. },
  49117. enumerable: true,
  49118. configurable: true
  49119. });
  49120. VRCameraMetrics.GetDefault = function () {
  49121. var result = new VRCameraMetrics();
  49122. result.hResolution = 1280;
  49123. result.vResolution = 800;
  49124. result.hScreenSize = 0.149759993;
  49125. result.vScreenSize = 0.0935999975;
  49126. result.vScreenCenter = 0.0467999987;
  49127. result.eyeToScreenDistance = 0.0410000011;
  49128. result.lensSeparationDistance = 0.0635000020;
  49129. result.interpupillaryDistance = 0.0640000030;
  49130. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  49131. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  49132. result.postProcessScaleFactor = 1.714605507808412;
  49133. result.lensCenterOffset = 0.151976421;
  49134. return result;
  49135. };
  49136. return VRCameraMetrics;
  49137. }());
  49138. BABYLON.VRCameraMetrics = VRCameraMetrics;
  49139. })(BABYLON || (BABYLON = {}));
  49140. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  49141. var BABYLON;
  49142. (function (BABYLON) {
  49143. var WebVRFreeCamera = (function (_super) {
  49144. __extends(WebVRFreeCamera, _super);
  49145. function WebVRFreeCamera(name, position, scene, webVROptions) {
  49146. if (webVROptions === void 0) { webVROptions = {}; }
  49147. var _this = _super.call(this, name, position, scene) || this;
  49148. _this.webVROptions = webVROptions;
  49149. _this._vrDevice = null;
  49150. _this.rawPose = null;
  49151. _this._vrEnabled = false;
  49152. _this._attached = false;
  49153. _this._positionOffset = BABYLON.Vector3.Zero();
  49154. _this._descendants = [];
  49155. _this.devicePosition = BABYLON.Vector3.Zero();
  49156. _this.deviceScaleFactor = 1;
  49157. _this.controllers = [];
  49158. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  49159. //legacy support - the compensation boolean was removed.
  49160. if (arguments.length === 5) {
  49161. _this.webVROptions = arguments[4];
  49162. }
  49163. // default webVR options
  49164. if (_this.webVROptions.trackPosition == undefined) {
  49165. _this.webVROptions.trackPosition = true;
  49166. }
  49167. if (_this.webVROptions.controllerMeshes == undefined) {
  49168. _this.webVROptions.controllerMeshes = true;
  49169. }
  49170. _this.rotationQuaternion = new BABYLON.Quaternion();
  49171. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  49172. if (_this.webVROptions && _this.webVROptions.positionScale) {
  49173. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  49174. }
  49175. //enable VR
  49176. _this.getEngine().initWebVR();
  49177. if (!_this.getEngine().vrDisplaysPromise) {
  49178. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  49179. }
  49180. else {
  49181. _this._frameData = new VRFrameData();
  49182. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  49183. if (devices.length > 0) {
  49184. _this._vrEnabled = true;
  49185. if (_this.webVROptions.displayName) {
  49186. var found = devices.some(function (device) {
  49187. if (device.displayName === _this.webVROptions.displayName) {
  49188. _this._vrDevice = device;
  49189. return true;
  49190. }
  49191. else {
  49192. return false;
  49193. }
  49194. });
  49195. if (!found) {
  49196. _this._vrDevice = devices[0];
  49197. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  49198. }
  49199. }
  49200. else {
  49201. //choose the first one
  49202. _this._vrDevice = devices[0];
  49203. }
  49204. //reset the rig parameters.
  49205. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData });
  49206. if (_this._attached) {
  49207. _this.getEngine().enableVR(_this._vrDevice);
  49208. }
  49209. }
  49210. else {
  49211. BABYLON.Tools.Error("No WebVR devices found!");
  49212. }
  49213. });
  49214. }
  49215. // try to attach the controllers, if found.
  49216. _this.initControllers();
  49217. /**
  49218. * The idea behind the following lines:
  49219. * objects that have the camera as parent should actually have the rig cameras as a parent.
  49220. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  49221. * the second will not show it correctly.
  49222. *
  49223. * To solve this - each object that has the camera as parent will be added to a protected array.
  49224. * When the rig camera renders, it will take this array and set all of those to be its children.
  49225. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  49226. * Amazing!
  49227. */
  49228. scene.onBeforeCameraRenderObservable.add(function (camera) {
  49229. if (camera.parent === _this && _this.rigParenting) {
  49230. _this._descendants = _this.getDescendants(true, function (n) {
  49231. // don't take the cameras or the controllers!
  49232. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  49233. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  49234. return !isController && !isRigCamera;
  49235. });
  49236. _this._descendants.forEach(function (node) {
  49237. node.parent = camera;
  49238. });
  49239. }
  49240. });
  49241. scene.onAfterCameraRenderObservable.add(function (camera) {
  49242. if (camera.parent === _this && _this.rigParenting) {
  49243. _this._descendants.forEach(function (node) {
  49244. node.parent = _this;
  49245. });
  49246. }
  49247. });
  49248. return _this;
  49249. }
  49250. WebVRFreeCamera.prototype._checkInputs = function () {
  49251. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  49252. var currentPose = this._frameData.pose;
  49253. this.updateFromDevice(currentPose);
  49254. }
  49255. _super.prototype._checkInputs.call(this);
  49256. };
  49257. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  49258. if (poseData && poseData.orientation) {
  49259. this.rawPose = poseData;
  49260. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  49261. if (this.getScene().useRightHandedSystem) {
  49262. this.deviceRotationQuaternion.z *= -1;
  49263. this.deviceRotationQuaternion.w *= -1;
  49264. }
  49265. if (this.webVROptions.trackPosition && this.rawPose.position) {
  49266. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  49267. if (this.getScene().useRightHandedSystem) {
  49268. this.devicePosition.z *= -1;
  49269. }
  49270. }
  49271. }
  49272. };
  49273. /**
  49274. * WebVR's attach control will start broadcasting frames to the device.
  49275. * Note that in certain browsers (chrome for example) this function must be called
  49276. * within a user-interaction callback. Example:
  49277. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  49278. *
  49279. * @param {HTMLElement} element
  49280. * @param {boolean} [noPreventDefault]
  49281. *
  49282. * @memberOf WebVRFreeCamera
  49283. */
  49284. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49285. _super.prototype.attachControl.call(this, element, noPreventDefault);
  49286. this._attached = true;
  49287. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  49288. if (this._vrEnabled) {
  49289. this.getEngine().enableVR(this._vrDevice);
  49290. }
  49291. };
  49292. WebVRFreeCamera.prototype.detachControl = function (element) {
  49293. _super.prototype.detachControl.call(this, element);
  49294. this._vrEnabled = false;
  49295. this._attached = false;
  49296. this.getEngine().disableVR();
  49297. };
  49298. WebVRFreeCamera.prototype.getClassName = function () {
  49299. return "WebVRFreeCamera";
  49300. };
  49301. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  49302. //uses the vrDisplay's "resetPose()".
  49303. //pitch and roll won't be affected.
  49304. this._vrDevice.resetPose();
  49305. };
  49306. WebVRFreeCamera.prototype._updateRigCameras = function () {
  49307. var camLeft = this._rigCameras[0];
  49308. var camRight = this._rigCameras[1];
  49309. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  49310. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  49311. camLeft.position.copyFrom(this.devicePosition);
  49312. camRight.position.copyFrom(this.devicePosition);
  49313. };
  49314. /**
  49315. * This function is called by the two RIG cameras.
  49316. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  49317. */
  49318. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  49319. var _this = this;
  49320. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  49321. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  49322. if (!this.getScene().useRightHandedSystem) {
  49323. [2, 6, 8, 9, 14].forEach(function (num) {
  49324. _this._webvrViewMatrix.m[num] *= -1;
  49325. });
  49326. }
  49327. var parentCamera = this._cameraRigParams["parentCamera"];
  49328. // should the view matrix be updated with scale and position offset?
  49329. if (parentCamera.deviceScaleFactor !== 1) {
  49330. this._webvrViewMatrix.invert();
  49331. // scale the position, if set
  49332. if (parentCamera.deviceScaleFactor) {
  49333. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  49334. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  49335. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  49336. }
  49337. this._webvrViewMatrix.invert();
  49338. }
  49339. // update the camera rotation matrix
  49340. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  49341. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  49342. // Computing target and final matrix
  49343. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  49344. return this._webvrViewMatrix;
  49345. };
  49346. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  49347. var _this = this;
  49348. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  49349. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  49350. //babylon compatible matrix
  49351. if (!this.getScene().useRightHandedSystem) {
  49352. [8, 9, 10, 11].forEach(function (num) {
  49353. _this._projectionMatrix.m[num] *= -1;
  49354. });
  49355. }
  49356. return this._projectionMatrix;
  49357. };
  49358. WebVRFreeCamera.prototype.initControllers = function () {
  49359. var _this = this;
  49360. this.controllers = [];
  49361. new BABYLON.Gamepads(function (gp) {
  49362. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  49363. var webVrController = gp;
  49364. if (_this.webVROptions.controllerMeshes) {
  49365. webVrController.initControllerMesh(_this.getScene());
  49366. }
  49367. webVrController.attachToPoseControlledCamera(_this);
  49368. // since this is async - sanity check. Is the controller already stored?
  49369. if (_this.controllers.indexOf(webVrController) === -1) {
  49370. //add to the controllers array
  49371. _this.controllers.push(webVrController);
  49372. //did we find enough controllers? Great! let the developer know.
  49373. if (_this.onControllersAttached && _this.controllers.length === 2) {
  49374. _this.onControllersAttached(_this.controllers);
  49375. }
  49376. }
  49377. }
  49378. });
  49379. };
  49380. return WebVRFreeCamera;
  49381. }(BABYLON.FreeCamera));
  49382. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  49383. })(BABYLON || (BABYLON = {}));
  49384. //# sourceMappingURL=babylon.webVRCamera.js.map
  49385. var BABYLON;
  49386. (function (BABYLON) {
  49387. // Standard optimizations
  49388. var SceneOptimization = (function () {
  49389. function SceneOptimization(priority) {
  49390. if (priority === void 0) { priority = 0; }
  49391. this.priority = priority;
  49392. this.apply = function (scene) {
  49393. return true; // Return true if everything that can be done was applied
  49394. };
  49395. }
  49396. return SceneOptimization;
  49397. }());
  49398. BABYLON.SceneOptimization = SceneOptimization;
  49399. var TextureOptimization = (function (_super) {
  49400. __extends(TextureOptimization, _super);
  49401. function TextureOptimization(priority, maximumSize) {
  49402. if (priority === void 0) { priority = 0; }
  49403. if (maximumSize === void 0) { maximumSize = 1024; }
  49404. var _this = _super.call(this, priority) || this;
  49405. _this.priority = priority;
  49406. _this.maximumSize = maximumSize;
  49407. _this.apply = function (scene) {
  49408. var allDone = true;
  49409. for (var index = 0; index < scene.textures.length; index++) {
  49410. var texture = scene.textures[index];
  49411. if (!texture.canRescale) {
  49412. continue;
  49413. }
  49414. var currentSize = texture.getSize();
  49415. var maxDimension = Math.max(currentSize.width, currentSize.height);
  49416. if (maxDimension > _this.maximumSize) {
  49417. texture.scale(0.5);
  49418. allDone = false;
  49419. }
  49420. }
  49421. return allDone;
  49422. };
  49423. return _this;
  49424. }
  49425. return TextureOptimization;
  49426. }(SceneOptimization));
  49427. BABYLON.TextureOptimization = TextureOptimization;
  49428. var HardwareScalingOptimization = (function (_super) {
  49429. __extends(HardwareScalingOptimization, _super);
  49430. function HardwareScalingOptimization(priority, maximumScale) {
  49431. if (priority === void 0) { priority = 0; }
  49432. if (maximumScale === void 0) { maximumScale = 2; }
  49433. var _this = _super.call(this, priority) || this;
  49434. _this.priority = priority;
  49435. _this.maximumScale = maximumScale;
  49436. _this._currentScale = 1;
  49437. _this.apply = function (scene) {
  49438. _this._currentScale++;
  49439. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  49440. return _this._currentScale >= _this.maximumScale;
  49441. };
  49442. return _this;
  49443. }
  49444. return HardwareScalingOptimization;
  49445. }(SceneOptimization));
  49446. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  49447. var ShadowsOptimization = (function (_super) {
  49448. __extends(ShadowsOptimization, _super);
  49449. function ShadowsOptimization() {
  49450. var _this = _super !== null && _super.apply(this, arguments) || this;
  49451. _this.apply = function (scene) {
  49452. scene.shadowsEnabled = false;
  49453. return true;
  49454. };
  49455. return _this;
  49456. }
  49457. return ShadowsOptimization;
  49458. }(SceneOptimization));
  49459. BABYLON.ShadowsOptimization = ShadowsOptimization;
  49460. var PostProcessesOptimization = (function (_super) {
  49461. __extends(PostProcessesOptimization, _super);
  49462. function PostProcessesOptimization() {
  49463. var _this = _super !== null && _super.apply(this, arguments) || this;
  49464. _this.apply = function (scene) {
  49465. scene.postProcessesEnabled = false;
  49466. return true;
  49467. };
  49468. return _this;
  49469. }
  49470. return PostProcessesOptimization;
  49471. }(SceneOptimization));
  49472. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  49473. var LensFlaresOptimization = (function (_super) {
  49474. __extends(LensFlaresOptimization, _super);
  49475. function LensFlaresOptimization() {
  49476. var _this = _super !== null && _super.apply(this, arguments) || this;
  49477. _this.apply = function (scene) {
  49478. scene.lensFlaresEnabled = false;
  49479. return true;
  49480. };
  49481. return _this;
  49482. }
  49483. return LensFlaresOptimization;
  49484. }(SceneOptimization));
  49485. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  49486. var ParticlesOptimization = (function (_super) {
  49487. __extends(ParticlesOptimization, _super);
  49488. function ParticlesOptimization() {
  49489. var _this = _super !== null && _super.apply(this, arguments) || this;
  49490. _this.apply = function (scene) {
  49491. scene.particlesEnabled = false;
  49492. return true;
  49493. };
  49494. return _this;
  49495. }
  49496. return ParticlesOptimization;
  49497. }(SceneOptimization));
  49498. BABYLON.ParticlesOptimization = ParticlesOptimization;
  49499. var RenderTargetsOptimization = (function (_super) {
  49500. __extends(RenderTargetsOptimization, _super);
  49501. function RenderTargetsOptimization() {
  49502. var _this = _super !== null && _super.apply(this, arguments) || this;
  49503. _this.apply = function (scene) {
  49504. scene.renderTargetsEnabled = false;
  49505. return true;
  49506. };
  49507. return _this;
  49508. }
  49509. return RenderTargetsOptimization;
  49510. }(SceneOptimization));
  49511. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  49512. var MergeMeshesOptimization = (function (_super) {
  49513. __extends(MergeMeshesOptimization, _super);
  49514. function MergeMeshesOptimization() {
  49515. var _this = _super !== null && _super.apply(this, arguments) || this;
  49516. _this._canBeMerged = function (abstractMesh) {
  49517. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  49518. return false;
  49519. }
  49520. var mesh = abstractMesh;
  49521. if (!mesh.isVisible || !mesh.isEnabled()) {
  49522. return false;
  49523. }
  49524. if (mesh.instances.length > 0) {
  49525. return false;
  49526. }
  49527. if (mesh.skeleton || mesh.hasLODLevels) {
  49528. return false;
  49529. }
  49530. if (mesh.parent) {
  49531. return false;
  49532. }
  49533. return true;
  49534. };
  49535. _this.apply = function (scene, updateSelectionTree) {
  49536. var globalPool = scene.meshes.slice(0);
  49537. var globalLength = globalPool.length;
  49538. for (var index = 0; index < globalLength; index++) {
  49539. var currentPool = new Array();
  49540. var current = globalPool[index];
  49541. // Checks
  49542. if (!_this._canBeMerged(current)) {
  49543. continue;
  49544. }
  49545. currentPool.push(current);
  49546. // Find compatible meshes
  49547. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  49548. var otherMesh = globalPool[subIndex];
  49549. if (!_this._canBeMerged(otherMesh)) {
  49550. continue;
  49551. }
  49552. if (otherMesh.material !== current.material) {
  49553. continue;
  49554. }
  49555. if (otherMesh.checkCollisions !== current.checkCollisions) {
  49556. continue;
  49557. }
  49558. currentPool.push(otherMesh);
  49559. globalLength--;
  49560. globalPool.splice(subIndex, 1);
  49561. subIndex--;
  49562. }
  49563. if (currentPool.length < 2) {
  49564. continue;
  49565. }
  49566. // Merge meshes
  49567. BABYLON.Mesh.MergeMeshes(currentPool);
  49568. }
  49569. if (updateSelectionTree != undefined) {
  49570. if (updateSelectionTree) {
  49571. scene.createOrUpdateSelectionOctree();
  49572. }
  49573. }
  49574. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  49575. scene.createOrUpdateSelectionOctree();
  49576. }
  49577. return true;
  49578. };
  49579. return _this;
  49580. }
  49581. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  49582. get: function () {
  49583. return MergeMeshesOptimization._UpdateSelectionTree;
  49584. },
  49585. set: function (value) {
  49586. MergeMeshesOptimization._UpdateSelectionTree = value;
  49587. },
  49588. enumerable: true,
  49589. configurable: true
  49590. });
  49591. return MergeMeshesOptimization;
  49592. }(SceneOptimization));
  49593. MergeMeshesOptimization._UpdateSelectionTree = false;
  49594. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  49595. // Options
  49596. var SceneOptimizerOptions = (function () {
  49597. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  49598. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  49599. if (trackerDuration === void 0) { trackerDuration = 2000; }
  49600. this.targetFrameRate = targetFrameRate;
  49601. this.trackerDuration = trackerDuration;
  49602. this.optimizations = new Array();
  49603. }
  49604. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  49605. var result = new SceneOptimizerOptions(targetFrameRate);
  49606. var priority = 0;
  49607. result.optimizations.push(new MergeMeshesOptimization(priority));
  49608. result.optimizations.push(new ShadowsOptimization(priority));
  49609. result.optimizations.push(new LensFlaresOptimization(priority));
  49610. // Next priority
  49611. priority++;
  49612. result.optimizations.push(new PostProcessesOptimization(priority));
  49613. result.optimizations.push(new ParticlesOptimization(priority));
  49614. // Next priority
  49615. priority++;
  49616. result.optimizations.push(new TextureOptimization(priority, 1024));
  49617. return result;
  49618. };
  49619. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  49620. var result = new SceneOptimizerOptions(targetFrameRate);
  49621. var priority = 0;
  49622. result.optimizations.push(new MergeMeshesOptimization(priority));
  49623. result.optimizations.push(new ShadowsOptimization(priority));
  49624. result.optimizations.push(new LensFlaresOptimization(priority));
  49625. // Next priority
  49626. priority++;
  49627. result.optimizations.push(new PostProcessesOptimization(priority));
  49628. result.optimizations.push(new ParticlesOptimization(priority));
  49629. // Next priority
  49630. priority++;
  49631. result.optimizations.push(new TextureOptimization(priority, 512));
  49632. // Next priority
  49633. priority++;
  49634. result.optimizations.push(new RenderTargetsOptimization(priority));
  49635. // Next priority
  49636. priority++;
  49637. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  49638. return result;
  49639. };
  49640. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  49641. var result = new SceneOptimizerOptions(targetFrameRate);
  49642. var priority = 0;
  49643. result.optimizations.push(new MergeMeshesOptimization(priority));
  49644. result.optimizations.push(new ShadowsOptimization(priority));
  49645. result.optimizations.push(new LensFlaresOptimization(priority));
  49646. // Next priority
  49647. priority++;
  49648. result.optimizations.push(new PostProcessesOptimization(priority));
  49649. result.optimizations.push(new ParticlesOptimization(priority));
  49650. // Next priority
  49651. priority++;
  49652. result.optimizations.push(new TextureOptimization(priority, 256));
  49653. // Next priority
  49654. priority++;
  49655. result.optimizations.push(new RenderTargetsOptimization(priority));
  49656. // Next priority
  49657. priority++;
  49658. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  49659. return result;
  49660. };
  49661. return SceneOptimizerOptions;
  49662. }());
  49663. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  49664. // Scene optimizer tool
  49665. var SceneOptimizer = (function () {
  49666. function SceneOptimizer() {
  49667. }
  49668. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  49669. // TODO: add an epsilon
  49670. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  49671. if (onSuccess) {
  49672. onSuccess();
  49673. }
  49674. return;
  49675. }
  49676. // Apply current level of optimizations
  49677. var allDone = true;
  49678. var noOptimizationApplied = true;
  49679. for (var index = 0; index < options.optimizations.length; index++) {
  49680. var optimization = options.optimizations[index];
  49681. if (optimization.priority === currentPriorityLevel) {
  49682. noOptimizationApplied = false;
  49683. allDone = allDone && optimization.apply(scene);
  49684. }
  49685. }
  49686. // If no optimization was applied, this is a failure :(
  49687. if (noOptimizationApplied) {
  49688. if (onFailure) {
  49689. onFailure();
  49690. }
  49691. return;
  49692. }
  49693. // If all optimizations were done, move to next level
  49694. if (allDone) {
  49695. currentPriorityLevel++;
  49696. }
  49697. // Let's the system running for a specific amount of time before checking FPS
  49698. scene.executeWhenReady(function () {
  49699. setTimeout(function () {
  49700. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  49701. }, options.trackerDuration);
  49702. });
  49703. };
  49704. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  49705. if (!options) {
  49706. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  49707. }
  49708. // Let's the system running for a specific amount of time before checking FPS
  49709. scene.executeWhenReady(function () {
  49710. setTimeout(function () {
  49711. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  49712. }, options.trackerDuration);
  49713. });
  49714. };
  49715. return SceneOptimizer;
  49716. }());
  49717. BABYLON.SceneOptimizer = SceneOptimizer;
  49718. })(BABYLON || (BABYLON = {}));
  49719. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  49720. var BABYLON;
  49721. (function (BABYLON) {
  49722. var Internals;
  49723. (function (Internals) {
  49724. var MeshLODLevel = (function () {
  49725. function MeshLODLevel(distance, mesh) {
  49726. this.distance = distance;
  49727. this.mesh = mesh;
  49728. }
  49729. return MeshLODLevel;
  49730. }());
  49731. Internals.MeshLODLevel = MeshLODLevel;
  49732. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49733. })(BABYLON || (BABYLON = {}));
  49734. //# sourceMappingURL=babylon.meshLODLevel.js.map
  49735. var BABYLON;
  49736. (function (BABYLON) {
  49737. var RawTexture = (function (_super) {
  49738. __extends(RawTexture, _super);
  49739. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  49740. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49741. if (invertY === void 0) { invertY = false; }
  49742. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49743. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  49744. _this.format = format;
  49745. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  49746. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49747. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49748. return _this;
  49749. }
  49750. RawTexture.prototype.update = function (data) {
  49751. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  49752. };
  49753. // Statics
  49754. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49755. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49756. if (invertY === void 0) { invertY = false; }
  49757. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49758. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  49759. };
  49760. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49761. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49762. if (invertY === void 0) { invertY = false; }
  49763. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49764. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49765. };
  49766. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49767. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49768. if (invertY === void 0) { invertY = false; }
  49769. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49770. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49771. };
  49772. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49773. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49774. if (invertY === void 0) { invertY = false; }
  49775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49776. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  49777. };
  49778. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49779. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49780. if (invertY === void 0) { invertY = false; }
  49781. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49782. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  49783. };
  49784. return RawTexture;
  49785. }(BABYLON.Texture));
  49786. BABYLON.RawTexture = RawTexture;
  49787. })(BABYLON || (BABYLON = {}));
  49788. //# sourceMappingURL=babylon.rawTexture.js.map
  49789. /// <reference path="..\Math\babylon.math.ts" />
  49790. var BABYLON;
  49791. (function (BABYLON) {
  49792. var IndexedVector2 = (function (_super) {
  49793. __extends(IndexedVector2, _super);
  49794. function IndexedVector2(original, index) {
  49795. var _this = _super.call(this, original.x, original.y) || this;
  49796. _this.index = index;
  49797. return _this;
  49798. }
  49799. return IndexedVector2;
  49800. }(BABYLON.Vector2));
  49801. var PolygonPoints = (function () {
  49802. function PolygonPoints() {
  49803. this.elements = new Array();
  49804. }
  49805. PolygonPoints.prototype.add = function (originalPoints) {
  49806. var _this = this;
  49807. var result = new Array();
  49808. originalPoints.forEach(function (point) {
  49809. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  49810. var newPoint = new IndexedVector2(point, _this.elements.length);
  49811. result.push(newPoint);
  49812. _this.elements.push(newPoint);
  49813. }
  49814. });
  49815. return result;
  49816. };
  49817. PolygonPoints.prototype.computeBounds = function () {
  49818. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49819. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49820. this.elements.forEach(function (point) {
  49821. // x
  49822. if (point.x < lmin.x) {
  49823. lmin.x = point.x;
  49824. }
  49825. else if (point.x > lmax.x) {
  49826. lmax.x = point.x;
  49827. }
  49828. // y
  49829. if (point.y < lmin.y) {
  49830. lmin.y = point.y;
  49831. }
  49832. else if (point.y > lmax.y) {
  49833. lmax.y = point.y;
  49834. }
  49835. });
  49836. return {
  49837. min: lmin,
  49838. max: lmax,
  49839. width: lmax.x - lmin.x,
  49840. height: lmax.y - lmin.y
  49841. };
  49842. };
  49843. return PolygonPoints;
  49844. }());
  49845. var Polygon = (function () {
  49846. function Polygon() {
  49847. }
  49848. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  49849. return [
  49850. new BABYLON.Vector2(xmin, ymin),
  49851. new BABYLON.Vector2(xmax, ymin),
  49852. new BABYLON.Vector2(xmax, ymax),
  49853. new BABYLON.Vector2(xmin, ymax)
  49854. ];
  49855. };
  49856. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  49857. if (cx === void 0) { cx = 0; }
  49858. if (cy === void 0) { cy = 0; }
  49859. if (numberOfSides === void 0) { numberOfSides = 32; }
  49860. var result = new Array();
  49861. var angle = 0;
  49862. var increment = (Math.PI * 2) / numberOfSides;
  49863. for (var i = 0; i < numberOfSides; i++) {
  49864. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  49865. angle -= increment;
  49866. }
  49867. return result;
  49868. };
  49869. Polygon.Parse = function (input) {
  49870. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  49871. var i, result = [];
  49872. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  49873. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  49874. }
  49875. return result;
  49876. };
  49877. Polygon.StartingAt = function (x, y) {
  49878. return BABYLON.Path2.StartingAt(x, y);
  49879. };
  49880. return Polygon;
  49881. }());
  49882. BABYLON.Polygon = Polygon;
  49883. var PolygonMeshBuilder = (function () {
  49884. function PolygonMeshBuilder(name, contours, scene) {
  49885. this._points = new PolygonPoints();
  49886. this._outlinepoints = new PolygonPoints();
  49887. this._holes = [];
  49888. this._epoints = new Array();
  49889. this._eholes = new Array();
  49890. this._name = name;
  49891. this._scene = scene;
  49892. var points;
  49893. if (contours instanceof BABYLON.Path2) {
  49894. points = contours.getPoints();
  49895. }
  49896. else {
  49897. points = contours;
  49898. }
  49899. this._addToepoint(points);
  49900. this._points.add(points);
  49901. this._outlinepoints.add(points);
  49902. }
  49903. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  49904. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  49905. var p = points_1[_i];
  49906. this._epoints.push(p.x, p.y);
  49907. }
  49908. };
  49909. PolygonMeshBuilder.prototype.addHole = function (hole) {
  49910. this._points.add(hole);
  49911. var holepoints = new PolygonPoints();
  49912. holepoints.add(hole);
  49913. this._holes.push(holepoints);
  49914. this._eholes.push(this._epoints.length / 2);
  49915. this._addToepoint(hole);
  49916. return this;
  49917. };
  49918. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  49919. var _this = this;
  49920. if (updatable === void 0) { updatable = false; }
  49921. var result = new BABYLON.Mesh(this._name, this._scene);
  49922. var normals = [];
  49923. var positions = [];
  49924. var uvs = [];
  49925. var bounds = this._points.computeBounds();
  49926. this._points.elements.forEach(function (p) {
  49927. normals.push(0, 1.0, 0);
  49928. positions.push(p.x, 0, p.y);
  49929. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  49930. });
  49931. var indices = [];
  49932. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  49933. for (var i = 0; i < res.length; i++) {
  49934. indices.push(res[i]);
  49935. }
  49936. if (depth > 0) {
  49937. var positionscount = (positions.length / 3); //get the current pointcount
  49938. this._points.elements.forEach(function (p) {
  49939. normals.push(0, -1.0, 0);
  49940. positions.push(p.x, -depth, p.y);
  49941. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  49942. });
  49943. var totalCount = indices.length;
  49944. for (var i = 0; i < totalCount; i += 3) {
  49945. var i0 = indices[i + 0];
  49946. var i1 = indices[i + 1];
  49947. var i2 = indices[i + 2];
  49948. indices.push(i2 + positionscount);
  49949. indices.push(i1 + positionscount);
  49950. indices.push(i0 + positionscount);
  49951. }
  49952. //Add the sides
  49953. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  49954. this._holes.forEach(function (hole) {
  49955. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  49956. });
  49957. }
  49958. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  49959. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  49960. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  49961. result.setIndices(indices);
  49962. return result;
  49963. };
  49964. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  49965. var StartIndex = positions.length / 3;
  49966. var ulength = 0;
  49967. for (var i = 0; i < points.elements.length; i++) {
  49968. var p = points.elements[i];
  49969. var p1;
  49970. if ((i + 1) > points.elements.length - 1) {
  49971. p1 = points.elements[0];
  49972. }
  49973. else {
  49974. p1 = points.elements[i + 1];
  49975. }
  49976. positions.push(p.x, 0, p.y);
  49977. positions.push(p.x, -depth, p.y);
  49978. positions.push(p1.x, 0, p1.y);
  49979. positions.push(p1.x, -depth, p1.y);
  49980. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  49981. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  49982. var v3 = v2.subtract(v1);
  49983. var v4 = new BABYLON.Vector3(0, 1, 0);
  49984. var vn = BABYLON.Vector3.Cross(v3, v4);
  49985. vn = vn.normalize();
  49986. uvs.push(ulength / bounds.width, 0);
  49987. uvs.push(ulength / bounds.width, 1);
  49988. ulength += v3.length();
  49989. uvs.push((ulength / bounds.width), 0);
  49990. uvs.push((ulength / bounds.width), 1);
  49991. if (!flip) {
  49992. normals.push(-vn.x, -vn.y, -vn.z);
  49993. normals.push(-vn.x, -vn.y, -vn.z);
  49994. normals.push(-vn.x, -vn.y, -vn.z);
  49995. normals.push(-vn.x, -vn.y, -vn.z);
  49996. indices.push(StartIndex);
  49997. indices.push(StartIndex + 1);
  49998. indices.push(StartIndex + 2);
  49999. indices.push(StartIndex + 1);
  50000. indices.push(StartIndex + 3);
  50001. indices.push(StartIndex + 2);
  50002. }
  50003. else {
  50004. normals.push(vn.x, vn.y, vn.z);
  50005. normals.push(vn.x, vn.y, vn.z);
  50006. normals.push(vn.x, vn.y, vn.z);
  50007. normals.push(vn.x, vn.y, vn.z);
  50008. indices.push(StartIndex);
  50009. indices.push(StartIndex + 2);
  50010. indices.push(StartIndex + 1);
  50011. indices.push(StartIndex + 1);
  50012. indices.push(StartIndex + 2);
  50013. indices.push(StartIndex + 3);
  50014. }
  50015. StartIndex += 4;
  50016. }
  50017. ;
  50018. };
  50019. return PolygonMeshBuilder;
  50020. }());
  50021. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  50022. })(BABYLON || (BABYLON = {}));
  50023. //# sourceMappingURL=babylon.polygonMesh.js.map
  50024. var BABYLON;
  50025. (function (BABYLON) {
  50026. var Octree = (function () {
  50027. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  50028. if (maxDepth === void 0) { maxDepth = 2; }
  50029. this.maxDepth = maxDepth;
  50030. this.dynamicContent = new Array();
  50031. this._maxBlockCapacity = maxBlockCapacity || 64;
  50032. this._selectionContent = new BABYLON.SmartArray(1024);
  50033. this._creationFunc = creationFunc;
  50034. }
  50035. // Methods
  50036. Octree.prototype.update = function (worldMin, worldMax, entries) {
  50037. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  50038. };
  50039. Octree.prototype.addMesh = function (entry) {
  50040. for (var index = 0; index < this.blocks.length; index++) {
  50041. var block = this.blocks[index];
  50042. block.addEntry(entry);
  50043. }
  50044. };
  50045. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  50046. this._selectionContent.reset();
  50047. for (var index = 0; index < this.blocks.length; index++) {
  50048. var block = this.blocks[index];
  50049. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  50050. }
  50051. if (allowDuplicate) {
  50052. this._selectionContent.concat(this.dynamicContent);
  50053. }
  50054. else {
  50055. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50056. }
  50057. return this._selectionContent;
  50058. };
  50059. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  50060. this._selectionContent.reset();
  50061. for (var index = 0; index < this.blocks.length; index++) {
  50062. var block = this.blocks[index];
  50063. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  50064. }
  50065. if (allowDuplicate) {
  50066. this._selectionContent.concat(this.dynamicContent);
  50067. }
  50068. else {
  50069. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50070. }
  50071. return this._selectionContent;
  50072. };
  50073. Octree.prototype.intersectsRay = function (ray) {
  50074. this._selectionContent.reset();
  50075. for (var index = 0; index < this.blocks.length; index++) {
  50076. var block = this.blocks[index];
  50077. block.intersectsRay(ray, this._selectionContent);
  50078. }
  50079. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50080. return this._selectionContent;
  50081. };
  50082. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  50083. target.blocks = new Array();
  50084. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  50085. // Segmenting space
  50086. for (var x = 0; x < 2; x++) {
  50087. for (var y = 0; y < 2; y++) {
  50088. for (var z = 0; z < 2; z++) {
  50089. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  50090. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  50091. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  50092. block.addEntries(entries);
  50093. target.blocks.push(block);
  50094. }
  50095. }
  50096. }
  50097. };
  50098. return Octree;
  50099. }());
  50100. Octree.CreationFuncForMeshes = function (entry, block) {
  50101. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50102. block.entries.push(entry);
  50103. }
  50104. };
  50105. Octree.CreationFuncForSubMeshes = function (entry, block) {
  50106. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50107. block.entries.push(entry);
  50108. }
  50109. };
  50110. BABYLON.Octree = Octree;
  50111. })(BABYLON || (BABYLON = {}));
  50112. //# sourceMappingURL=babylon.octree.js.map
  50113. var BABYLON;
  50114. (function (BABYLON) {
  50115. var OctreeBlock = (function () {
  50116. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  50117. this.entries = new Array();
  50118. this._boundingVectors = new Array();
  50119. this._capacity = capacity;
  50120. this._depth = depth;
  50121. this._maxDepth = maxDepth;
  50122. this._creationFunc = creationFunc;
  50123. this._minPoint = minPoint;
  50124. this._maxPoint = maxPoint;
  50125. this._boundingVectors.push(minPoint.clone());
  50126. this._boundingVectors.push(maxPoint.clone());
  50127. this._boundingVectors.push(minPoint.clone());
  50128. this._boundingVectors[2].x = maxPoint.x;
  50129. this._boundingVectors.push(minPoint.clone());
  50130. this._boundingVectors[3].y = maxPoint.y;
  50131. this._boundingVectors.push(minPoint.clone());
  50132. this._boundingVectors[4].z = maxPoint.z;
  50133. this._boundingVectors.push(maxPoint.clone());
  50134. this._boundingVectors[5].z = minPoint.z;
  50135. this._boundingVectors.push(maxPoint.clone());
  50136. this._boundingVectors[6].x = minPoint.x;
  50137. this._boundingVectors.push(maxPoint.clone());
  50138. this._boundingVectors[7].y = minPoint.y;
  50139. }
  50140. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  50141. // Property
  50142. get: function () {
  50143. return this._capacity;
  50144. },
  50145. enumerable: true,
  50146. configurable: true
  50147. });
  50148. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  50149. get: function () {
  50150. return this._minPoint;
  50151. },
  50152. enumerable: true,
  50153. configurable: true
  50154. });
  50155. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  50156. get: function () {
  50157. return this._maxPoint;
  50158. },
  50159. enumerable: true,
  50160. configurable: true
  50161. });
  50162. // Methods
  50163. OctreeBlock.prototype.addEntry = function (entry) {
  50164. if (this.blocks) {
  50165. for (var index = 0; index < this.blocks.length; index++) {
  50166. var block = this.blocks[index];
  50167. block.addEntry(entry);
  50168. }
  50169. return;
  50170. }
  50171. this._creationFunc(entry, this);
  50172. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  50173. this.createInnerBlocks();
  50174. }
  50175. };
  50176. OctreeBlock.prototype.addEntries = function (entries) {
  50177. for (var index = 0; index < entries.length; index++) {
  50178. var mesh = entries[index];
  50179. this.addEntry(mesh);
  50180. }
  50181. };
  50182. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  50183. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  50184. if (this.blocks) {
  50185. for (var index = 0; index < this.blocks.length; index++) {
  50186. var block = this.blocks[index];
  50187. block.select(frustumPlanes, selection, allowDuplicate);
  50188. }
  50189. return;
  50190. }
  50191. if (allowDuplicate) {
  50192. selection.concat(this.entries);
  50193. }
  50194. else {
  50195. selection.concatWithNoDuplicate(this.entries);
  50196. }
  50197. }
  50198. };
  50199. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  50200. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  50201. if (this.blocks) {
  50202. for (var index = 0; index < this.blocks.length; index++) {
  50203. var block = this.blocks[index];
  50204. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  50205. }
  50206. return;
  50207. }
  50208. if (allowDuplicate) {
  50209. selection.concat(this.entries);
  50210. }
  50211. else {
  50212. selection.concatWithNoDuplicate(this.entries);
  50213. }
  50214. }
  50215. };
  50216. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  50217. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  50218. if (this.blocks) {
  50219. for (var index = 0; index < this.blocks.length; index++) {
  50220. var block = this.blocks[index];
  50221. block.intersectsRay(ray, selection);
  50222. }
  50223. return;
  50224. }
  50225. selection.concatWithNoDuplicate(this.entries);
  50226. }
  50227. };
  50228. OctreeBlock.prototype.createInnerBlocks = function () {
  50229. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  50230. };
  50231. return OctreeBlock;
  50232. }());
  50233. BABYLON.OctreeBlock = OctreeBlock;
  50234. })(BABYLON || (BABYLON = {}));
  50235. //# sourceMappingURL=babylon.octreeBlock.js.map
  50236. var BABYLON;
  50237. (function (BABYLON) {
  50238. var BlurPostProcess = (function (_super) {
  50239. __extends(BlurPostProcess, _super);
  50240. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  50241. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50242. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  50243. _this.direction = direction;
  50244. _this.blurWidth = blurWidth;
  50245. _this.onApplyObservable.add(function (effect) {
  50246. effect.setFloat2("screenSize", _this.width, _this.height);
  50247. effect.setVector2("direction", _this.direction);
  50248. effect.setFloat("blurWidth", _this.blurWidth);
  50249. });
  50250. return _this;
  50251. }
  50252. return BlurPostProcess;
  50253. }(BABYLON.PostProcess));
  50254. BABYLON.BlurPostProcess = BlurPostProcess;
  50255. })(BABYLON || (BABYLON = {}));
  50256. //# sourceMappingURL=babylon.blurPostProcess.js.map
  50257. var BABYLON;
  50258. (function (BABYLON) {
  50259. var RefractionPostProcess = (function (_super) {
  50260. __extends(RefractionPostProcess, _super);
  50261. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  50262. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  50263. _this.color = color;
  50264. _this.depth = depth;
  50265. _this.colorLevel = colorLevel;
  50266. _this.onActivateObservable.add(function (cam) {
  50267. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  50268. });
  50269. _this.onApplyObservable.add(function (effect) {
  50270. effect.setColor3("baseColor", _this.color);
  50271. effect.setFloat("depth", _this.depth);
  50272. effect.setFloat("colorLevel", _this.colorLevel);
  50273. effect.setTexture("refractionSampler", _this._refRexture);
  50274. });
  50275. return _this;
  50276. }
  50277. // Methods
  50278. RefractionPostProcess.prototype.dispose = function (camera) {
  50279. if (this._refRexture) {
  50280. this._refRexture.dispose();
  50281. }
  50282. _super.prototype.dispose.call(this, camera);
  50283. };
  50284. return RefractionPostProcess;
  50285. }(BABYLON.PostProcess));
  50286. BABYLON.RefractionPostProcess = RefractionPostProcess;
  50287. })(BABYLON || (BABYLON = {}));
  50288. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  50289. var BABYLON;
  50290. (function (BABYLON) {
  50291. var BlackAndWhitePostProcess = (function (_super) {
  50292. __extends(BlackAndWhitePostProcess, _super);
  50293. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  50294. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  50295. }
  50296. return BlackAndWhitePostProcess;
  50297. }(BABYLON.PostProcess));
  50298. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  50299. })(BABYLON || (BABYLON = {}));
  50300. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  50301. var BABYLON;
  50302. (function (BABYLON) {
  50303. var ConvolutionPostProcess = (function (_super) {
  50304. __extends(ConvolutionPostProcess, _super);
  50305. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  50306. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  50307. _this.kernel = kernel;
  50308. _this.onApply = function (effect) {
  50309. effect.setFloat2("screenSize", _this.width, _this.height);
  50310. effect.setArray("kernel", _this.kernel);
  50311. };
  50312. return _this;
  50313. }
  50314. return ConvolutionPostProcess;
  50315. }(BABYLON.PostProcess));
  50316. // Statics
  50317. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  50318. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  50319. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  50320. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  50321. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  50322. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  50323. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  50324. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  50325. })(BABYLON || (BABYLON = {}));
  50326. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  50327. var BABYLON;
  50328. (function (BABYLON) {
  50329. var FilterPostProcess = (function (_super) {
  50330. __extends(FilterPostProcess, _super);
  50331. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  50332. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  50333. _this.kernelMatrix = kernelMatrix;
  50334. _this.onApply = function (effect) {
  50335. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  50336. };
  50337. return _this;
  50338. }
  50339. return FilterPostProcess;
  50340. }(BABYLON.PostProcess));
  50341. BABYLON.FilterPostProcess = FilterPostProcess;
  50342. })(BABYLON || (BABYLON = {}));
  50343. //# sourceMappingURL=babylon.filterPostProcess.js.map
  50344. var BABYLON;
  50345. (function (BABYLON) {
  50346. var FxaaPostProcess = (function (_super) {
  50347. __extends(FxaaPostProcess, _super);
  50348. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50349. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  50350. _this.onSizeChangedObservable.add(function () {
  50351. _this.texelWidth = 1.0 / _this.width;
  50352. _this.texelHeight = 1.0 / _this.height;
  50353. });
  50354. _this.onApplyObservable.add(function (effect) {
  50355. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  50356. });
  50357. return _this;
  50358. }
  50359. return FxaaPostProcess;
  50360. }(BABYLON.PostProcess));
  50361. BABYLON.FxaaPostProcess = FxaaPostProcess;
  50362. })(BABYLON || (BABYLON = {}));
  50363. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  50364. var BABYLON;
  50365. (function (BABYLON) {
  50366. var StereoscopicInterlacePostProcess = (function (_super) {
  50367. __extends(StereoscopicInterlacePostProcess, _super);
  50368. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  50369. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  50370. _this._passedProcess = rigCameras[0]._rigPostProcess;
  50371. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  50372. _this.onSizeChangedObservable.add(function () {
  50373. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  50374. });
  50375. _this.onApplyObservable.add(function (effect) {
  50376. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  50377. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  50378. });
  50379. return _this;
  50380. }
  50381. return StereoscopicInterlacePostProcess;
  50382. }(BABYLON.PostProcess));
  50383. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  50384. })(BABYLON || (BABYLON = {}));
  50385. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  50386. var BABYLON;
  50387. (function (BABYLON) {
  50388. var LensFlare = (function () {
  50389. function LensFlare(size, position, color, imgUrl, system) {
  50390. this.size = size;
  50391. this.position = position;
  50392. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  50393. this.dispose = function () {
  50394. if (this.texture) {
  50395. this.texture.dispose();
  50396. }
  50397. // Remove from scene
  50398. var index = this._system.lensFlares.indexOf(this);
  50399. this._system.lensFlares.splice(index, 1);
  50400. };
  50401. this.color = color || new BABYLON.Color3(1, 1, 1);
  50402. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  50403. this._system = system;
  50404. system.lensFlares.push(this);
  50405. }
  50406. return LensFlare;
  50407. }());
  50408. BABYLON.LensFlare = LensFlare;
  50409. })(BABYLON || (BABYLON = {}));
  50410. //# sourceMappingURL=babylon.lensFlare.js.map
  50411. var BABYLON;
  50412. (function (BABYLON) {
  50413. var LensFlareSystem = (function () {
  50414. function LensFlareSystem(name, emitter, scene) {
  50415. this.name = name;
  50416. this.lensFlares = new Array();
  50417. this.borderLimit = 300;
  50418. this.viewportBorder = 0;
  50419. this.layerMask = 0x0FFFFFFF;
  50420. this._vertexBuffers = {};
  50421. this._isEnabled = true;
  50422. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50423. this._emitter = emitter;
  50424. this.id = name;
  50425. scene.lensFlareSystems.push(this);
  50426. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  50427. var engine = scene.getEngine();
  50428. // VBO
  50429. var vertices = [];
  50430. vertices.push(1, 1);
  50431. vertices.push(-1, 1);
  50432. vertices.push(-1, -1);
  50433. vertices.push(1, -1);
  50434. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  50435. // Indices
  50436. var indices = [];
  50437. indices.push(0);
  50438. indices.push(1);
  50439. indices.push(2);
  50440. indices.push(0);
  50441. indices.push(2);
  50442. indices.push(3);
  50443. this._indexBuffer = engine.createIndexBuffer(indices);
  50444. // Effects
  50445. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  50446. }
  50447. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  50448. get: function () {
  50449. return this._isEnabled;
  50450. },
  50451. set: function (value) {
  50452. this._isEnabled = value;
  50453. },
  50454. enumerable: true,
  50455. configurable: true
  50456. });
  50457. LensFlareSystem.prototype.getScene = function () {
  50458. return this._scene;
  50459. };
  50460. LensFlareSystem.prototype.getEmitter = function () {
  50461. return this._emitter;
  50462. };
  50463. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  50464. this._emitter = newEmitter;
  50465. };
  50466. LensFlareSystem.prototype.getEmitterPosition = function () {
  50467. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  50468. };
  50469. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  50470. var position = this.getEmitterPosition();
  50471. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  50472. this._positionX = position.x;
  50473. this._positionY = position.y;
  50474. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  50475. if (this.viewportBorder > 0) {
  50476. globalViewport.x -= this.viewportBorder;
  50477. globalViewport.y -= this.viewportBorder;
  50478. globalViewport.width += this.viewportBorder * 2;
  50479. globalViewport.height += this.viewportBorder * 2;
  50480. position.x += this.viewportBorder;
  50481. position.y += this.viewportBorder;
  50482. this._positionX += this.viewportBorder;
  50483. this._positionY += this.viewportBorder;
  50484. }
  50485. if (position.z > 0) {
  50486. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  50487. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  50488. return true;
  50489. }
  50490. return true;
  50491. }
  50492. return false;
  50493. };
  50494. LensFlareSystem.prototype._isVisible = function () {
  50495. if (!this._isEnabled) {
  50496. return false;
  50497. }
  50498. var emitterPosition = this.getEmitterPosition();
  50499. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  50500. var distance = direction.length();
  50501. direction.normalize();
  50502. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  50503. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  50504. return !pickInfo.hit || pickInfo.distance > distance;
  50505. };
  50506. LensFlareSystem.prototype.render = function () {
  50507. if (!this._effect.isReady())
  50508. return false;
  50509. var engine = this._scene.getEngine();
  50510. var viewport = this._scene.activeCamera.viewport;
  50511. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  50512. // Position
  50513. if (!this.computeEffectivePosition(globalViewport)) {
  50514. return false;
  50515. }
  50516. // Visibility
  50517. if (!this._isVisible()) {
  50518. return false;
  50519. }
  50520. // Intensity
  50521. var awayX;
  50522. var awayY;
  50523. if (this._positionX < this.borderLimit + globalViewport.x) {
  50524. awayX = this.borderLimit + globalViewport.x - this._positionX;
  50525. }
  50526. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  50527. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  50528. }
  50529. else {
  50530. awayX = 0;
  50531. }
  50532. if (this._positionY < this.borderLimit + globalViewport.y) {
  50533. awayY = this.borderLimit + globalViewport.y - this._positionY;
  50534. }
  50535. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  50536. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  50537. }
  50538. else {
  50539. awayY = 0;
  50540. }
  50541. var away = (awayX > awayY) ? awayX : awayY;
  50542. away -= this.viewportBorder;
  50543. if (away > this.borderLimit) {
  50544. away = this.borderLimit;
  50545. }
  50546. var intensity = 1.0 - (away / this.borderLimit);
  50547. if (intensity < 0) {
  50548. return false;
  50549. }
  50550. if (intensity > 1.0) {
  50551. intensity = 1.0;
  50552. }
  50553. if (this.viewportBorder > 0) {
  50554. globalViewport.x += this.viewportBorder;
  50555. globalViewport.y += this.viewportBorder;
  50556. globalViewport.width -= this.viewportBorder * 2;
  50557. globalViewport.height -= this.viewportBorder * 2;
  50558. this._positionX -= this.viewportBorder;
  50559. this._positionY -= this.viewportBorder;
  50560. }
  50561. // Position
  50562. var centerX = globalViewport.x + globalViewport.width / 2;
  50563. var centerY = globalViewport.y + globalViewport.height / 2;
  50564. var distX = centerX - this._positionX;
  50565. var distY = centerY - this._positionY;
  50566. // Effects
  50567. engine.enableEffect(this._effect);
  50568. engine.setState(false);
  50569. engine.setDepthBuffer(false);
  50570. // VBOs
  50571. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50572. // Flares
  50573. for (var index = 0; index < this.lensFlares.length; index++) {
  50574. var flare = this.lensFlares[index];
  50575. engine.setAlphaMode(flare.alphaMode);
  50576. var x = centerX - (distX * flare.position);
  50577. var y = centerY - (distY * flare.position);
  50578. var cw = flare.size;
  50579. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  50580. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  50581. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  50582. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  50583. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  50584. // Texture
  50585. this._effect.setTexture("textureSampler", flare.texture);
  50586. // Color
  50587. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  50588. // Draw order
  50589. engine.draw(true, 0, 6);
  50590. }
  50591. engine.setDepthBuffer(true);
  50592. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50593. return true;
  50594. };
  50595. LensFlareSystem.prototype.dispose = function () {
  50596. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50597. if (vertexBuffer) {
  50598. vertexBuffer.dispose();
  50599. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50600. }
  50601. if (this._indexBuffer) {
  50602. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50603. this._indexBuffer = null;
  50604. }
  50605. while (this.lensFlares.length) {
  50606. this.lensFlares[0].dispose();
  50607. }
  50608. // Remove from scene
  50609. var index = this._scene.lensFlareSystems.indexOf(this);
  50610. this._scene.lensFlareSystems.splice(index, 1);
  50611. };
  50612. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  50613. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  50614. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  50615. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  50616. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  50617. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  50618. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  50619. var parsedFlare = parsedLensFlareSystem.flares[index];
  50620. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  50621. }
  50622. return lensFlareSystem;
  50623. };
  50624. LensFlareSystem.prototype.serialize = function () {
  50625. var serializationObject = {};
  50626. serializationObject.id = this.id;
  50627. serializationObject.name = this.name;
  50628. serializationObject.emitterId = this.getEmitter().id;
  50629. serializationObject.borderLimit = this.borderLimit;
  50630. serializationObject.flares = [];
  50631. for (var index = 0; index < this.lensFlares.length; index++) {
  50632. var flare = this.lensFlares[index];
  50633. serializationObject.flares.push({
  50634. size: flare.size,
  50635. position: flare.position,
  50636. color: flare.color.asArray(),
  50637. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  50638. });
  50639. }
  50640. return serializationObject;
  50641. };
  50642. return LensFlareSystem;
  50643. }());
  50644. BABYLON.LensFlareSystem = LensFlareSystem;
  50645. })(BABYLON || (BABYLON = {}));
  50646. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  50647. /// <reference path="babylon.freeCamera.ts" />
  50648. var BABYLON;
  50649. (function (BABYLON) {
  50650. // We're mainly based on the logic defined into the FreeCamera code
  50651. var DeviceOrientationCamera = (function (_super) {
  50652. __extends(DeviceOrientationCamera, _super);
  50653. function DeviceOrientationCamera(name, position, scene) {
  50654. var _this = _super.call(this, name, position, scene) || this;
  50655. _this._quaternionCache = new BABYLON.Quaternion();
  50656. _this.inputs.addDeviceOrientation();
  50657. return _this;
  50658. }
  50659. DeviceOrientationCamera.prototype.getClassName = function () {
  50660. return "DeviceOrientationCamera";
  50661. };
  50662. DeviceOrientationCamera.prototype._checkInputs = function () {
  50663. _super.prototype._checkInputs.call(this);
  50664. this._quaternionCache.copyFrom(this.rotationQuaternion);
  50665. if (this._initialQuaternion) {
  50666. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  50667. }
  50668. };
  50669. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  50670. var _this = this;
  50671. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  50672. //can only work if this camera has a rotation quaternion already.
  50673. if (!this.rotationQuaternion)
  50674. return;
  50675. if (!this._initialQuaternion) {
  50676. this._initialQuaternion = new BABYLON.Quaternion();
  50677. }
  50678. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  50679. ['x', 'y', 'z'].forEach(function (axisName) {
  50680. if (!axis[axisName]) {
  50681. _this._initialQuaternion[axisName] = 0;
  50682. }
  50683. else {
  50684. _this._initialQuaternion[axisName] *= -1;
  50685. }
  50686. });
  50687. this._initialQuaternion.normalize();
  50688. //force rotation update
  50689. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  50690. };
  50691. return DeviceOrientationCamera;
  50692. }(BABYLON.FreeCamera));
  50693. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  50694. })(BABYLON || (BABYLON = {}));
  50695. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  50696. var BABYLON;
  50697. (function (BABYLON) {
  50698. var VRDeviceOrientationFreeCamera = (function (_super) {
  50699. __extends(VRDeviceOrientationFreeCamera, _super);
  50700. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  50701. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50702. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50703. var _this = _super.call(this, name, position, scene) || this;
  50704. vrCameraMetrics.compensateDistortion = compensateDistortion;
  50705. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  50706. return _this;
  50707. }
  50708. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  50709. return "VRDeviceOrientationFreeCamera";
  50710. };
  50711. return VRDeviceOrientationFreeCamera;
  50712. }(BABYLON.DeviceOrientationCamera));
  50713. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  50714. var VRDeviceOrientationGamepadCamera = (function (_super) {
  50715. __extends(VRDeviceOrientationGamepadCamera, _super);
  50716. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  50717. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50718. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50719. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  50720. _this.inputs.addGamepad();
  50721. return _this;
  50722. }
  50723. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  50724. return "VRDeviceOrientationGamepadCamera";
  50725. };
  50726. return VRDeviceOrientationGamepadCamera;
  50727. }(VRDeviceOrientationFreeCamera));
  50728. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  50729. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  50730. __extends(VRDeviceOrientationArcRotateCamera, _super);
  50731. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  50732. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50733. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50734. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  50735. vrCameraMetrics.compensateDistortion = compensateDistortion;
  50736. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  50737. _this.inputs.addVRDeviceOrientation();
  50738. return _this;
  50739. }
  50740. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  50741. return "VRDeviceOrientationArcRotateCamera";
  50742. };
  50743. return VRDeviceOrientationArcRotateCamera;
  50744. }(BABYLON.ArcRotateCamera));
  50745. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  50746. })(BABYLON || (BABYLON = {}));
  50747. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  50748. /// <reference path="babylon.touchCamera.ts" />
  50749. var BABYLON;
  50750. (function (BABYLON) {
  50751. // We're mainly based on the logic defined into the FreeCamera code
  50752. var UniversalCamera = (function (_super) {
  50753. __extends(UniversalCamera, _super);
  50754. //-- end properties for backward compatibility for inputs
  50755. function UniversalCamera(name, position, scene) {
  50756. var _this = _super.call(this, name, position, scene) || this;
  50757. _this.inputs.addGamepad();
  50758. return _this;
  50759. }
  50760. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  50761. //-- Begin properties for backward compatibility for inputs
  50762. get: function () {
  50763. var gamepad = this.inputs.attached["gamepad"];
  50764. if (gamepad)
  50765. return gamepad.gamepadAngularSensibility;
  50766. },
  50767. set: function (value) {
  50768. var gamepad = this.inputs.attached["gamepad"];
  50769. if (gamepad)
  50770. gamepad.gamepadAngularSensibility = value;
  50771. },
  50772. enumerable: true,
  50773. configurable: true
  50774. });
  50775. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  50776. get: function () {
  50777. var gamepad = this.inputs.attached["gamepad"];
  50778. if (gamepad)
  50779. return gamepad.gamepadMoveSensibility;
  50780. },
  50781. set: function (value) {
  50782. var gamepad = this.inputs.attached["gamepad"];
  50783. if (gamepad)
  50784. gamepad.gamepadMoveSensibility = value;
  50785. },
  50786. enumerable: true,
  50787. configurable: true
  50788. });
  50789. UniversalCamera.prototype.getClassName = function () {
  50790. return "UniversalCamera";
  50791. };
  50792. return UniversalCamera;
  50793. }(BABYLON.TouchCamera));
  50794. BABYLON.UniversalCamera = UniversalCamera;
  50795. })(BABYLON || (BABYLON = {}));
  50796. //# sourceMappingURL=babylon.universalCamera.js.map
  50797. var BABYLON;
  50798. (function (BABYLON) {
  50799. var Gamepads = (function () {
  50800. function Gamepads(ongamedpadconnected) {
  50801. var _this = this;
  50802. this.babylonGamepads = [];
  50803. this.oneGamepadConnected = false;
  50804. this.isMonitoring = false;
  50805. this.gamepadEventSupported = 'GamepadEvent' in window;
  50806. this.gamepadSupport = (navigator.getGamepads ||
  50807. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  50808. this._callbackGamepadConnected = ongamedpadconnected;
  50809. if (this.gamepadSupport) {
  50810. //first add already-connected gamepads
  50811. this._updateGamepadObjects();
  50812. if (this.babylonGamepads.length) {
  50813. this._startMonitoringGamepads();
  50814. }
  50815. // Checking if the gamepad connected event is supported (like in Firefox)
  50816. if (this.gamepadEventSupported) {
  50817. this._onGamepadConnectedEvent = function (evt) {
  50818. _this._onGamepadConnected(evt.gamepad);
  50819. };
  50820. this._onGamepadDisonnectedEvent = function (evt) {
  50821. _this._onGamepadDisconnected(evt);
  50822. };
  50823. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50824. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50825. }
  50826. else {
  50827. this._startMonitoringGamepads();
  50828. }
  50829. }
  50830. }
  50831. Gamepads.prototype.dispose = function () {
  50832. if (Gamepads.gamepadDOMInfo) {
  50833. document.body.removeChild(Gamepads.gamepadDOMInfo);
  50834. }
  50835. if (this._onGamepadConnectedEvent) {
  50836. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50837. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50838. this._onGamepadConnectedEvent = null;
  50839. this._onGamepadDisonnectedEvent = null;
  50840. }
  50841. };
  50842. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  50843. var newGamepad = this._addNewGamepad(gamepad);
  50844. if (this._callbackGamepadConnected)
  50845. this._callbackGamepadConnected(newGamepad);
  50846. this._startMonitoringGamepads();
  50847. };
  50848. Gamepads.prototype._addNewGamepad = function (gamepad) {
  50849. if (!this.oneGamepadConnected) {
  50850. this.oneGamepadConnected = true;
  50851. if (Gamepads.gamepadDOMInfo) {
  50852. document.body.removeChild(Gamepads.gamepadDOMInfo);
  50853. Gamepads.gamepadDOMInfo = null;
  50854. }
  50855. }
  50856. var newGamepad;
  50857. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  50858. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  50859. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  50860. }
  50861. else if (gamepad.pose) {
  50862. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  50863. }
  50864. else {
  50865. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  50866. }
  50867. this.babylonGamepads.push(newGamepad);
  50868. return newGamepad;
  50869. };
  50870. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  50871. // Remove the gamepad from the list of gamepads to monitor.
  50872. for (var i in this.babylonGamepads) {
  50873. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  50874. this.babylonGamepads.splice(+i, 1);
  50875. break;
  50876. }
  50877. }
  50878. // If no gamepads are left, stop the polling loop.
  50879. if (this.babylonGamepads.length == 0) {
  50880. this._stopMonitoringGamepads();
  50881. }
  50882. };
  50883. Gamepads.prototype._startMonitoringGamepads = function () {
  50884. if (!this.isMonitoring) {
  50885. this.isMonitoring = true;
  50886. this._checkGamepadsStatus();
  50887. }
  50888. };
  50889. Gamepads.prototype._stopMonitoringGamepads = function () {
  50890. this.isMonitoring = false;
  50891. };
  50892. Gamepads.prototype._checkGamepadsStatus = function () {
  50893. var _this = this;
  50894. // updating gamepad objects
  50895. this._updateGamepadObjects();
  50896. for (var i in this.babylonGamepads) {
  50897. this.babylonGamepads[i].update();
  50898. }
  50899. if (this.isMonitoring) {
  50900. if (window.requestAnimationFrame) {
  50901. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50902. }
  50903. else if (window.mozRequestAnimationFrame) {
  50904. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50905. }
  50906. else if (window.webkitRequestAnimationFrame) {
  50907. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50908. }
  50909. }
  50910. };
  50911. // This function is called only on Chrome, which does not yet support
  50912. // connection/disconnection events, but requires you to monitor
  50913. // an array for changes.
  50914. Gamepads.prototype._updateGamepadObjects = function () {
  50915. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  50916. for (var i = 0; i < gamepads.length; i++) {
  50917. if (gamepads[i]) {
  50918. if (!(gamepads[i].index in this.babylonGamepads)) {
  50919. var newGamepad = this._addNewGamepad(gamepads[i]);
  50920. if (this._callbackGamepadConnected) {
  50921. this._callbackGamepadConnected(newGamepad);
  50922. }
  50923. }
  50924. else {
  50925. this.babylonGamepads[i].browserGamepad = gamepads[i];
  50926. }
  50927. }
  50928. }
  50929. };
  50930. return Gamepads;
  50931. }());
  50932. BABYLON.Gamepads = Gamepads;
  50933. var StickValues = (function () {
  50934. function StickValues(x, y) {
  50935. this.x = x;
  50936. this.y = y;
  50937. }
  50938. return StickValues;
  50939. }());
  50940. BABYLON.StickValues = StickValues;
  50941. var Gamepad = (function () {
  50942. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  50943. if (leftStickX === void 0) { leftStickX = 0; }
  50944. if (leftStickY === void 0) { leftStickY = 1; }
  50945. if (rightStickX === void 0) { rightStickX = 2; }
  50946. if (rightStickY === void 0) { rightStickY = 3; }
  50947. this.id = id;
  50948. this.index = index;
  50949. this.browserGamepad = browserGamepad;
  50950. this.type = Gamepad.GAMEPAD;
  50951. this._leftStickAxisX = leftStickX;
  50952. this._leftStickAxisY = leftStickY;
  50953. this._rightStickAxisX = rightStickX;
  50954. this._rightStickAxisY = rightStickY;
  50955. if (this.browserGamepad.axes.length >= 2) {
  50956. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50957. }
  50958. if (this.browserGamepad.axes.length >= 4) {
  50959. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  50960. }
  50961. }
  50962. Gamepad.prototype.onleftstickchanged = function (callback) {
  50963. this._onleftstickchanged = callback;
  50964. };
  50965. Gamepad.prototype.onrightstickchanged = function (callback) {
  50966. this._onrightstickchanged = callback;
  50967. };
  50968. Object.defineProperty(Gamepad.prototype, "leftStick", {
  50969. get: function () {
  50970. return this._leftStick;
  50971. },
  50972. set: function (newValues) {
  50973. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  50974. this._onleftstickchanged(newValues);
  50975. }
  50976. this._leftStick = newValues;
  50977. },
  50978. enumerable: true,
  50979. configurable: true
  50980. });
  50981. Object.defineProperty(Gamepad.prototype, "rightStick", {
  50982. get: function () {
  50983. return this._rightStick;
  50984. },
  50985. set: function (newValues) {
  50986. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  50987. this._onrightstickchanged(newValues);
  50988. }
  50989. this._rightStick = newValues;
  50990. },
  50991. enumerable: true,
  50992. configurable: true
  50993. });
  50994. Gamepad.prototype.update = function () {
  50995. if (this._leftStick) {
  50996. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50997. }
  50998. if (this._rightStick) {
  50999. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51000. }
  51001. };
  51002. return Gamepad;
  51003. }());
  51004. Gamepad.GAMEPAD = 0;
  51005. Gamepad.GENERIC = 1;
  51006. Gamepad.XBOX = 2;
  51007. Gamepad.POSE_ENABLED = 3;
  51008. BABYLON.Gamepad = Gamepad;
  51009. var GenericPad = (function (_super) {
  51010. __extends(GenericPad, _super);
  51011. function GenericPad(id, index, gamepad) {
  51012. var _this = _super.call(this, id, index, gamepad) || this;
  51013. _this.id = id;
  51014. _this.index = index;
  51015. _this.gamepad = gamepad;
  51016. _this.type = Gamepad.GENERIC;
  51017. _this._buttons = new Array(gamepad.buttons.length);
  51018. return _this;
  51019. }
  51020. GenericPad.prototype.onbuttondown = function (callback) {
  51021. this._onbuttondown = callback;
  51022. };
  51023. GenericPad.prototype.onbuttonup = function (callback) {
  51024. this._onbuttonup = callback;
  51025. };
  51026. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51027. if (newValue !== currentValue) {
  51028. if (this._onbuttondown && newValue === 1) {
  51029. this._onbuttondown(buttonIndex);
  51030. }
  51031. if (this._onbuttonup && newValue === 0) {
  51032. this._onbuttonup(buttonIndex);
  51033. }
  51034. }
  51035. return newValue;
  51036. };
  51037. GenericPad.prototype.update = function () {
  51038. _super.prototype.update.call(this);
  51039. for (var index = 0; index < this._buttons.length; index++) {
  51040. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  51041. }
  51042. };
  51043. return GenericPad;
  51044. }(Gamepad));
  51045. BABYLON.GenericPad = GenericPad;
  51046. var Xbox360Button;
  51047. (function (Xbox360Button) {
  51048. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51049. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51050. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51051. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51052. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51053. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51054. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51055. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51056. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51057. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51058. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51059. var Xbox360Dpad;
  51060. (function (Xbox360Dpad) {
  51061. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51062. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51063. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51064. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51065. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51066. var Xbox360Pad = (function (_super) {
  51067. __extends(Xbox360Pad, _super);
  51068. function Xbox360Pad(id, index, gamepad, xboxOne) {
  51069. if (xboxOne === void 0) { xboxOne = false; }
  51070. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  51071. _this._leftTrigger = 0;
  51072. _this._rightTrigger = 0;
  51073. _this._buttonA = 0;
  51074. _this._buttonB = 0;
  51075. _this._buttonX = 0;
  51076. _this._buttonY = 0;
  51077. _this._buttonBack = 0;
  51078. _this._buttonStart = 0;
  51079. _this._buttonLB = 0;
  51080. _this._buttonRB = 0;
  51081. _this._buttonLeftStick = 0;
  51082. _this._buttonRightStick = 0;
  51083. _this._dPadUp = 0;
  51084. _this._dPadDown = 0;
  51085. _this._dPadLeft = 0;
  51086. _this._dPadRight = 0;
  51087. _this._isXboxOnePad = false;
  51088. _this.type = Gamepad.XBOX;
  51089. _this._isXboxOnePad = xboxOne;
  51090. return _this;
  51091. }
  51092. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51093. this._onlefttriggerchanged = callback;
  51094. };
  51095. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51096. this._onrighttriggerchanged = callback;
  51097. };
  51098. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51099. get: function () {
  51100. return this._leftTrigger;
  51101. },
  51102. set: function (newValue) {
  51103. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51104. this._onlefttriggerchanged(newValue);
  51105. }
  51106. this._leftTrigger = newValue;
  51107. },
  51108. enumerable: true,
  51109. configurable: true
  51110. });
  51111. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51112. get: function () {
  51113. return this._rightTrigger;
  51114. },
  51115. set: function (newValue) {
  51116. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51117. this._onrighttriggerchanged(newValue);
  51118. }
  51119. this._rightTrigger = newValue;
  51120. },
  51121. enumerable: true,
  51122. configurable: true
  51123. });
  51124. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51125. this._onbuttondown = callback;
  51126. };
  51127. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51128. this._onbuttonup = callback;
  51129. };
  51130. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51131. this._ondpaddown = callback;
  51132. };
  51133. Xbox360Pad.prototype.ondpadup = function (callback) {
  51134. this._ondpadup = callback;
  51135. };
  51136. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51137. if (newValue !== currentValue) {
  51138. if (this._onbuttondown && newValue === 1) {
  51139. this._onbuttondown(buttonType);
  51140. }
  51141. if (this._onbuttonup && newValue === 0) {
  51142. this._onbuttonup(buttonType);
  51143. }
  51144. }
  51145. return newValue;
  51146. };
  51147. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51148. if (newValue !== currentValue) {
  51149. if (this._ondpaddown && newValue === 1) {
  51150. this._ondpaddown(buttonType);
  51151. }
  51152. if (this._ondpadup && newValue === 0) {
  51153. this._ondpadup(buttonType);
  51154. }
  51155. }
  51156. return newValue;
  51157. };
  51158. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51159. get: function () {
  51160. return this._buttonA;
  51161. },
  51162. set: function (value) {
  51163. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51164. },
  51165. enumerable: true,
  51166. configurable: true
  51167. });
  51168. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51169. get: function () {
  51170. return this._buttonB;
  51171. },
  51172. set: function (value) {
  51173. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51174. },
  51175. enumerable: true,
  51176. configurable: true
  51177. });
  51178. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51179. get: function () {
  51180. return this._buttonX;
  51181. },
  51182. set: function (value) {
  51183. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51184. },
  51185. enumerable: true,
  51186. configurable: true
  51187. });
  51188. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51189. get: function () {
  51190. return this._buttonY;
  51191. },
  51192. set: function (value) {
  51193. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  51194. },
  51195. enumerable: true,
  51196. configurable: true
  51197. });
  51198. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  51199. get: function () {
  51200. return this._buttonStart;
  51201. },
  51202. set: function (value) {
  51203. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  51204. },
  51205. enumerable: true,
  51206. configurable: true
  51207. });
  51208. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  51209. get: function () {
  51210. return this._buttonBack;
  51211. },
  51212. set: function (value) {
  51213. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  51214. },
  51215. enumerable: true,
  51216. configurable: true
  51217. });
  51218. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  51219. get: function () {
  51220. return this._buttonLB;
  51221. },
  51222. set: function (value) {
  51223. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  51224. },
  51225. enumerable: true,
  51226. configurable: true
  51227. });
  51228. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  51229. get: function () {
  51230. return this._buttonRB;
  51231. },
  51232. set: function (value) {
  51233. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  51234. },
  51235. enumerable: true,
  51236. configurable: true
  51237. });
  51238. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  51239. get: function () {
  51240. return this._buttonLeftStick;
  51241. },
  51242. set: function (value) {
  51243. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  51244. },
  51245. enumerable: true,
  51246. configurable: true
  51247. });
  51248. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  51249. get: function () {
  51250. return this._buttonRightStick;
  51251. },
  51252. set: function (value) {
  51253. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  51254. },
  51255. enumerable: true,
  51256. configurable: true
  51257. });
  51258. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  51259. get: function () {
  51260. return this._dPadUp;
  51261. },
  51262. set: function (value) {
  51263. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  51264. },
  51265. enumerable: true,
  51266. configurable: true
  51267. });
  51268. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  51269. get: function () {
  51270. return this._dPadDown;
  51271. },
  51272. set: function (value) {
  51273. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  51274. },
  51275. enumerable: true,
  51276. configurable: true
  51277. });
  51278. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51279. get: function () {
  51280. return this._dPadLeft;
  51281. },
  51282. set: function (value) {
  51283. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51284. },
  51285. enumerable: true,
  51286. configurable: true
  51287. });
  51288. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51289. get: function () {
  51290. return this._dPadRight;
  51291. },
  51292. set: function (value) {
  51293. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51294. },
  51295. enumerable: true,
  51296. configurable: true
  51297. });
  51298. Xbox360Pad.prototype.update = function () {
  51299. _super.prototype.update.call(this);
  51300. if (this._isXboxOnePad) {
  51301. this.buttonA = this.browserGamepad.buttons[0].value;
  51302. this.buttonB = this.browserGamepad.buttons[1].value;
  51303. this.buttonX = this.browserGamepad.buttons[2].value;
  51304. this.buttonY = this.browserGamepad.buttons[3].value;
  51305. this.buttonLB = this.browserGamepad.buttons[4].value;
  51306. this.buttonRB = this.browserGamepad.buttons[5].value;
  51307. this.leftTrigger = this.browserGamepad.axes[2];
  51308. this.rightTrigger = this.browserGamepad.axes[5];
  51309. this.buttonBack = this.browserGamepad.buttons[9].value;
  51310. this.buttonStart = this.browserGamepad.buttons[8].value;
  51311. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  51312. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  51313. this.dPadUp = this.browserGamepad.buttons[11].value;
  51314. this.dPadDown = this.browserGamepad.buttons[12].value;
  51315. this.dPadLeft = this.browserGamepad.buttons[13].value;
  51316. this.dPadRight = this.browserGamepad.buttons[14].value;
  51317. }
  51318. else {
  51319. this.buttonA = this.browserGamepad.buttons[0].value;
  51320. this.buttonB = this.browserGamepad.buttons[1].value;
  51321. this.buttonX = this.browserGamepad.buttons[2].value;
  51322. this.buttonY = this.browserGamepad.buttons[3].value;
  51323. this.buttonLB = this.browserGamepad.buttons[4].value;
  51324. this.buttonRB = this.browserGamepad.buttons[5].value;
  51325. this.leftTrigger = this.browserGamepad.buttons[6].value;
  51326. this.rightTrigger = this.browserGamepad.buttons[7].value;
  51327. this.buttonBack = this.browserGamepad.buttons[8].value;
  51328. this.buttonStart = this.browserGamepad.buttons[9].value;
  51329. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  51330. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  51331. this.dPadUp = this.browserGamepad.buttons[12].value;
  51332. this.dPadDown = this.browserGamepad.buttons[13].value;
  51333. this.dPadLeft = this.browserGamepad.buttons[14].value;
  51334. this.dPadRight = this.browserGamepad.buttons[15].value;
  51335. }
  51336. };
  51337. return Xbox360Pad;
  51338. }(Gamepad));
  51339. BABYLON.Xbox360Pad = Xbox360Pad;
  51340. })(BABYLON || (BABYLON = {}));
  51341. //# sourceMappingURL=babylon.gamepads.js.map
  51342. var BABYLON;
  51343. (function (BABYLON) {
  51344. var PoseEnabledControllerType;
  51345. (function (PoseEnabledControllerType) {
  51346. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  51347. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  51348. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  51349. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  51350. var PoseEnabledControllerHelper = (function () {
  51351. function PoseEnabledControllerHelper() {
  51352. }
  51353. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  51354. // for now, only Oculus and Vive are supported
  51355. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  51356. return new OculusTouchController(vrGamepad);
  51357. }
  51358. else {
  51359. return new ViveController(vrGamepad);
  51360. }
  51361. };
  51362. return PoseEnabledControllerHelper;
  51363. }());
  51364. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  51365. var PoseEnabledController = (function (_super) {
  51366. __extends(PoseEnabledController, _super);
  51367. function PoseEnabledController(vrGamepad) {
  51368. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  51369. _this.vrGamepad = vrGamepad;
  51370. _this.deviceScaleFactor = 1;
  51371. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  51372. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  51373. _this.controllerType = PoseEnabledControllerType.GENERIC;
  51374. _this.position = BABYLON.Vector3.Zero();
  51375. _this.rotationQuaternion = new BABYLON.Quaternion();
  51376. _this.devicePosition = BABYLON.Vector3.Zero();
  51377. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  51378. _this._calculatedPosition = BABYLON.Vector3.Zero();
  51379. _this._calculatedRotation = new BABYLON.Quaternion();
  51380. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  51381. return _this;
  51382. }
  51383. PoseEnabledController.prototype.update = function () {
  51384. _super.prototype.update.call(this);
  51385. // update this device's offset position from the attached camera, if provided
  51386. //if (this._poseControlledCamera && this._poseControlledCamera.deviceScaleFactor) {
  51387. //this.position.copyFrom(this._poseControlledCamera.position);
  51388. //this.rotationQuaternion.copyFrom(this._poseControlledCamera.rotationQuaternion);
  51389. //this.deviceScaleFactor = this._poseControlledCamera.deviceScaleFactor;
  51390. //}
  51391. var pose = this.vrGamepad.pose;
  51392. this.updateFromDevice(pose);
  51393. if (this._mesh) {
  51394. this._mesh.position.copyFrom(this._calculatedPosition);
  51395. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  51396. }
  51397. };
  51398. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  51399. if (poseData) {
  51400. this.rawPose = poseData;
  51401. if (poseData.position) {
  51402. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  51403. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  51404. this.devicePosition.z *= -1;
  51405. }
  51406. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  51407. this._calculatedPosition.addInPlace(this.position);
  51408. }
  51409. if (poseData.orientation) {
  51410. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  51411. if (this._mesh) {
  51412. if (this._mesh.getScene().useRightHandedSystem) {
  51413. this.deviceRotationQuaternion.z *= -1;
  51414. this.deviceRotationQuaternion.w *= -1;
  51415. }
  51416. else {
  51417. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  51418. }
  51419. }
  51420. // if the camera is set, rotate to the camera's rotation
  51421. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  51422. }
  51423. }
  51424. };
  51425. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  51426. if (this._mesh) {
  51427. this._mesh.parent = undefined;
  51428. }
  51429. this._mesh = mesh;
  51430. if (this._poseControlledCamera) {
  51431. this._mesh.parent = this._poseControlledCamera;
  51432. }
  51433. if (!this._mesh.rotationQuaternion) {
  51434. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  51435. }
  51436. };
  51437. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  51438. this._poseControlledCamera = camera;
  51439. if (this._mesh) {
  51440. this._mesh.parent = this._poseControlledCamera;
  51441. }
  51442. };
  51443. PoseEnabledController.prototype.detachMesh = function () {
  51444. this._mesh = undefined;
  51445. };
  51446. return PoseEnabledController;
  51447. }(BABYLON.Gamepad));
  51448. BABYLON.PoseEnabledController = PoseEnabledController;
  51449. var WebVRController = (function (_super) {
  51450. __extends(WebVRController, _super);
  51451. function WebVRController(vrGamepad) {
  51452. var _this = _super.call(this, vrGamepad) || this;
  51453. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  51454. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  51455. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  51456. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  51457. _this.onPadStateChangedObservable = new BABYLON.Observable();
  51458. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  51459. _this.pad = { x: 0, y: 0 };
  51460. // avoid GC, store state in a tmp object
  51461. _this._changes = {
  51462. pressChanged: false,
  51463. touchChanged: false,
  51464. valueChanged: false,
  51465. changed: false
  51466. };
  51467. _this._buttons = new Array(vrGamepad.buttons.length);
  51468. _this.hand = vrGamepad.hand;
  51469. return _this;
  51470. }
  51471. WebVRController.prototype.onButtonStateChange = function (callback) {
  51472. this._onButtonStateChange = callback;
  51473. };
  51474. WebVRController.prototype.update = function () {
  51475. _super.prototype.update.call(this);
  51476. for (var index = 0; index < this._buttons.length; index++) {
  51477. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  51478. }
  51479. ;
  51480. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  51481. this.pad.x = this.leftStick.x;
  51482. this.pad.y = this.leftStick.y;
  51483. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  51484. }
  51485. };
  51486. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  51487. if (!currentState) {
  51488. this._buttons[buttonIndex] = {
  51489. pressed: newState.pressed,
  51490. touched: newState.touched,
  51491. value: newState.value
  51492. };
  51493. return;
  51494. }
  51495. this._checkChanges(newState, currentState);
  51496. if (this._changes.changed) {
  51497. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  51498. this.handleButtonChange(buttonIndex, newState, this._changes);
  51499. }
  51500. this._buttons[buttonIndex].pressed = newState.pressed;
  51501. this._buttons[buttonIndex].touched = newState.touched;
  51502. // oculus triggers are never 0, thou not touched.
  51503. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  51504. };
  51505. WebVRController.prototype._checkChanges = function (newState, currentState) {
  51506. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  51507. this._changes.touchChanged = newState.touched !== currentState.touched;
  51508. this._changes.valueChanged = newState.value !== currentState.value;
  51509. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  51510. return this._changes;
  51511. };
  51512. return WebVRController;
  51513. }(PoseEnabledController));
  51514. BABYLON.WebVRController = WebVRController;
  51515. var OculusTouchController = (function (_super) {
  51516. __extends(OculusTouchController, _super);
  51517. function OculusTouchController(vrGamepad) {
  51518. var _this = _super.call(this, vrGamepad) || this;
  51519. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  51520. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  51521. _this.controllerType = PoseEnabledControllerType.OCULUS;
  51522. return _this;
  51523. }
  51524. OculusTouchController.prototype.initControllerMesh = function (scene) {
  51525. var _this = this;
  51526. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  51527. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  51528. /*
  51529. Parent Mesh name: oculus_touch_left
  51530. - body
  51531. - trigger
  51532. - thumbstick
  51533. - grip
  51534. - button_y
  51535. - button_x
  51536. - button_enter
  51537. */
  51538. _this._defaultModel = newMeshes[1];
  51539. _this._hlButtonA = new BABYLON.HighlightLayer("hlButtonA", scene);
  51540. _this._hlButtonB = new BABYLON.HighlightLayer("hlButtonB", scene);
  51541. _this.attachToMesh(_this._defaultModel);
  51542. });
  51543. };
  51544. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  51545. // helper getters for left and right hand.
  51546. get: function () {
  51547. if (this.hand === 'right') {
  51548. return this.onMainButtonStateChangedObservable;
  51549. }
  51550. else {
  51551. throw new Error('No A button on left hand');
  51552. }
  51553. },
  51554. enumerable: true,
  51555. configurable: true
  51556. });
  51557. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  51558. get: function () {
  51559. if (this.hand === 'right') {
  51560. return this.onSecondaryButtonStateChangedObservable;
  51561. }
  51562. else {
  51563. throw new Error('No B button on left hand');
  51564. }
  51565. },
  51566. enumerable: true,
  51567. configurable: true
  51568. });
  51569. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  51570. get: function () {
  51571. if (this.hand === 'left') {
  51572. return this.onMainButtonStateChangedObservable;
  51573. }
  51574. else {
  51575. throw new Error('No X button on right hand');
  51576. }
  51577. },
  51578. enumerable: true,
  51579. configurable: true
  51580. });
  51581. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  51582. get: function () {
  51583. if (this.hand === 'left') {
  51584. return this.onSecondaryButtonStateChangedObservable;
  51585. }
  51586. else {
  51587. throw new Error('No Y button on right hand');
  51588. }
  51589. },
  51590. enumerable: true,
  51591. configurable: true
  51592. });
  51593. /*
  51594. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  51595. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  51596. 2) secondary trigger (same)
  51597. 3) A (right) X (left), touch, pressed = value
  51598. 4) B / Y
  51599. 5) thumb rest
  51600. */
  51601. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51602. var notifyObject = state; //{ state: state, changes: changes };
  51603. switch (buttonIdx) {
  51604. case 0:
  51605. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51606. return;
  51607. case 1:
  51608. if (this._defaultModel) {
  51609. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  51610. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  51611. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  51612. }
  51613. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51614. return;
  51615. case 2:
  51616. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  51617. return;
  51618. case 3:
  51619. if (this._defaultModel) {
  51620. if (notifyObject.pressed) {
  51621. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  51622. }
  51623. else {
  51624. (this._defaultModel.getChildren()[1]).position.y = 0;
  51625. }
  51626. if (notifyObject.touched) {
  51627. this._hlButtonA.addMesh(this._defaultModel.getChildren()[1], BABYLON.Color3.White());
  51628. }
  51629. else {
  51630. this._hlButtonA.removeMesh(this._defaultModel.getChildren()[1]);
  51631. }
  51632. }
  51633. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51634. return;
  51635. case 4:
  51636. if (this._defaultModel) {
  51637. if (notifyObject.pressed) {
  51638. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51639. }
  51640. else {
  51641. (this._defaultModel.getChildren()[2]).position.y = 0;
  51642. }
  51643. if (notifyObject.touched) {
  51644. this._hlButtonB.addMesh(this._defaultModel.getChildren()[2], BABYLON.Color3.White());
  51645. }
  51646. else {
  51647. this._hlButtonB.removeMesh(this._defaultModel.getChildren()[2]);
  51648. }
  51649. }
  51650. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51651. return;
  51652. case 5:
  51653. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  51654. return;
  51655. }
  51656. };
  51657. return OculusTouchController;
  51658. }(WebVRController));
  51659. BABYLON.OculusTouchController = OculusTouchController;
  51660. var ViveController = (function (_super) {
  51661. __extends(ViveController, _super);
  51662. function ViveController(vrGamepad) {
  51663. var _this = _super.call(this, vrGamepad) || this;
  51664. _this.controllerType = PoseEnabledControllerType.VIVE;
  51665. return _this;
  51666. }
  51667. ViveController.prototype.initControllerMesh = function (scene) {
  51668. var _this = this;
  51669. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  51670. /*
  51671. Parent Mesh name: ViveWand
  51672. - body
  51673. - r_gripper
  51674. - l_gripper
  51675. - menu_button
  51676. - system_button
  51677. - trackpad
  51678. - trigger
  51679. - LED
  51680. */
  51681. _this._defaultModel = newMeshes[1];
  51682. _this._hlButtonMenu = new BABYLON.HighlightLayer("hlButtonMenu", scene);
  51683. _this.attachToMesh(_this._defaultModel);
  51684. });
  51685. };
  51686. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  51687. get: function () {
  51688. return this.onMainButtonStateChangedObservable;
  51689. },
  51690. enumerable: true,
  51691. configurable: true
  51692. });
  51693. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  51694. get: function () {
  51695. return this.onMainButtonStateChangedObservable;
  51696. },
  51697. enumerable: true,
  51698. configurable: true
  51699. });
  51700. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  51701. get: function () {
  51702. return this.onSecondaryButtonStateChangedObservable;
  51703. },
  51704. enumerable: true,
  51705. configurable: true
  51706. });
  51707. /**
  51708. * Vive mapping:
  51709. * 0: touchpad
  51710. * 1: trigger
  51711. * 2: left AND right buttons
  51712. * 3: menu button
  51713. */
  51714. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51715. var notifyObject = state; //{ state: state, changes: changes };
  51716. switch (buttonIdx) {
  51717. case 0:
  51718. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51719. return;
  51720. case 1:
  51721. if (this._defaultModel) {
  51722. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  51723. }
  51724. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51725. return;
  51726. case 2:
  51727. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51728. return;
  51729. case 3:
  51730. if (this._defaultModel) {
  51731. if (notifyObject.pressed) {
  51732. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51733. this._hlButtonMenu.addMesh(this._defaultModel.getChildren()[2], BABYLON.Color3.White());
  51734. }
  51735. else {
  51736. (this._defaultModel.getChildren()[2]).position.y = 0;
  51737. this._hlButtonMenu.removeMesh(this._defaultModel.getChildren()[2]);
  51738. }
  51739. }
  51740. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51741. return;
  51742. }
  51743. };
  51744. return ViveController;
  51745. }(WebVRController));
  51746. BABYLON.ViveController = ViveController;
  51747. })(BABYLON || (BABYLON = {}));
  51748. //# sourceMappingURL=babylon.extendedGamepad.js.map
  51749. /// <reference path="babylon.universalCamera.ts" />
  51750. var BABYLON;
  51751. (function (BABYLON) {
  51752. // We're mainly based on the logic defined into the FreeCamera code
  51753. var GamepadCamera = (function (_super) {
  51754. __extends(GamepadCamera, _super);
  51755. //-- end properties for backward compatibility for inputs
  51756. function GamepadCamera(name, position, scene) {
  51757. return _super.call(this, name, position, scene) || this;
  51758. }
  51759. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  51760. //-- Begin properties for backward compatibility for inputs
  51761. get: function () {
  51762. var gamepad = this.inputs.attached["gamepad"];
  51763. if (gamepad)
  51764. return gamepad.gamepadAngularSensibility;
  51765. },
  51766. set: function (value) {
  51767. var gamepad = this.inputs.attached["gamepad"];
  51768. if (gamepad)
  51769. gamepad.gamepadAngularSensibility = value;
  51770. },
  51771. enumerable: true,
  51772. configurable: true
  51773. });
  51774. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  51775. get: function () {
  51776. var gamepad = this.inputs.attached["gamepad"];
  51777. if (gamepad)
  51778. return gamepad.gamepadMoveSensibility;
  51779. },
  51780. set: function (value) {
  51781. var gamepad = this.inputs.attached["gamepad"];
  51782. if (gamepad)
  51783. gamepad.gamepadMoveSensibility = value;
  51784. },
  51785. enumerable: true,
  51786. configurable: true
  51787. });
  51788. GamepadCamera.prototype.getClassName = function () {
  51789. return "GamepadCamera";
  51790. };
  51791. return GamepadCamera;
  51792. }(BABYLON.UniversalCamera));
  51793. BABYLON.GamepadCamera = GamepadCamera;
  51794. })(BABYLON || (BABYLON = {}));
  51795. //# sourceMappingURL=babylon.gamepadCamera.js.map
  51796. var BABYLON;
  51797. (function (BABYLON) {
  51798. var Analyser = (function () {
  51799. function Analyser(scene) {
  51800. this.SMOOTHING = 0.75;
  51801. this.FFT_SIZE = 512;
  51802. this.BARGRAPHAMPLITUDE = 256;
  51803. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51804. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51805. this._scene = scene;
  51806. this._audioEngine = BABYLON.Engine.audioEngine;
  51807. if (this._audioEngine.canUseWebAudio) {
  51808. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51809. this._webAudioAnalyser.minDecibels = -140;
  51810. this._webAudioAnalyser.maxDecibels = 0;
  51811. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51812. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51813. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51814. }
  51815. }
  51816. Analyser.prototype.getFrequencyBinCount = function () {
  51817. if (this._audioEngine.canUseWebAudio) {
  51818. return this._webAudioAnalyser.frequencyBinCount;
  51819. }
  51820. else {
  51821. return 0;
  51822. }
  51823. };
  51824. Analyser.prototype.getByteFrequencyData = function () {
  51825. if (this._audioEngine.canUseWebAudio) {
  51826. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51827. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51828. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51829. }
  51830. return this._byteFreqs;
  51831. };
  51832. Analyser.prototype.getByteTimeDomainData = function () {
  51833. if (this._audioEngine.canUseWebAudio) {
  51834. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51835. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51836. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51837. }
  51838. return this._byteTime;
  51839. };
  51840. Analyser.prototype.getFloatFrequencyData = function () {
  51841. if (this._audioEngine.canUseWebAudio) {
  51842. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51843. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51844. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51845. }
  51846. return this._floatFreqs;
  51847. };
  51848. Analyser.prototype.drawDebugCanvas = function () {
  51849. var _this = this;
  51850. if (this._audioEngine.canUseWebAudio) {
  51851. if (!this._debugCanvas) {
  51852. this._debugCanvas = document.createElement("canvas");
  51853. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51854. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51855. this._debugCanvas.style.position = "absolute";
  51856. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51857. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51858. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51859. document.body.appendChild(this._debugCanvas);
  51860. this._registerFunc = function () {
  51861. _this.drawDebugCanvas();
  51862. };
  51863. this._scene.registerBeforeRender(this._registerFunc);
  51864. }
  51865. if (this._registerFunc) {
  51866. var workingArray = this.getByteFrequencyData();
  51867. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51868. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51869. // Draw the frequency domain chart.
  51870. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51871. var value = workingArray[i];
  51872. var percent = value / this.BARGRAPHAMPLITUDE;
  51873. var height = this.DEBUGCANVASSIZE.height * percent;
  51874. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51875. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51876. var hue = i / this.getFrequencyBinCount() * 360;
  51877. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51878. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51879. }
  51880. }
  51881. }
  51882. };
  51883. Analyser.prototype.stopDebugCanvas = function () {
  51884. if (this._debugCanvas) {
  51885. this._scene.unregisterBeforeRender(this._registerFunc);
  51886. this._registerFunc = null;
  51887. document.body.removeChild(this._debugCanvas);
  51888. this._debugCanvas = null;
  51889. this._debugCanvasContext = null;
  51890. }
  51891. };
  51892. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51893. if (this._audioEngine.canUseWebAudio) {
  51894. inputAudioNode.connect(this._webAudioAnalyser);
  51895. this._webAudioAnalyser.connect(outputAudioNode);
  51896. }
  51897. };
  51898. Analyser.prototype.dispose = function () {
  51899. if (this._audioEngine.canUseWebAudio) {
  51900. this._webAudioAnalyser.disconnect();
  51901. }
  51902. };
  51903. return Analyser;
  51904. }());
  51905. BABYLON.Analyser = Analyser;
  51906. })(BABYLON || (BABYLON = {}));
  51907. //# sourceMappingURL=babylon.analyser.js.map
  51908. var BABYLON;
  51909. (function (BABYLON) {
  51910. var DepthRenderer = (function () {
  51911. function DepthRenderer(scene, type) {
  51912. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  51913. var _this = this;
  51914. this._viewMatrix = BABYLON.Matrix.Zero();
  51915. this._projectionMatrix = BABYLON.Matrix.Zero();
  51916. this._transformMatrix = BABYLON.Matrix.Zero();
  51917. this._worldViewProjection = BABYLON.Matrix.Zero();
  51918. this._scene = scene;
  51919. var engine = scene.getEngine();
  51920. // Render target
  51921. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  51922. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51923. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51924. this._depthMap.refreshRate = 1;
  51925. this._depthMap.renderParticles = false;
  51926. this._depthMap.renderList = null;
  51927. // set default depth value to 1.0 (far away)
  51928. this._depthMap.onClearObservable.add(function (engine) {
  51929. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51930. });
  51931. // Custom render function
  51932. var renderSubMesh = function (subMesh) {
  51933. var mesh = subMesh.getRenderingMesh();
  51934. var scene = _this._scene;
  51935. var engine = scene.getEngine();
  51936. // Culling
  51937. engine.setState(subMesh.getMaterial().backFaceCulling);
  51938. // Managing instances
  51939. var batch = mesh._getInstancesRenderList(subMesh._id);
  51940. if (batch.mustReturn) {
  51941. return;
  51942. }
  51943. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  51944. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51945. engine.enableEffect(_this._effect);
  51946. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  51947. var material = subMesh.getMaterial();
  51948. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  51949. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  51950. // Alpha test
  51951. if (material && material.needAlphaTesting()) {
  51952. var alphaTexture = material.getAlphaTestTexture();
  51953. _this._effect.setTexture("diffuseSampler", alphaTexture);
  51954. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51955. }
  51956. // Bones
  51957. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51958. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51959. }
  51960. // Draw
  51961. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51962. }
  51963. };
  51964. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  51965. var index;
  51966. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51967. renderSubMesh(opaqueSubMeshes.data[index]);
  51968. }
  51969. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51970. renderSubMesh(alphaTestSubMeshes.data[index]);
  51971. }
  51972. };
  51973. }
  51974. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  51975. var material = subMesh.getMaterial();
  51976. if (material.disableDepthWrite) {
  51977. return false;
  51978. }
  51979. var defines = [];
  51980. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51981. var mesh = subMesh.getMesh();
  51982. var scene = mesh.getScene();
  51983. // Alpha test
  51984. if (material && material.needAlphaTesting()) {
  51985. defines.push("#define ALPHATEST");
  51986. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51987. attribs.push(BABYLON.VertexBuffer.UVKind);
  51988. defines.push("#define UV1");
  51989. }
  51990. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51991. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51992. defines.push("#define UV2");
  51993. }
  51994. }
  51995. // Bones
  51996. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51997. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51998. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51999. if (mesh.numBoneInfluencers > 4) {
  52000. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52001. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52002. }
  52003. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52004. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52005. }
  52006. else {
  52007. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52008. }
  52009. // Instances
  52010. if (useInstances) {
  52011. defines.push("#define INSTANCES");
  52012. attribs.push("world0");
  52013. attribs.push("world1");
  52014. attribs.push("world2");
  52015. attribs.push("world3");
  52016. }
  52017. // Get correct effect
  52018. var join = defines.join("\n");
  52019. if (this._cachedDefines !== join) {
  52020. this._cachedDefines = join;
  52021. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  52022. }
  52023. return this._effect.isReady();
  52024. };
  52025. DepthRenderer.prototype.getDepthMap = function () {
  52026. return this._depthMap;
  52027. };
  52028. // Methods
  52029. DepthRenderer.prototype.dispose = function () {
  52030. this._depthMap.dispose();
  52031. };
  52032. return DepthRenderer;
  52033. }());
  52034. BABYLON.DepthRenderer = DepthRenderer;
  52035. })(BABYLON || (BABYLON = {}));
  52036. //# sourceMappingURL=babylon.depthRenderer.js.map
  52037. var BABYLON;
  52038. (function (BABYLON) {
  52039. var SSAORenderingPipeline = (function (_super) {
  52040. __extends(SSAORenderingPipeline, _super);
  52041. /**
  52042. * @constructor
  52043. * @param {string} name - The rendering pipeline name
  52044. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52045. * @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 }
  52046. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52047. */
  52048. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  52049. var _this = _super.call(this, scene.getEngine(), name) || this;
  52050. // Members
  52051. /**
  52052. * The PassPostProcess id in the pipeline that contains the original scene color
  52053. * @type {string}
  52054. */
  52055. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52056. /**
  52057. * The SSAO PostProcess id in the pipeline
  52058. * @type {string}
  52059. */
  52060. _this.SSAORenderEffect = "SSAORenderEffect";
  52061. /**
  52062. * The horizontal blur PostProcess id in the pipeline
  52063. * @type {string}
  52064. */
  52065. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52066. /**
  52067. * The vertical blur PostProcess id in the pipeline
  52068. * @type {string}
  52069. */
  52070. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52071. /**
  52072. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52073. * @type {string}
  52074. */
  52075. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52076. /**
  52077. * The output strength of the SSAO post-process. Default value is 1.0.
  52078. * @type {number}
  52079. */
  52080. _this.totalStrength = 1.0;
  52081. /**
  52082. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  52083. * @type {number}
  52084. */
  52085. _this.radius = 0.0001;
  52086. /**
  52087. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  52088. * Must not be equal to fallOff and superior to fallOff.
  52089. * Default value is 0.975
  52090. * @type {number}
  52091. */
  52092. _this.area = 0.0075;
  52093. /**
  52094. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  52095. * Must not be equal to area and inferior to area.
  52096. * Default value is 0.0
  52097. * @type {number}
  52098. */
  52099. _this.fallOff = 0.000001;
  52100. /**
  52101. * The base color of the SSAO post-process
  52102. * The final result is "base + ssao" between [0, 1]
  52103. * @type {number}
  52104. */
  52105. _this.base = 0.5;
  52106. _this._firstUpdate = true;
  52107. _this._scene = scene;
  52108. // Set up assets
  52109. _this._createRandomTexture();
  52110. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52111. var ssaoRatio = ratio.ssaoRatio || ratio;
  52112. var combineRatio = ratio.combineRatio || ratio;
  52113. _this._ratio = {
  52114. ssaoRatio: ssaoRatio,
  52115. combineRatio: combineRatio
  52116. };
  52117. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52118. _this._createSSAOPostProcess(ssaoRatio);
  52119. _this._createBlurPostProcess(ssaoRatio);
  52120. _this._createSSAOCombinePostProcess(combineRatio);
  52121. // Set up pipeline
  52122. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52123. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52124. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52125. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52127. // Finish
  52128. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52129. if (cameras)
  52130. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52131. return _this;
  52132. }
  52133. // Public Methods
  52134. /**
  52135. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52136. */
  52137. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52138. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52139. for (var i = 0; i < this._scene.cameras.length; i++) {
  52140. var camera = this._scene.cameras[i];
  52141. this._originalColorPostProcess.dispose(camera);
  52142. this._ssaoPostProcess.dispose(camera);
  52143. this._blurHPostProcess.dispose(camera);
  52144. this._blurVPostProcess.dispose(camera);
  52145. this._ssaoCombinePostProcess.dispose(camera);
  52146. }
  52147. this._randomTexture.dispose();
  52148. if (disableDepthRender)
  52149. this._scene.disableDepthRenderer();
  52150. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52151. _super.prototype.dispose.call(this);
  52152. };
  52153. // Private Methods
  52154. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  52155. var _this = this;
  52156. /*
  52157. var samplerOffsets = [
  52158. -8.0, -6.0, -4.0, -2.0,
  52159. 0.0,
  52160. 2.0, 4.0, 6.0, 8.0
  52161. ];
  52162. */
  52163. var samples = 16;
  52164. var samplerOffsets = [];
  52165. for (var i = -8; i < 8; i++) {
  52166. samplerOffsets.push(i * 2);
  52167. }
  52168. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  52169. this._blurHPostProcess.onApply = function (effect) {
  52170. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52171. effect.setTexture("depthSampler", _this._depthTexture);
  52172. if (_this._firstUpdate) {
  52173. effect.setArray("samplerOffsets", samplerOffsets);
  52174. }
  52175. };
  52176. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  52177. this._blurVPostProcess.onApply = function (effect) {
  52178. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52179. effect.setTexture("depthSampler", _this._depthTexture);
  52180. if (_this._firstUpdate) {
  52181. effect.setArray("samplerOffsets", samplerOffsets);
  52182. _this._firstUpdate = false;
  52183. }
  52184. };
  52185. };
  52186. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52187. var _this = this;
  52188. var numSamples = 16;
  52189. var sampleSphere = [
  52190. 0.5381, 0.1856, -0.4319,
  52191. 0.1379, 0.2486, 0.4430,
  52192. 0.3371, 0.5679, -0.0057,
  52193. -0.6999, -0.0451, -0.0019,
  52194. 0.0689, -0.1598, -0.8547,
  52195. 0.0560, 0.0069, -0.1843,
  52196. -0.0146, 0.1402, 0.0762,
  52197. 0.0100, -0.1924, -0.0344,
  52198. -0.3577, -0.5301, -0.4358,
  52199. -0.3169, 0.1063, 0.0158,
  52200. 0.0103, -0.5869, 0.0046,
  52201. -0.0897, -0.4940, 0.3287,
  52202. 0.7119, -0.0154, -0.0918,
  52203. -0.0533, 0.0596, -0.5411,
  52204. 0.0352, -0.0631, 0.5460,
  52205. -0.4776, 0.2847, -0.0271
  52206. ];
  52207. var samplesFactor = 1.0 / numSamples;
  52208. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  52209. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52210. "area", "fallOff", "base", "range", "viewport"
  52211. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52212. var viewport = new BABYLON.Vector2(0, 0);
  52213. this._ssaoPostProcess.onApply = function (effect) {
  52214. if (_this._firstUpdate) {
  52215. effect.setArray3("sampleSphere", sampleSphere);
  52216. effect.setFloat("samplesFactor", samplesFactor);
  52217. effect.setFloat("randTextureTiles", 4.0);
  52218. }
  52219. effect.setFloat("totalStrength", _this.totalStrength);
  52220. effect.setFloat("radius", _this.radius);
  52221. effect.setFloat("area", _this.area);
  52222. effect.setFloat("fallOff", _this.fallOff);
  52223. effect.setFloat("base", _this.base);
  52224. effect.setTexture("textureSampler", _this._depthTexture);
  52225. effect.setTexture("randomSampler", _this._randomTexture);
  52226. };
  52227. };
  52228. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52229. var _this = this;
  52230. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52231. this._ssaoCombinePostProcess.onApply = function (effect) {
  52232. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52233. };
  52234. };
  52235. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  52236. var size = 512;
  52237. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52238. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52239. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52240. var context = this._randomTexture.getContext();
  52241. var rand = function (min, max) {
  52242. return Math.random() * (max - min) + min;
  52243. };
  52244. var randVector = BABYLON.Vector3.Zero();
  52245. for (var x = 0; x < size; x++) {
  52246. for (var y = 0; y < size; y++) {
  52247. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  52248. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  52249. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  52250. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52251. context.fillRect(x, y, 1, 1);
  52252. }
  52253. }
  52254. this._randomTexture.update(false);
  52255. };
  52256. return SSAORenderingPipeline;
  52257. }(BABYLON.PostProcessRenderPipeline));
  52258. __decorate([
  52259. BABYLON.serialize()
  52260. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  52261. __decorate([
  52262. BABYLON.serialize()
  52263. ], SSAORenderingPipeline.prototype, "radius", void 0);
  52264. __decorate([
  52265. BABYLON.serialize()
  52266. ], SSAORenderingPipeline.prototype, "area", void 0);
  52267. __decorate([
  52268. BABYLON.serialize()
  52269. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  52270. __decorate([
  52271. BABYLON.serialize()
  52272. ], SSAORenderingPipeline.prototype, "base", void 0);
  52273. __decorate([
  52274. BABYLON.serialize()
  52275. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  52276. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  52277. })(BABYLON || (BABYLON = {}));
  52278. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  52279. var BABYLON;
  52280. (function (BABYLON) {
  52281. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  52282. var VolumetricLightScatteringPostProcess = (function (_super) {
  52283. __extends(VolumetricLightScatteringPostProcess, _super);
  52284. /**
  52285. * @constructor
  52286. * @param {string} name - The post-process name
  52287. * @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)
  52288. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  52289. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  52290. * @param {number} samples - The post-process quality, default 100
  52291. * @param {number} samplingMode - The post-process filtering mode
  52292. * @param {BABYLON.Engine} engine - The babylon engine
  52293. * @param {boolean} reusable - If the post-process is reusable
  52294. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  52295. */
  52296. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  52297. if (samples === void 0) { samples = 100; }
  52298. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52299. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  52300. _this._screenCoordinates = BABYLON.Vector2.Zero();
  52301. /**
  52302. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  52303. * @type {Vector3}
  52304. */
  52305. _this.customMeshPosition = BABYLON.Vector3.Zero();
  52306. /**
  52307. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  52308. * @type {boolean}
  52309. */
  52310. _this.useCustomMeshPosition = false;
  52311. /**
  52312. * If the post-process should inverse the light scattering direction
  52313. * @type {boolean}
  52314. */
  52315. _this.invert = true;
  52316. /**
  52317. * Array containing the excluded meshes not rendered in the internal pass
  52318. */
  52319. _this.excludedMeshes = new Array();
  52320. /**
  52321. * Controls the overall intensity of the post-process
  52322. * @type {number}
  52323. */
  52324. _this.exposure = 0.3;
  52325. /**
  52326. * Dissipates each sample's contribution in range [0, 1]
  52327. * @type {number}
  52328. */
  52329. _this.decay = 0.96815;
  52330. /**
  52331. * Controls the overall intensity of each sample
  52332. * @type {number}
  52333. */
  52334. _this.weight = 0.58767;
  52335. /**
  52336. * Controls the density of each sample
  52337. * @type {number}
  52338. */
  52339. _this.density = 0.926;
  52340. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  52341. var engine = scene.getEngine();
  52342. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  52343. // Configure mesh
  52344. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  52345. // Configure
  52346. _this._createPass(scene, ratio.passRatio || ratio);
  52347. _this.onActivate = function (camera) {
  52348. if (!_this.isSupported) {
  52349. _this.dispose(camera);
  52350. }
  52351. _this.onActivate = null;
  52352. };
  52353. _this.onApplyObservable.add(function (effect) {
  52354. _this._updateMeshScreenCoordinates(scene);
  52355. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  52356. effect.setFloat("exposure", _this.exposure);
  52357. effect.setFloat("decay", _this.decay);
  52358. effect.setFloat("weight", _this.weight);
  52359. effect.setFloat("density", _this.density);
  52360. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  52361. });
  52362. return _this;
  52363. }
  52364. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  52365. get: function () {
  52366. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52367. return false;
  52368. },
  52369. set: function (useDiffuseColor) {
  52370. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52371. },
  52372. enumerable: true,
  52373. configurable: true
  52374. });
  52375. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  52376. var mesh = subMesh.getMesh();
  52377. // Render this.mesh as default
  52378. if (mesh === this.mesh) {
  52379. return mesh.material.isReady(mesh);
  52380. }
  52381. var defines = [];
  52382. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52383. var material = subMesh.getMaterial();
  52384. var needUV = false;
  52385. // Alpha test
  52386. if (material) {
  52387. if (material.needAlphaTesting()) {
  52388. defines.push("#define ALPHATEST");
  52389. }
  52390. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52391. attribs.push(BABYLON.VertexBuffer.UVKind);
  52392. defines.push("#define UV1");
  52393. }
  52394. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52395. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52396. defines.push("#define UV2");
  52397. }
  52398. }
  52399. // Bones
  52400. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52401. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52402. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52403. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52404. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52405. }
  52406. else {
  52407. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52408. }
  52409. // Instances
  52410. if (useInstances) {
  52411. defines.push("#define INSTANCES");
  52412. attribs.push("world0");
  52413. attribs.push("world1");
  52414. attribs.push("world2");
  52415. attribs.push("world3");
  52416. }
  52417. // Get correct effect
  52418. var join = defines.join("\n");
  52419. if (this._cachedDefines !== join) {
  52420. this._cachedDefines = join;
  52421. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  52422. }
  52423. return this._volumetricLightScatteringPass.isReady();
  52424. };
  52425. /**
  52426. * Sets the new light position for light scattering effect
  52427. * @param {BABYLON.Vector3} The new custom light position
  52428. */
  52429. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  52430. this.customMeshPosition = position;
  52431. };
  52432. /**
  52433. * Returns the light position for light scattering effect
  52434. * @return {BABYLON.Vector3} The custom light position
  52435. */
  52436. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  52437. return this.customMeshPosition;
  52438. };
  52439. /**
  52440. * Disposes the internal assets and detaches the post-process from the camera
  52441. */
  52442. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  52443. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  52444. if (rttIndex !== -1) {
  52445. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  52446. }
  52447. this._volumetricLightScatteringRTT.dispose();
  52448. _super.prototype.dispose.call(this, camera);
  52449. };
  52450. /**
  52451. * Returns the render target texture used by the post-process
  52452. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  52453. */
  52454. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  52455. return this._volumetricLightScatteringRTT;
  52456. };
  52457. // Private methods
  52458. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  52459. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  52460. return true;
  52461. }
  52462. return false;
  52463. };
  52464. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  52465. var _this = this;
  52466. var engine = scene.getEngine();
  52467. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52468. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52469. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52470. this._volumetricLightScatteringRTT.renderList = null;
  52471. this._volumetricLightScatteringRTT.renderParticles = false;
  52472. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  52473. // Custom render function for submeshes
  52474. var renderSubMesh = function (subMesh) {
  52475. var mesh = subMesh.getRenderingMesh();
  52476. if (_this._meshExcluded(mesh)) {
  52477. return;
  52478. }
  52479. var scene = mesh.getScene();
  52480. var engine = scene.getEngine();
  52481. // Culling
  52482. engine.setState(subMesh.getMaterial().backFaceCulling);
  52483. // Managing instances
  52484. var batch = mesh._getInstancesRenderList(subMesh._id);
  52485. if (batch.mustReturn) {
  52486. return;
  52487. }
  52488. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  52489. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52490. var effect = _this._volumetricLightScatteringPass;
  52491. if (mesh === _this.mesh) {
  52492. effect = subMesh.getMaterial().getEffect();
  52493. }
  52494. engine.enableEffect(effect);
  52495. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  52496. if (mesh === _this.mesh) {
  52497. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  52498. }
  52499. else {
  52500. var material = subMesh.getMaterial();
  52501. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  52502. // Alpha test
  52503. if (material && material.needAlphaTesting()) {
  52504. var alphaTexture = material.getAlphaTestTexture();
  52505. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  52506. if (alphaTexture) {
  52507. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52508. }
  52509. }
  52510. // Bones
  52511. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52512. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52513. }
  52514. }
  52515. // Draw
  52516. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  52517. }
  52518. };
  52519. // Render target texture callbacks
  52520. var savedSceneClearColor;
  52521. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  52522. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  52523. savedSceneClearColor = scene.clearColor;
  52524. scene.clearColor = sceneClearColor;
  52525. });
  52526. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  52527. scene.clearColor = savedSceneClearColor;
  52528. });
  52529. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  52530. var engine = scene.getEngine();
  52531. var index;
  52532. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52533. renderSubMesh(opaqueSubMeshes.data[index]);
  52534. }
  52535. engine.setAlphaTesting(true);
  52536. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52537. renderSubMesh(alphaTestSubMeshes.data[index]);
  52538. }
  52539. engine.setAlphaTesting(false);
  52540. if (transparentSubMeshes.length) {
  52541. // Sort sub meshes
  52542. for (index = 0; index < transparentSubMeshes.length; index++) {
  52543. var submesh = transparentSubMeshes.data[index];
  52544. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  52545. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  52546. }
  52547. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  52548. sortedArray.sort(function (a, b) {
  52549. // Alpha index first
  52550. if (a._alphaIndex > b._alphaIndex) {
  52551. return 1;
  52552. }
  52553. if (a._alphaIndex < b._alphaIndex) {
  52554. return -1;
  52555. }
  52556. // Then distance to camera
  52557. if (a._distanceToCamera < b._distanceToCamera) {
  52558. return 1;
  52559. }
  52560. if (a._distanceToCamera > b._distanceToCamera) {
  52561. return -1;
  52562. }
  52563. return 0;
  52564. });
  52565. // Render sub meshes
  52566. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52567. for (index = 0; index < sortedArray.length; index++) {
  52568. renderSubMesh(sortedArray[index]);
  52569. }
  52570. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52571. }
  52572. };
  52573. };
  52574. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  52575. var transform = scene.getTransformMatrix();
  52576. var meshPosition;
  52577. if (this.useCustomMeshPosition) {
  52578. meshPosition = this.customMeshPosition;
  52579. }
  52580. else if (this.attachedNode) {
  52581. meshPosition = this.attachedNode.position;
  52582. }
  52583. else {
  52584. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  52585. }
  52586. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  52587. this._screenCoordinates.x = pos.x / this._viewPort.width;
  52588. this._screenCoordinates.y = pos.y / this._viewPort.height;
  52589. if (this.invert)
  52590. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  52591. };
  52592. // Static methods
  52593. /**
  52594. * Creates a default mesh for the Volumeric Light Scattering post-process
  52595. * @param {string} The mesh name
  52596. * @param {BABYLON.Scene} The scene where to create the mesh
  52597. * @return {BABYLON.Mesh} the default mesh
  52598. */
  52599. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  52600. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  52601. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  52602. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  52603. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  52604. mesh.material = material;
  52605. return mesh;
  52606. };
  52607. return VolumetricLightScatteringPostProcess;
  52608. }(BABYLON.PostProcess));
  52609. __decorate([
  52610. BABYLON.serializeAsVector3()
  52611. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  52612. __decorate([
  52613. BABYLON.serialize()
  52614. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  52615. __decorate([
  52616. BABYLON.serialize()
  52617. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  52618. __decorate([
  52619. BABYLON.serializeAsMeshReference()
  52620. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  52621. __decorate([
  52622. BABYLON.serialize()
  52623. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  52624. __decorate([
  52625. BABYLON.serialize()
  52626. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  52627. __decorate([
  52628. BABYLON.serialize()
  52629. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  52630. __decorate([
  52631. BABYLON.serialize()
  52632. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  52633. __decorate([
  52634. BABYLON.serialize()
  52635. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  52636. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  52637. })(BABYLON || (BABYLON = {}));
  52638. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  52639. // BABYLON.JS Chromatic Aberration GLSL Shader
  52640. // Author: Olivier Guyot
  52641. // Separates very slightly R, G and B colors on the edges of the screen
  52642. // Inspired by Francois Tarlier & Martins Upitis
  52643. var BABYLON;
  52644. (function (BABYLON) {
  52645. var LensRenderingPipeline = (function (_super) {
  52646. __extends(LensRenderingPipeline, _super);
  52647. /**
  52648. * @constructor
  52649. *
  52650. * Effect parameters are as follow:
  52651. * {
  52652. * chromatic_aberration: number; // from 0 to x (1 for realism)
  52653. * edge_blur: number; // from 0 to x (1 for realism)
  52654. * distortion: number; // from 0 to x (1 for realism)
  52655. * grain_amount: number; // from 0 to 1
  52656. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  52657. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  52658. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  52659. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  52660. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  52661. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  52662. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  52663. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  52664. * }
  52665. * Note: if an effect parameter is unset, effect is disabled
  52666. *
  52667. * @param {string} name - The rendering pipeline name
  52668. * @param {object} parameters - An object containing all parameters (see above)
  52669. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52670. * @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)
  52671. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52672. */
  52673. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  52674. if (ratio === void 0) { ratio = 1.0; }
  52675. var _this = _super.call(this, scene.getEngine(), name) || this;
  52676. // Lens effects can be of the following:
  52677. // - chromatic aberration (slight shift of RGB colors)
  52678. // - blur on the edge of the lens
  52679. // - lens distortion
  52680. // - depth-of-field blur & highlights enhancing
  52681. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  52682. // - grain effect (noise or custom texture)
  52683. // Two additional texture samplers are needed:
  52684. // - depth map (for depth-of-field)
  52685. // - grain texture
  52686. /**
  52687. * The chromatic aberration PostProcess id in the pipeline
  52688. * @type {string}
  52689. */
  52690. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  52691. /**
  52692. * The highlights enhancing PostProcess id in the pipeline
  52693. * @type {string}
  52694. */
  52695. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  52696. /**
  52697. * The depth-of-field PostProcess id in the pipeline
  52698. * @type {string}
  52699. */
  52700. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  52701. _this._scene = scene;
  52702. // Fetch texture samplers
  52703. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52704. if (parameters.grain_texture) {
  52705. _this._grainTexture = parameters.grain_texture;
  52706. }
  52707. else {
  52708. _this._createGrainTexture();
  52709. }
  52710. // save parameters
  52711. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  52712. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  52713. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  52714. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  52715. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  52716. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  52717. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  52718. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  52719. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  52720. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  52721. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  52722. // Create effects
  52723. _this._createChromaticAberrationPostProcess(ratio);
  52724. _this._createHighlightsPostProcess(ratio);
  52725. _this._createDepthOfFieldPostProcess(ratio / 4);
  52726. // Set up pipeline
  52727. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  52728. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  52729. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  52730. if (_this._highlightsGain === -1) {
  52731. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  52732. }
  52733. // Finish
  52734. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52735. if (cameras) {
  52736. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52737. }
  52738. return _this;
  52739. }
  52740. // public methods (self explanatory)
  52741. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  52742. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  52743. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  52744. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  52745. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  52746. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  52747. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  52748. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  52749. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  52750. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  52751. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  52752. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  52753. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  52754. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  52755. };
  52756. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  52757. this._highlightsPostProcess.updateEffect();
  52758. };
  52759. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  52760. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  52761. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  52762. this._highlightsGain = amount;
  52763. };
  52764. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  52765. if (this._highlightsGain === -1) {
  52766. this._highlightsGain = 1.0;
  52767. }
  52768. this._highlightsThreshold = amount;
  52769. };
  52770. LensRenderingPipeline.prototype.disableHighlights = function () {
  52771. this._highlightsGain = -1;
  52772. };
  52773. /**
  52774. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  52775. */
  52776. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52777. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52778. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52779. this._chromaticAberrationPostProcess = undefined;
  52780. this._highlightsPostProcess = undefined;
  52781. this._depthOfFieldPostProcess = undefined;
  52782. this._grainTexture.dispose();
  52783. if (disableDepthRender)
  52784. this._scene.disableDepthRenderer();
  52785. };
  52786. // colors shifting and distortion
  52787. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  52788. var _this = this;
  52789. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  52790. [], // samplers
  52791. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52792. this._chromaticAberrationPostProcess.onApply = function (effect) {
  52793. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  52794. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52795. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52796. };
  52797. };
  52798. // highlights enhancing
  52799. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  52800. var _this = this;
  52801. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  52802. [], // samplers
  52803. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  52804. this._highlightsPostProcess.onApply = function (effect) {
  52805. effect.setFloat('gain', _this._highlightsGain);
  52806. effect.setFloat('threshold', _this._highlightsThreshold);
  52807. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  52808. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52809. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52810. };
  52811. };
  52812. // colors shifting and distortion
  52813. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  52814. var _this = this;
  52815. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  52816. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  52817. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  52818. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52819. this._depthOfFieldPostProcess.onApply = function (effect) {
  52820. effect.setTexture("depthSampler", _this._depthTexture);
  52821. effect.setTexture("grainSampler", _this._grainTexture);
  52822. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  52823. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  52824. effect.setFloat('grain_amount', _this._grainAmount);
  52825. effect.setBool('blur_noise', _this._blurNoise);
  52826. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52827. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52828. effect.setFloat('distortion', _this._distortion);
  52829. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  52830. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  52831. effect.setFloat('aperture', _this._dofAperture);
  52832. effect.setFloat('darken', _this._dofDarken);
  52833. effect.setFloat('edge_blur', _this._edgeBlur);
  52834. effect.setBool('highlights', (_this._highlightsGain !== -1));
  52835. effect.setFloat('near', _this._scene.activeCamera.minZ);
  52836. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  52837. };
  52838. };
  52839. // creates a black and white random noise texture, 512x512
  52840. LensRenderingPipeline.prototype._createGrainTexture = function () {
  52841. var size = 512;
  52842. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52843. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52844. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52845. var context = this._grainTexture.getContext();
  52846. var rand = function (min, max) {
  52847. return Math.random() * (max - min) + min;
  52848. };
  52849. var value;
  52850. for (var x = 0; x < size; x++) {
  52851. for (var y = 0; y < size; y++) {
  52852. value = Math.floor(rand(0.42, 0.58) * 255);
  52853. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  52854. context.fillRect(x, y, 1, 1);
  52855. }
  52856. }
  52857. this._grainTexture.update(false);
  52858. };
  52859. return LensRenderingPipeline;
  52860. }(BABYLON.PostProcessRenderPipeline));
  52861. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  52862. })(BABYLON || (BABYLON = {}));
  52863. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  52864. //
  52865. // This post-process allows the modification of rendered colors by using
  52866. // a 'look-up table' (LUT). This effect is also called Color Grading.
  52867. //
  52868. // The object needs to be provided an url to a texture containing the color
  52869. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  52870. // Use an image editing software to tweak the LUT to match your needs.
  52871. //
  52872. // For an example of a color LUT, see here:
  52873. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  52874. // For explanations on color grading, see here:
  52875. // http://udn.epicgames.com/Three/ColorGrading.html
  52876. //
  52877. var BABYLON;
  52878. (function (BABYLON) {
  52879. var ColorCorrectionPostProcess = (function (_super) {
  52880. __extends(ColorCorrectionPostProcess, _super);
  52881. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  52882. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  52883. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52884. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  52885. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52886. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52887. _this.onApply = function (effect) {
  52888. effect.setTexture("colorTable", _this._colorTableTexture);
  52889. };
  52890. return _this;
  52891. }
  52892. return ColorCorrectionPostProcess;
  52893. }(BABYLON.PostProcess));
  52894. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  52895. })(BABYLON || (BABYLON = {}));
  52896. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  52897. /// <reference path="babylon.freeCamera.ts" />
  52898. /// <reference path="babylon.arcRotateCamera.ts" />
  52899. /// <reference path="babylon.gamepadCamera.ts" />
  52900. /// <reference path="babylon.universalCamera.ts" />
  52901. var BABYLON;
  52902. (function (BABYLON) {
  52903. var AnaglyphFreeCamera = (function (_super) {
  52904. __extends(AnaglyphFreeCamera, _super);
  52905. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  52906. var _this = _super.call(this, name, position, scene) || this;
  52907. _this.interaxialDistance = interaxialDistance;
  52908. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52909. return _this;
  52910. }
  52911. AnaglyphFreeCamera.prototype.getClassName = function () {
  52912. return "AnaglyphFreeCamera";
  52913. };
  52914. return AnaglyphFreeCamera;
  52915. }(BABYLON.FreeCamera));
  52916. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  52917. var AnaglyphArcRotateCamera = (function (_super) {
  52918. __extends(AnaglyphArcRotateCamera, _super);
  52919. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  52920. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  52921. _this.interaxialDistance = interaxialDistance;
  52922. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52923. return _this;
  52924. }
  52925. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  52926. return "AnaglyphArcRotateCamera";
  52927. };
  52928. return AnaglyphArcRotateCamera;
  52929. }(BABYLON.ArcRotateCamera));
  52930. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  52931. var AnaglyphGamepadCamera = (function (_super) {
  52932. __extends(AnaglyphGamepadCamera, _super);
  52933. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  52934. var _this = _super.call(this, name, position, scene) || this;
  52935. _this.interaxialDistance = interaxialDistance;
  52936. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52937. return _this;
  52938. }
  52939. AnaglyphGamepadCamera.prototype.getClassName = function () {
  52940. return "AnaglyphGamepadCamera";
  52941. };
  52942. return AnaglyphGamepadCamera;
  52943. }(BABYLON.GamepadCamera));
  52944. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  52945. var AnaglyphUniversalCamera = (function (_super) {
  52946. __extends(AnaglyphUniversalCamera, _super);
  52947. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  52948. var _this = _super.call(this, name, position, scene) || this;
  52949. _this.interaxialDistance = interaxialDistance;
  52950. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52951. return _this;
  52952. }
  52953. AnaglyphUniversalCamera.prototype.getClassName = function () {
  52954. return "AnaglyphUniversalCamera";
  52955. };
  52956. return AnaglyphUniversalCamera;
  52957. }(BABYLON.UniversalCamera));
  52958. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  52959. var StereoscopicFreeCamera = (function (_super) {
  52960. __extends(StereoscopicFreeCamera, _super);
  52961. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  52962. var _this = _super.call(this, name, position, scene) || this;
  52963. _this.interaxialDistance = interaxialDistance;
  52964. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52965. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52966. return _this;
  52967. }
  52968. StereoscopicFreeCamera.prototype.getClassName = function () {
  52969. return "StereoscopicFreeCamera";
  52970. };
  52971. return StereoscopicFreeCamera;
  52972. }(BABYLON.FreeCamera));
  52973. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  52974. var StereoscopicArcRotateCamera = (function (_super) {
  52975. __extends(StereoscopicArcRotateCamera, _super);
  52976. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  52977. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  52978. _this.interaxialDistance = interaxialDistance;
  52979. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52980. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52981. return _this;
  52982. }
  52983. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  52984. return "StereoscopicArcRotateCamera";
  52985. };
  52986. return StereoscopicArcRotateCamera;
  52987. }(BABYLON.ArcRotateCamera));
  52988. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  52989. var StereoscopicGamepadCamera = (function (_super) {
  52990. __extends(StereoscopicGamepadCamera, _super);
  52991. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  52992. var _this = _super.call(this, name, position, scene) || this;
  52993. _this.interaxialDistance = interaxialDistance;
  52994. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52995. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52996. return _this;
  52997. }
  52998. StereoscopicGamepadCamera.prototype.getClassName = function () {
  52999. return "StereoscopicGamepadCamera";
  53000. };
  53001. return StereoscopicGamepadCamera;
  53002. }(BABYLON.GamepadCamera));
  53003. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  53004. var StereoscopicUniversalCamera = (function (_super) {
  53005. __extends(StereoscopicUniversalCamera, _super);
  53006. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53007. var _this = _super.call(this, name, position, scene) || this;
  53008. _this.interaxialDistance = interaxialDistance;
  53009. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53010. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53011. return _this;
  53012. }
  53013. StereoscopicUniversalCamera.prototype.getClassName = function () {
  53014. return "StereoscopicUniversalCamera";
  53015. };
  53016. return StereoscopicUniversalCamera;
  53017. }(BABYLON.UniversalCamera));
  53018. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  53019. })(BABYLON || (BABYLON = {}));
  53020. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  53021. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  53022. var BABYLON;
  53023. (function (BABYLON) {
  53024. var HDRRenderingPipeline = (function (_super) {
  53025. __extends(HDRRenderingPipeline, _super);
  53026. /**
  53027. * @constructor
  53028. * @param {string} name - The rendering pipeline name
  53029. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53030. * @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)
  53031. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53032. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53033. */
  53034. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53035. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53036. var _this = _super.call(this, scene.getEngine(), name) || this;
  53037. /**
  53038. * Public members
  53039. */
  53040. // Gaussian Blur
  53041. /**
  53042. * Gaussian blur coefficient
  53043. * @type {number}
  53044. */
  53045. _this.gaussCoeff = 0.3;
  53046. /**
  53047. * Gaussian blur mean
  53048. * @type {number}
  53049. */
  53050. _this.gaussMean = 1.0;
  53051. /**
  53052. * Gaussian blur standard deviation
  53053. * @type {number}
  53054. */
  53055. _this.gaussStandDev = 0.8;
  53056. /**
  53057. * Gaussian blur multiplier. Multiplies the blur effect
  53058. * @type {number}
  53059. */
  53060. _this.gaussMultiplier = 4.0;
  53061. // HDR
  53062. /**
  53063. * Exposure, controls the overall intensity of the pipeline
  53064. * @type {number}
  53065. */
  53066. _this.exposure = 1.0;
  53067. /**
  53068. * Minimum luminance that the post-process can output. Luminance is >= 0
  53069. * @type {number}
  53070. */
  53071. _this.minimumLuminance = 1.0;
  53072. /**
  53073. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  53074. * @type {number}
  53075. */
  53076. _this.maximumLuminance = 1e20;
  53077. /**
  53078. * Increase rate for luminance: eye adaptation speed to dark
  53079. * @type {number}
  53080. */
  53081. _this.luminanceIncreaserate = 0.5;
  53082. /**
  53083. * Decrease rate for luminance: eye adaptation speed to bright
  53084. * @type {number}
  53085. */
  53086. _this.luminanceDecreaseRate = 0.5;
  53087. // Bright pass
  53088. /**
  53089. * Minimum luminance needed to compute HDR
  53090. * @type {number}
  53091. */
  53092. _this.brightThreshold = 0.8;
  53093. _this._needUpdate = true;
  53094. _this._scene = scene;
  53095. // Bright pass
  53096. _this._createBrightPassPostProcess(scene, ratio);
  53097. // Down sample X4
  53098. _this._createDownSampleX4PostProcess(scene, ratio);
  53099. // Create gaussian blur post-processes
  53100. _this._createGaussianBlurPostProcess(scene, ratio);
  53101. // Texture adder
  53102. _this._createTextureAdderPostProcess(scene, ratio);
  53103. // Luminance generator
  53104. _this._createLuminanceGeneratorPostProcess(scene);
  53105. // HDR
  53106. _this._createHDRPostProcess(scene, ratio);
  53107. // Pass postprocess
  53108. if (originalPostProcess === null) {
  53109. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53110. }
  53111. else {
  53112. _this._originalPostProcess = originalPostProcess;
  53113. }
  53114. // Configure pipeline
  53115. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  53116. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  53117. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  53118. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  53119. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  53120. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  53121. var addDownSamplerPostProcess = function (id) {
  53122. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  53123. };
  53124. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  53125. addDownSamplerPostProcess(i);
  53126. }
  53127. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  53128. // Finish
  53129. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53130. if (cameras !== null) {
  53131. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53132. }
  53133. _this.update();
  53134. return _this;
  53135. }
  53136. /**
  53137. * Tells the pipeline to update its post-processes
  53138. */
  53139. HDRRenderingPipeline.prototype.update = function () {
  53140. this._needUpdate = true;
  53141. };
  53142. /**
  53143. * Returns the current calculated luminance
  53144. */
  53145. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  53146. return this._hdrCurrentLuminance;
  53147. };
  53148. /**
  53149. * Returns the currently drawn luminance
  53150. */
  53151. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  53152. return this._hdrOutputLuminance;
  53153. };
  53154. /**
  53155. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  53156. */
  53157. HDRRenderingPipeline.prototype.dispose = function () {
  53158. for (var i = 0; i < this._scene.cameras.length; i++) {
  53159. var camera = this._scene.cameras[i];
  53160. this._originalPostProcess.dispose(camera);
  53161. this._brightPassPostProcess.dispose(camera);
  53162. this._downSampleX4PostProcess.dispose(camera);
  53163. this._guassianBlurHPostProcess.dispose(camera);
  53164. this._guassianBlurVPostProcess.dispose(camera);
  53165. this._textureAdderPostProcess.dispose(camera);
  53166. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  53167. this._downSamplePostProcesses[j].dispose(camera);
  53168. }
  53169. this._hdrPostProcess.dispose(camera);
  53170. }
  53171. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53172. _super.prototype.dispose.call(this);
  53173. };
  53174. /**
  53175. * Creates the HDR post-process and computes the luminance adaptation
  53176. */
  53177. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  53178. var _this = this;
  53179. var hdrLastLuminance = 0.0;
  53180. this._hdrOutputLuminance = -1.0;
  53181. this._hdrCurrentLuminance = 1.0;
  53182. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  53183. this._hdrPostProcess.onApply = function (effect) {
  53184. if (_this._hdrOutputLuminance < 0.0) {
  53185. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  53186. }
  53187. else {
  53188. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  53189. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  53190. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  53191. }
  53192. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  53193. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  53194. }
  53195. else {
  53196. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  53197. }
  53198. }
  53199. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  53200. hdrLastLuminance += scene.getEngine().getDeltaTime();
  53201. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  53202. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  53203. effect.setFloat("exposure", _this.exposure);
  53204. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  53205. _this._needUpdate = false;
  53206. };
  53207. };
  53208. /**
  53209. * Texture Adder post-process
  53210. */
  53211. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53212. var _this = this;
  53213. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  53214. this._textureAdderPostProcess.onApply = function (effect) {
  53215. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  53216. };
  53217. };
  53218. /**
  53219. * Down sample X4 post-process
  53220. */
  53221. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53222. var _this = this;
  53223. var downSampleX4Offsets = new Array(32);
  53224. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  53225. this._downSampleX4PostProcess.onApply = function (effect) {
  53226. if (_this._needUpdate) {
  53227. var id = 0;
  53228. for (var i = -2; i < 2; i++) {
  53229. for (var j = -2; j < 2; j++) {
  53230. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  53231. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  53232. id += 2;
  53233. }
  53234. }
  53235. }
  53236. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53237. };
  53238. };
  53239. /**
  53240. * Bright pass post-process
  53241. */
  53242. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53243. var _this = this;
  53244. var brightOffsets = new Array(8);
  53245. var brightPassCallback = function (effect) {
  53246. if (_this._needUpdate) {
  53247. var sU = (1.0 / _this._brightPassPostProcess.width);
  53248. var sV = (1.0 / _this._brightPassPostProcess.height);
  53249. brightOffsets[0] = -0.5 * sU;
  53250. brightOffsets[1] = 0.5 * sV;
  53251. brightOffsets[2] = 0.5 * sU;
  53252. brightOffsets[3] = 0.5 * sV;
  53253. brightOffsets[4] = -0.5 * sU;
  53254. brightOffsets[5] = -0.5 * sV;
  53255. brightOffsets[6] = 0.5 * sU;
  53256. brightOffsets[7] = -0.5 * sV;
  53257. }
  53258. effect.setArray2("dsOffsets", brightOffsets);
  53259. effect.setFloat("brightThreshold", _this.brightThreshold);
  53260. };
  53261. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  53262. this._brightPassPostProcess.onApply = brightPassCallback;
  53263. };
  53264. /**
  53265. * Luminance generator. Creates the luminance post-process and down sample post-processes
  53266. */
  53267. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  53268. var _this = this;
  53269. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  53270. var luminanceOffsets = new Array(8);
  53271. var downSampleOffsets = new Array(18);
  53272. var halfDestPixelSize;
  53273. this._downSamplePostProcesses = new Array(lumSteps);
  53274. // Utils for luminance
  53275. var luminanceUpdateSourceOffsets = function (width, height) {
  53276. var sU = (1.0 / width);
  53277. var sV = (1.0 / height);
  53278. luminanceOffsets[0] = -0.5 * sU;
  53279. luminanceOffsets[1] = 0.5 * sV;
  53280. luminanceOffsets[2] = 0.5 * sU;
  53281. luminanceOffsets[3] = 0.5 * sV;
  53282. luminanceOffsets[4] = -0.5 * sU;
  53283. luminanceOffsets[5] = -0.5 * sV;
  53284. luminanceOffsets[6] = 0.5 * sU;
  53285. luminanceOffsets[7] = -0.5 * sV;
  53286. };
  53287. var luminanceUpdateDestOffsets = function (width, height) {
  53288. var id = 0;
  53289. for (var x = -1; x < 2; x++) {
  53290. for (var y = -1; y < 2; y++) {
  53291. downSampleOffsets[id] = (x) / width;
  53292. downSampleOffsets[id + 1] = (y) / height;
  53293. id += 2;
  53294. }
  53295. }
  53296. };
  53297. // Luminance callback
  53298. var luminanceCallback = function (effect) {
  53299. if (_this._needUpdate) {
  53300. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  53301. }
  53302. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  53303. effect.setArray2("lumOffsets", luminanceOffsets);
  53304. };
  53305. // Down sample callbacks
  53306. var downSampleCallback = function (indice) {
  53307. var i = indice;
  53308. return function (effect) {
  53309. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  53310. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  53311. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  53312. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  53313. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  53314. effect.setArray2("dsOffsets", downSampleOffsets);
  53315. };
  53316. };
  53317. var downSampleAfterRenderCallback = function (effect) {
  53318. // Unpack result
  53319. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  53320. 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);
  53321. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  53322. };
  53323. // Create luminance post-process
  53324. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  53325. 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);
  53326. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  53327. // Create down sample post-processes
  53328. for (var i = lumSteps - 2; i >= 0; i--) {
  53329. var length = Math.pow(3, i);
  53330. ratio = { width: length, height: length };
  53331. var defines = "#define DOWN_SAMPLE\n";
  53332. if (i === 0) {
  53333. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  53334. }
  53335. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  53336. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  53337. if (i === 0) {
  53338. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  53339. }
  53340. }
  53341. };
  53342. /**
  53343. * Gaussian blur post-processes. Horizontal and Vertical
  53344. */
  53345. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  53346. var _this = this;
  53347. var blurOffsetsW = new Array(9);
  53348. var blurOffsetsH = new Array(9);
  53349. var blurWeights = new Array(9);
  53350. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  53351. // Utils for gaussian blur
  53352. var calculateBlurOffsets = function (height) {
  53353. var lastOutputDimensions = {
  53354. width: scene.getEngine().getRenderWidth(),
  53355. height: scene.getEngine().getRenderHeight()
  53356. };
  53357. for (var i = 0; i < 9; i++) {
  53358. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  53359. if (height) {
  53360. blurOffsetsH[i] = value;
  53361. }
  53362. else {
  53363. blurOffsetsW[i] = value;
  53364. }
  53365. }
  53366. };
  53367. var calculateWeights = function () {
  53368. var x = 0.0;
  53369. for (var i = 0; i < 9; i++) {
  53370. x = (i - 4.0) / 4.0;
  53371. 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));
  53372. }
  53373. };
  53374. // Callback
  53375. var gaussianBlurCallback = function (height) {
  53376. return function (effect) {
  53377. if (_this._needUpdate) {
  53378. calculateWeights();
  53379. calculateBlurOffsets(height);
  53380. }
  53381. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  53382. effect.setArray("blurWeights", blurWeights);
  53383. effect.setFloat("multiplier", _this.gaussMultiplier);
  53384. };
  53385. };
  53386. // Create horizontal gaussian blur post-processes
  53387. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  53388. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  53389. // Create vertical gaussian blur post-process
  53390. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  53391. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  53392. };
  53393. return HDRRenderingPipeline;
  53394. }(BABYLON.PostProcessRenderPipeline));
  53395. // Luminance generator
  53396. HDRRenderingPipeline.LUM_STEPS = 6;
  53397. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  53398. })(BABYLON || (BABYLON = {}));
  53399. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  53400. var BABYLON;
  53401. (function (BABYLON) {
  53402. var FaceAdjacencies = (function () {
  53403. function FaceAdjacencies() {
  53404. this.edges = new Array();
  53405. this.edgesConnectedCount = 0;
  53406. }
  53407. return FaceAdjacencies;
  53408. }());
  53409. var EdgesRenderer = (function () {
  53410. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  53411. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  53412. if (epsilon === void 0) { epsilon = 0.95; }
  53413. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  53414. this.edgesWidthScalerForOrthographic = 1000.0;
  53415. this.edgesWidthScalerForPerspective = 50.0;
  53416. this._linesPositions = new Array();
  53417. this._linesNormals = new Array();
  53418. this._linesIndices = new Array();
  53419. this._buffers = {};
  53420. this._checkVerticesInsteadOfIndices = false;
  53421. this._source = source;
  53422. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  53423. this._epsilon = epsilon;
  53424. this._prepareRessources();
  53425. this._generateEdgesLines();
  53426. }
  53427. EdgesRenderer.prototype._prepareRessources = function () {
  53428. if (this._lineShader) {
  53429. return;
  53430. }
  53431. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  53432. attributes: ["position", "normal"],
  53433. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  53434. });
  53435. this._lineShader.disableDepthWrite = true;
  53436. this._lineShader.backFaceCulling = false;
  53437. };
  53438. EdgesRenderer.prototype.dispose = function () {
  53439. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  53440. if (buffer) {
  53441. buffer.dispose();
  53442. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  53443. }
  53444. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  53445. if (buffer) {
  53446. buffer.dispose();
  53447. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  53448. }
  53449. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  53450. this._lineShader.dispose();
  53451. };
  53452. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  53453. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  53454. return 0;
  53455. }
  53456. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  53457. return 1;
  53458. }
  53459. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  53460. return 2;
  53461. }
  53462. return -1;
  53463. };
  53464. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  53465. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  53466. return 0;
  53467. }
  53468. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  53469. return 1;
  53470. }
  53471. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  53472. return 2;
  53473. }
  53474. return -1;
  53475. };
  53476. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  53477. var needToCreateLine;
  53478. if (edge === undefined) {
  53479. needToCreateLine = true;
  53480. }
  53481. else {
  53482. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  53483. needToCreateLine = dotProduct < this._epsilon;
  53484. }
  53485. if (needToCreateLine) {
  53486. var offset = this._linesPositions.length / 3;
  53487. var normal = p0.subtract(p1);
  53488. normal.normalize();
  53489. // Positions
  53490. this._linesPositions.push(p0.x);
  53491. this._linesPositions.push(p0.y);
  53492. this._linesPositions.push(p0.z);
  53493. this._linesPositions.push(p0.x);
  53494. this._linesPositions.push(p0.y);
  53495. this._linesPositions.push(p0.z);
  53496. this._linesPositions.push(p1.x);
  53497. this._linesPositions.push(p1.y);
  53498. this._linesPositions.push(p1.z);
  53499. this._linesPositions.push(p1.x);
  53500. this._linesPositions.push(p1.y);
  53501. this._linesPositions.push(p1.z);
  53502. // Normals
  53503. this._linesNormals.push(p1.x);
  53504. this._linesNormals.push(p1.y);
  53505. this._linesNormals.push(p1.z);
  53506. this._linesNormals.push(-1);
  53507. this._linesNormals.push(p1.x);
  53508. this._linesNormals.push(p1.y);
  53509. this._linesNormals.push(p1.z);
  53510. this._linesNormals.push(1);
  53511. this._linesNormals.push(p0.x);
  53512. this._linesNormals.push(p0.y);
  53513. this._linesNormals.push(p0.z);
  53514. this._linesNormals.push(-1);
  53515. this._linesNormals.push(p0.x);
  53516. this._linesNormals.push(p0.y);
  53517. this._linesNormals.push(p0.z);
  53518. this._linesNormals.push(1);
  53519. // Indices
  53520. this._linesIndices.push(offset);
  53521. this._linesIndices.push(offset + 1);
  53522. this._linesIndices.push(offset + 2);
  53523. this._linesIndices.push(offset);
  53524. this._linesIndices.push(offset + 2);
  53525. this._linesIndices.push(offset + 3);
  53526. }
  53527. };
  53528. EdgesRenderer.prototype._generateEdgesLines = function () {
  53529. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53530. var indices = this._source.getIndices();
  53531. // First let's find adjacencies
  53532. var adjacencies = new Array();
  53533. var faceNormals = new Array();
  53534. var index;
  53535. var faceAdjacencies;
  53536. // Prepare faces
  53537. for (index = 0; index < indices.length; index += 3) {
  53538. faceAdjacencies = new FaceAdjacencies();
  53539. var p0Index = indices[index];
  53540. var p1Index = indices[index + 1];
  53541. var p2Index = indices[index + 2];
  53542. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  53543. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  53544. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  53545. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  53546. faceNormal.normalize();
  53547. faceNormals.push(faceNormal);
  53548. adjacencies.push(faceAdjacencies);
  53549. }
  53550. // Scan
  53551. for (index = 0; index < adjacencies.length; index++) {
  53552. faceAdjacencies = adjacencies[index];
  53553. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  53554. var otherFaceAdjacencies = adjacencies[otherIndex];
  53555. if (faceAdjacencies.edgesConnectedCount === 3) {
  53556. break;
  53557. }
  53558. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  53559. continue;
  53560. }
  53561. var otherP0 = indices[otherIndex * 3];
  53562. var otherP1 = indices[otherIndex * 3 + 1];
  53563. var otherP2 = indices[otherIndex * 3 + 2];
  53564. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  53565. var otherEdgeIndex;
  53566. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  53567. continue;
  53568. }
  53569. switch (edgeIndex) {
  53570. case 0:
  53571. if (this._checkVerticesInsteadOfIndices) {
  53572. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53573. }
  53574. else {
  53575. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  53576. }
  53577. break;
  53578. case 1:
  53579. if (this._checkVerticesInsteadOfIndices) {
  53580. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53581. }
  53582. else {
  53583. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  53584. }
  53585. break;
  53586. case 2:
  53587. if (this._checkVerticesInsteadOfIndices) {
  53588. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53589. }
  53590. else {
  53591. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  53592. }
  53593. break;
  53594. }
  53595. if (otherEdgeIndex === -1) {
  53596. continue;
  53597. }
  53598. faceAdjacencies.edges[edgeIndex] = otherIndex;
  53599. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  53600. faceAdjacencies.edgesConnectedCount++;
  53601. otherFaceAdjacencies.edgesConnectedCount++;
  53602. if (faceAdjacencies.edgesConnectedCount === 3) {
  53603. break;
  53604. }
  53605. }
  53606. }
  53607. }
  53608. // Create lines
  53609. for (index = 0; index < adjacencies.length; index++) {
  53610. // 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
  53611. var current = adjacencies[index];
  53612. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  53613. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  53614. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  53615. }
  53616. // Merge into a single mesh
  53617. var engine = this._source.getScene().getEngine();
  53618. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  53619. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  53620. this._ib = engine.createIndexBuffer(this._linesIndices);
  53621. this._indicesCount = this._linesIndices.length;
  53622. };
  53623. EdgesRenderer.prototype.render = function () {
  53624. if (!this._lineShader.isReady()) {
  53625. return;
  53626. }
  53627. var scene = this._source.getScene();
  53628. var engine = scene.getEngine();
  53629. this._lineShader._preBind();
  53630. // VBOs
  53631. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  53632. scene.resetCachedMaterial();
  53633. this._lineShader.setColor4("color", this._source.edgesColor);
  53634. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  53635. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  53636. }
  53637. else {
  53638. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  53639. }
  53640. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  53641. this._lineShader.bind(this._source.getWorldMatrix());
  53642. // Draw order
  53643. engine.draw(true, 0, this._indicesCount);
  53644. this._lineShader.unbind();
  53645. engine.setDepthWrite(true);
  53646. };
  53647. return EdgesRenderer;
  53648. }());
  53649. BABYLON.EdgesRenderer = EdgesRenderer;
  53650. })(BABYLON || (BABYLON = {}));
  53651. //# sourceMappingURL=babylon.edgesRenderer.js.map
  53652. var BABYLON;
  53653. (function (BABYLON) {
  53654. var TonemappingOperator;
  53655. (function (TonemappingOperator) {
  53656. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  53657. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  53658. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  53659. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  53660. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  53661. ;
  53662. var TonemapPostProcess = (function (_super) {
  53663. __extends(TonemapPostProcess, _super);
  53664. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  53665. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53666. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53667. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  53668. _this._operator = _operator;
  53669. _this.exposureAdjustment = exposureAdjustment;
  53670. var defines = "#define ";
  53671. if (_this._operator === TonemappingOperator.Hable)
  53672. defines += "HABLE_TONEMAPPING";
  53673. else if (_this._operator === TonemappingOperator.Reinhard)
  53674. defines += "REINHARD_TONEMAPPING";
  53675. else if (_this._operator === TonemappingOperator.HejiDawson)
  53676. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  53677. else if (_this._operator === TonemappingOperator.Photographic)
  53678. defines += "PHOTOGRAPHIC_TONEMAPPING";
  53679. //sadly a second call to create the effect.
  53680. _this.updateEffect(defines);
  53681. _this.onApply = function (effect) {
  53682. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  53683. };
  53684. return _this;
  53685. }
  53686. return TonemapPostProcess;
  53687. }(BABYLON.PostProcess));
  53688. BABYLON.TonemapPostProcess = TonemapPostProcess;
  53689. })(BABYLON || (BABYLON = {}));
  53690. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  53691. var BABYLON;
  53692. (function (BABYLON) {
  53693. var ReflectionProbe = (function () {
  53694. function ReflectionProbe(name, size, scene, generateMipMaps) {
  53695. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53696. var _this = this;
  53697. this.name = name;
  53698. this._viewMatrix = BABYLON.Matrix.Identity();
  53699. this._target = BABYLON.Vector3.Zero();
  53700. this._add = BABYLON.Vector3.Zero();
  53701. this.invertYAxis = false;
  53702. this.position = BABYLON.Vector3.Zero();
  53703. this._scene = scene;
  53704. this._scene.reflectionProbes.push(this);
  53705. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  53706. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  53707. switch (faceIndex) {
  53708. case 0:
  53709. _this._add.copyFromFloats(1, 0, 0);
  53710. break;
  53711. case 1:
  53712. _this._add.copyFromFloats(-1, 0, 0);
  53713. break;
  53714. case 2:
  53715. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  53716. break;
  53717. case 3:
  53718. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  53719. break;
  53720. case 4:
  53721. _this._add.copyFromFloats(0, 0, 1);
  53722. break;
  53723. case 5:
  53724. _this._add.copyFromFloats(0, 0, -1);
  53725. break;
  53726. }
  53727. if (_this._attachedMesh) {
  53728. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  53729. }
  53730. _this.position.addToRef(_this._add, _this._target);
  53731. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  53732. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  53733. });
  53734. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  53735. scene.updateTransformMatrix(true);
  53736. });
  53737. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  53738. }
  53739. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  53740. get: function () {
  53741. return this._renderTargetTexture.samples;
  53742. },
  53743. set: function (value) {
  53744. this._renderTargetTexture.samples = value;
  53745. },
  53746. enumerable: true,
  53747. configurable: true
  53748. });
  53749. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  53750. get: function () {
  53751. return this._renderTargetTexture.refreshRate;
  53752. },
  53753. set: function (value) {
  53754. this._renderTargetTexture.refreshRate = value;
  53755. },
  53756. enumerable: true,
  53757. configurable: true
  53758. });
  53759. ReflectionProbe.prototype.getScene = function () {
  53760. return this._scene;
  53761. };
  53762. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  53763. get: function () {
  53764. return this._renderTargetTexture;
  53765. },
  53766. enumerable: true,
  53767. configurable: true
  53768. });
  53769. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  53770. get: function () {
  53771. return this._renderTargetTexture.renderList;
  53772. },
  53773. enumerable: true,
  53774. configurable: true
  53775. });
  53776. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  53777. this._attachedMesh = mesh;
  53778. };
  53779. ReflectionProbe.prototype.dispose = function () {
  53780. var index = this._scene.reflectionProbes.indexOf(this);
  53781. if (index !== -1) {
  53782. // Remove from the scene if found
  53783. this._scene.reflectionProbes.splice(index, 1);
  53784. }
  53785. if (this._renderTargetTexture) {
  53786. this._renderTargetTexture.dispose();
  53787. this._renderTargetTexture = null;
  53788. }
  53789. };
  53790. return ReflectionProbe;
  53791. }());
  53792. BABYLON.ReflectionProbe = ReflectionProbe;
  53793. })(BABYLON || (BABYLON = {}));
  53794. //# sourceMappingURL=babylon.reflectionProbe.js.map
  53795. var BABYLON;
  53796. (function (BABYLON) {
  53797. var SolidParticle = (function () {
  53798. /**
  53799. * Creates a Solid Particle object.
  53800. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53801. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53802. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53803. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  53804. * `shapeId` (integer) is the model shape identifier in the SPS.
  53805. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53806. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  53807. */
  53808. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53809. this.idx = 0; // particle global index
  53810. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  53811. this.position = BABYLON.Vector3.Zero(); // position
  53812. this.rotation = BABYLON.Vector3.Zero(); // rotation
  53813. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  53814. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  53815. this.velocity = BABYLON.Vector3.Zero(); // velocity
  53816. this.alive = true; // alive
  53817. this.isVisible = true; // visibility
  53818. this._pos = 0; // index of this particle in the global "positions" array
  53819. this.shapeId = 0; // model shape id
  53820. this.idxInShape = 0; // index of the particle in its shape id
  53821. this.idx = particleIndex;
  53822. this._pos = positionIndex;
  53823. this._model = model;
  53824. this.shapeId = shapeId;
  53825. this.idxInShape = idxInShape;
  53826. this._sps = sps;
  53827. if (modelBoundingInfo) {
  53828. this._modelBoundingInfo = modelBoundingInfo;
  53829. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53830. }
  53831. }
  53832. Object.defineProperty(SolidParticle.prototype, "scale", {
  53833. /**
  53834. * legacy support, changed scale to scaling
  53835. */
  53836. get: function () {
  53837. return this.scaling;
  53838. },
  53839. set: function (scale) {
  53840. this.scaling = scale;
  53841. },
  53842. enumerable: true,
  53843. configurable: true
  53844. });
  53845. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53846. /**
  53847. * legacy support, changed quaternion to rotationQuaternion
  53848. */
  53849. get: function () {
  53850. return this.rotationQuaternion;
  53851. },
  53852. set: function (q) {
  53853. this.rotationQuaternion = q;
  53854. },
  53855. enumerable: true,
  53856. configurable: true
  53857. });
  53858. /**
  53859. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53860. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53861. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  53862. */
  53863. SolidParticle.prototype.intersectsMesh = function (target) {
  53864. if (!this._boundingInfo || !target._boundingInfo) {
  53865. return false;
  53866. }
  53867. if (this._sps._bSphereOnly) {
  53868. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53869. }
  53870. return this._boundingInfo.intersects(target._boundingInfo, false);
  53871. };
  53872. return SolidParticle;
  53873. }());
  53874. BABYLON.SolidParticle = SolidParticle;
  53875. var ModelShape = (function () {
  53876. /**
  53877. * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
  53878. * SPS internal tool, don't use it manually.
  53879. */
  53880. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  53881. this.shapeID = id;
  53882. this._shape = shape;
  53883. this._shapeUV = shapeUV;
  53884. this._positionFunction = posFunction;
  53885. this._vertexFunction = vtxFunction;
  53886. }
  53887. return ModelShape;
  53888. }());
  53889. BABYLON.ModelShape = ModelShape;
  53890. })(BABYLON || (BABYLON = {}));
  53891. //# sourceMappingURL=babylon.solidParticle.js.map
  53892. var BABYLON;
  53893. (function (BABYLON) {
  53894. /**
  53895. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53896. */
  53897. var SolidParticleSystem = (function () {
  53898. /**
  53899. * Creates a SPS (Solid Particle System) object.
  53900. * `name` (String) is the SPS name, this will be the underlying mesh name.
  53901. * `scene` (Scene) is the scene in which the SPS is added.
  53902. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  53903. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  53904. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  53905. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53906. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53907. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53908. */
  53909. function SolidParticleSystem(name, scene, options) {
  53910. // public members
  53911. /**
  53912. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53913. * Example : var p = SPS.particles[i];
  53914. */
  53915. this.particles = new Array();
  53916. /**
  53917. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53918. */
  53919. this.nbParticles = 0;
  53920. /**
  53921. * If the particles must ever face the camera (default false). Useful for planar particles.
  53922. */
  53923. this.billboard = false;
  53924. /**
  53925. * Recompute normals when adding a shape
  53926. */
  53927. this.recomputeNormals = true;
  53928. /**
  53929. * This a counter ofr your own usage. It's not set by any SPS functions.
  53930. */
  53931. this.counter = 0;
  53932. /**
  53933. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53934. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53935. */
  53936. this.vars = {};
  53937. this._positions = new Array();
  53938. this._indices = new Array();
  53939. this._normals = new Array();
  53940. this._colors = new Array();
  53941. this._uvs = new Array();
  53942. this._index = 0; // indices index
  53943. this._updatable = true;
  53944. this._pickable = false;
  53945. this._isVisibilityBoxLocked = false;
  53946. this._alwaysVisible = false;
  53947. this._shapeCounter = 0;
  53948. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  53949. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53950. this._computeParticleColor = true;
  53951. this._computeParticleTexture = true;
  53952. this._computeParticleRotation = true;
  53953. this._computeParticleVertex = false;
  53954. this._computeBoundingBox = false;
  53955. this._cam_axisZ = BABYLON.Vector3.Zero();
  53956. this._cam_axisY = BABYLON.Vector3.Zero();
  53957. this._cam_axisX = BABYLON.Vector3.Zero();
  53958. this._axisX = BABYLON.Axis.X;
  53959. this._axisY = BABYLON.Axis.Y;
  53960. this._axisZ = BABYLON.Axis.Z;
  53961. this._camDir = BABYLON.Vector3.Zero();
  53962. this._rotMatrix = new BABYLON.Matrix();
  53963. this._invertMatrix = new BABYLON.Matrix();
  53964. this._rotated = BABYLON.Vector3.Zero();
  53965. this._quaternion = new BABYLON.Quaternion();
  53966. this._vertex = BABYLON.Vector3.Zero();
  53967. this._normal = BABYLON.Vector3.Zero();
  53968. this._yaw = 0.0;
  53969. this._pitch = 0.0;
  53970. this._roll = 0.0;
  53971. this._halfroll = 0.0;
  53972. this._halfpitch = 0.0;
  53973. this._halfyaw = 0.0;
  53974. this._sinRoll = 0.0;
  53975. this._cosRoll = 0.0;
  53976. this._sinPitch = 0.0;
  53977. this._cosPitch = 0.0;
  53978. this._sinYaw = 0.0;
  53979. this._cosYaw = 0.0;
  53980. this._w = 0.0;
  53981. this._mustUnrotateFixedNormals = false;
  53982. this._minimum = BABYLON.Tmp.Vector3[0];
  53983. this._maximum = BABYLON.Tmp.Vector3[1];
  53984. this._scale = BABYLON.Tmp.Vector3[2];
  53985. this._translation = BABYLON.Tmp.Vector3[3];
  53986. this._minBbox = BABYLON.Tmp.Vector3[4];
  53987. this._maxBbox = BABYLON.Tmp.Vector3[5];
  53988. this._particlesIntersect = false;
  53989. this._bSphereOnly = false;
  53990. this._bSphereRadiusFactor = 1.0;
  53991. this.name = name;
  53992. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53993. this._camera = scene.activeCamera;
  53994. this._pickable = options ? options.isPickable : false;
  53995. this._particlesIntersect = options ? options.particleIntersection : false;
  53996. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53997. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53998. if (options && options.updatable) {
  53999. this._updatable = options.updatable;
  54000. }
  54001. else {
  54002. this._updatable = true;
  54003. }
  54004. if (this._pickable) {
  54005. this.pickedParticles = [];
  54006. }
  54007. }
  54008. /**
  54009. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54010. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54011. */
  54012. SolidParticleSystem.prototype.buildMesh = function () {
  54013. if (this.nbParticles === 0) {
  54014. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54015. this.addShape(triangle, 1);
  54016. triangle.dispose();
  54017. }
  54018. this._positions32 = new Float32Array(this._positions);
  54019. this._uvs32 = new Float32Array(this._uvs);
  54020. this._colors32 = new Float32Array(this._colors);
  54021. if (this.recomputeNormals) {
  54022. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  54023. }
  54024. this._normals32 = new Float32Array(this._normals);
  54025. this._fixedNormal32 = new Float32Array(this._normals);
  54026. if (this._mustUnrotateFixedNormals) {
  54027. this._unrotateFixedNormals();
  54028. }
  54029. var vertexData = new BABYLON.VertexData();
  54030. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54031. vertexData.indices = this._indices;
  54032. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54033. if (this._uvs32) {
  54034. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54035. ;
  54036. }
  54037. if (this._colors32) {
  54038. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54039. }
  54040. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54041. vertexData.applyToMesh(mesh, this._updatable);
  54042. this.mesh = mesh;
  54043. this.mesh.isPickable = this._pickable;
  54044. // free memory
  54045. this._positions = null;
  54046. this._normals = null;
  54047. this._uvs = null;
  54048. this._colors = null;
  54049. if (!this._updatable) {
  54050. this.particles.length = 0;
  54051. }
  54052. return mesh;
  54053. };
  54054. /**
  54055. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54056. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54057. * Thus the particles generated from `digest()` have their property `position` set yet.
  54058. * `mesh` ( Mesh ) is the mesh to be digested
  54059. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  54060. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54061. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54062. */
  54063. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54064. var size = (options && options.facetNb) || 1;
  54065. var number = (options && options.number);
  54066. var delta = (options && options.delta) || 0;
  54067. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54068. var meshInd = mesh.getIndices();
  54069. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54070. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54071. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54072. var f = 0; // facet counter
  54073. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54074. // compute size from number
  54075. if (number) {
  54076. number = (number > totalFacets) ? totalFacets : number;
  54077. size = Math.round(totalFacets / number);
  54078. delta = 0;
  54079. }
  54080. else {
  54081. size = (size > totalFacets) ? totalFacets : size;
  54082. }
  54083. var facetPos = []; // submesh positions
  54084. var facetInd = []; // submesh indices
  54085. var facetUV = []; // submesh UV
  54086. var facetCol = []; // submesh colors
  54087. var barycenter = BABYLON.Tmp.Vector3[0];
  54088. var rand;
  54089. var sizeO = size;
  54090. while (f < totalFacets) {
  54091. size = sizeO + Math.floor((1 + delta) * Math.random());
  54092. if (f > totalFacets - size) {
  54093. size = totalFacets - f;
  54094. }
  54095. // reset temp arrays
  54096. facetPos.length = 0;
  54097. facetInd.length = 0;
  54098. facetUV.length = 0;
  54099. facetCol.length = 0;
  54100. // iterate over "size" facets
  54101. var fi = 0;
  54102. for (var j = f * 3; j < (f + size) * 3; j++) {
  54103. facetInd.push(fi);
  54104. var i = meshInd[j];
  54105. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54106. if (meshUV) {
  54107. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54108. }
  54109. if (meshCol) {
  54110. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54111. }
  54112. fi++;
  54113. }
  54114. // create a model shape for each single particle
  54115. var idx = this.nbParticles;
  54116. var shape = this._posToShape(facetPos);
  54117. var shapeUV = this._uvsToShapeUV(facetUV);
  54118. // compute the barycenter of the shape
  54119. var v;
  54120. for (v = 0; v < shape.length; v++) {
  54121. barycenter.addInPlace(shape[v]);
  54122. }
  54123. barycenter.scaleInPlace(1 / shape.length);
  54124. // shift the shape from its barycenter to the origin
  54125. for (v = 0; v < shape.length; v++) {
  54126. shape[v].subtractInPlace(barycenter);
  54127. }
  54128. var bInfo;
  54129. if (this._particlesIntersect) {
  54130. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54131. }
  54132. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  54133. // add the particle in the SPS
  54134. var currentPos = this._positions.length;
  54135. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54136. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  54137. // initialize the particle position
  54138. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54139. this._index += shape.length;
  54140. idx++;
  54141. this.nbParticles++;
  54142. this._shapeCounter++;
  54143. f += size;
  54144. }
  54145. return this;
  54146. };
  54147. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54148. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54149. var index = 0;
  54150. var idx = 0;
  54151. for (var p = 0; p < this.particles.length; p++) {
  54152. this._particle = this.particles[p];
  54153. this._shape = this._particle._model._shape;
  54154. if (this._particle.rotationQuaternion) {
  54155. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54156. }
  54157. else {
  54158. this._yaw = this._particle.rotation.y;
  54159. this._pitch = this._particle.rotation.x;
  54160. this._roll = this._particle.rotation.z;
  54161. this._quaternionRotationYPR();
  54162. }
  54163. this._quaternionToRotationMatrix();
  54164. this._rotMatrix.invertToRef(this._invertMatrix);
  54165. for (var pt = 0; pt < this._shape.length; pt++) {
  54166. idx = index + pt * 3;
  54167. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54168. this._fixedNormal32[idx] = this._normal.x;
  54169. this._fixedNormal32[idx + 1] = this._normal.y;
  54170. this._fixedNormal32[idx + 2] = this._normal.z;
  54171. }
  54172. index = idx + 3;
  54173. }
  54174. };
  54175. //reset copy
  54176. SolidParticleSystem.prototype._resetCopy = function () {
  54177. this._copy.position.x = 0;
  54178. this._copy.position.y = 0;
  54179. this._copy.position.z = 0;
  54180. this._copy.rotation.x = 0;
  54181. this._copy.rotation.y = 0;
  54182. this._copy.rotation.z = 0;
  54183. this._copy.rotationQuaternion = null;
  54184. this._copy.scaling.x = 1;
  54185. this._copy.scaling.y = 1;
  54186. this._copy.scaling.z = 1;
  54187. this._copy.uvs.x = 0;
  54188. this._copy.uvs.y = 0;
  54189. this._copy.uvs.z = 1;
  54190. this._copy.uvs.w = 1;
  54191. this._copy.color = null;
  54192. };
  54193. // _meshBuilder : inserts the shape model in the global SPS mesh
  54194. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54195. var i;
  54196. var u = 0;
  54197. var c = 0;
  54198. var n = 0;
  54199. this._resetCopy();
  54200. if (options && options.positionFunction) {
  54201. options.positionFunction(this._copy, idx, idxInShape);
  54202. this._mustUnrotateFixedNormals = true;
  54203. }
  54204. if (this._copy.rotationQuaternion) {
  54205. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54206. }
  54207. else {
  54208. this._yaw = this._copy.rotation.y;
  54209. this._pitch = this._copy.rotation.x;
  54210. this._roll = this._copy.rotation.z;
  54211. this._quaternionRotationYPR();
  54212. }
  54213. this._quaternionToRotationMatrix();
  54214. for (i = 0; i < shape.length; i++) {
  54215. this._vertex.x = shape[i].x;
  54216. this._vertex.y = shape[i].y;
  54217. this._vertex.z = shape[i].z;
  54218. if (options && options.vertexFunction) {
  54219. options.vertexFunction(this._copy, this._vertex, i);
  54220. }
  54221. this._vertex.x *= this._copy.scaling.x;
  54222. this._vertex.y *= this._copy.scaling.y;
  54223. this._vertex.z *= this._copy.scaling.z;
  54224. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54225. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54226. if (meshUV) {
  54227. 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);
  54228. u += 2;
  54229. }
  54230. if (this._copy.color) {
  54231. this._color = this._copy.color;
  54232. }
  54233. else if (meshCol && meshCol[c] !== undefined) {
  54234. this._color.r = meshCol[c];
  54235. this._color.g = meshCol[c + 1];
  54236. this._color.b = meshCol[c + 2];
  54237. this._color.a = meshCol[c + 3];
  54238. }
  54239. else {
  54240. this._color.r = 1;
  54241. this._color.g = 1;
  54242. this._color.b = 1;
  54243. this._color.a = 1;
  54244. }
  54245. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54246. c += 4;
  54247. if (!this.recomputeNormals && meshNor) {
  54248. this._normal.x = meshNor[n];
  54249. this._normal.y = meshNor[n + 1];
  54250. this._normal.z = meshNor[n + 2];
  54251. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54252. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54253. n += 3;
  54254. }
  54255. }
  54256. for (i = 0; i < meshInd.length; i++) {
  54257. indices.push(p + meshInd[i]);
  54258. }
  54259. if (this._pickable) {
  54260. var nbfaces = meshInd.length / 3;
  54261. for (i = 0; i < nbfaces; i++) {
  54262. this.pickedParticles.push({ idx: idx, faceId: i });
  54263. }
  54264. }
  54265. return this._copy;
  54266. };
  54267. // returns a shape array from positions array
  54268. SolidParticleSystem.prototype._posToShape = function (positions) {
  54269. var shape = [];
  54270. for (var i = 0; i < positions.length; i += 3) {
  54271. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54272. }
  54273. return shape;
  54274. };
  54275. // returns a shapeUV array from a Vector4 uvs
  54276. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54277. var shapeUV = [];
  54278. if (uvs) {
  54279. for (var i = 0; i < uvs.length; i++)
  54280. shapeUV.push(uvs[i]);
  54281. }
  54282. return shapeUV;
  54283. };
  54284. // adds a new particle object in the particles array
  54285. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  54286. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  54287. this.particles.push(sp);
  54288. return sp;
  54289. };
  54290. /**
  54291. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54292. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54293. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  54294. * `nb` (positive integer) the number of particles to be created from this model
  54295. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  54296. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  54297. */
  54298. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54299. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54300. var meshInd = mesh.getIndices();
  54301. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54302. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54303. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54304. var bbInfo;
  54305. if (this._particlesIntersect) {
  54306. bbInfo = mesh.getBoundingInfo();
  54307. }
  54308. var shape = this._posToShape(meshPos);
  54309. var shapeUV = this._uvsToShapeUV(meshUV);
  54310. var posfunc = options ? options.positionFunction : null;
  54311. var vtxfunc = options ? options.vertexFunction : null;
  54312. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  54313. // particles
  54314. var sp;
  54315. var currentCopy;
  54316. var idx = this.nbParticles;
  54317. for (var i = 0; i < nb; i++) {
  54318. var currentPos = this._positions.length;
  54319. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54320. if (this._updatable) {
  54321. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  54322. sp.position.copyFrom(currentCopy.position);
  54323. sp.rotation.copyFrom(currentCopy.rotation);
  54324. if (currentCopy.rotationQuaternion) {
  54325. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54326. }
  54327. if (currentCopy.color) {
  54328. sp.color.copyFrom(currentCopy.color);
  54329. }
  54330. sp.scaling.copyFrom(currentCopy.scaling);
  54331. sp.uvs.copyFrom(currentCopy.uvs);
  54332. }
  54333. this._index += shape.length;
  54334. idx++;
  54335. }
  54336. this.nbParticles += nb;
  54337. this._shapeCounter++;
  54338. return this._shapeCounter - 1;
  54339. };
  54340. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54341. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54342. this._resetCopy();
  54343. if (particle._model._positionFunction) {
  54344. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54345. }
  54346. if (this._copy.rotationQuaternion) {
  54347. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54348. }
  54349. else {
  54350. this._yaw = this._copy.rotation.y;
  54351. this._pitch = this._copy.rotation.x;
  54352. this._roll = this._copy.rotation.z;
  54353. this._quaternionRotationYPR();
  54354. }
  54355. this._quaternionToRotationMatrix();
  54356. this._shape = particle._model._shape;
  54357. for (var pt = 0; pt < this._shape.length; pt++) {
  54358. this._vertex.x = this._shape[pt].x;
  54359. this._vertex.y = this._shape[pt].y;
  54360. this._vertex.z = this._shape[pt].z;
  54361. if (particle._model._vertexFunction) {
  54362. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54363. }
  54364. this._vertex.x *= this._copy.scaling.x;
  54365. this._vertex.y *= this._copy.scaling.y;
  54366. this._vertex.z *= this._copy.scaling.z;
  54367. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54368. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54369. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54370. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54371. }
  54372. particle.position.x = 0.0;
  54373. particle.position.y = 0.0;
  54374. particle.position.z = 0.0;
  54375. particle.rotation.x = 0.0;
  54376. particle.rotation.y = 0.0;
  54377. particle.rotation.z = 0.0;
  54378. particle.rotationQuaternion = null;
  54379. particle.scaling.x = 1.0;
  54380. particle.scaling.y = 1.0;
  54381. particle.scaling.z = 1.0;
  54382. };
  54383. /**
  54384. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54385. * Returns the SPS.
  54386. */
  54387. SolidParticleSystem.prototype.rebuildMesh = function () {
  54388. for (var p = 0; p < this.particles.length; p++) {
  54389. this._rebuildParticle(this.particles[p]);
  54390. }
  54391. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54392. return this;
  54393. };
  54394. /**
  54395. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54396. * This method calls `updateParticle()` for each particle of the SPS.
  54397. * For an animated SPS, it is usually called within the render loop.
  54398. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54399. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54400. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54401. * Returns the SPS.
  54402. */
  54403. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54404. if (start === void 0) { start = 0; }
  54405. if (end === void 0) { end = this.nbParticles - 1; }
  54406. if (update === void 0) { update = true; }
  54407. if (!this._updatable) {
  54408. return;
  54409. }
  54410. // custom beforeUpdate
  54411. this.beforeUpdateParticles(start, end, update);
  54412. this._cam_axisX.x = 1.0;
  54413. this._cam_axisX.y = 0.0;
  54414. this._cam_axisX.z = 0.0;
  54415. this._cam_axisY.x = 0.0;
  54416. this._cam_axisY.y = 1.0;
  54417. this._cam_axisY.z = 0.0;
  54418. this._cam_axisZ.x = 0.0;
  54419. this._cam_axisZ.y = 0.0;
  54420. this._cam_axisZ.z = 1.0;
  54421. // if the particles will always face the camera
  54422. if (this.billboard) {
  54423. this.mesh.computeWorldMatrix(true);
  54424. // compute the camera position and un-rotate it by the current mesh rotation
  54425. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  54426. this._quaternionToRotationMatrix();
  54427. this._rotMatrix.invertToRef(this._invertMatrix);
  54428. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  54429. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54430. this._cam_axisZ.normalize();
  54431. // same for camera up vector extracted from the cam view matrix
  54432. var view = this._camera.getViewMatrix(true);
  54433. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54434. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54435. this._cam_axisY.normalize();
  54436. this._cam_axisX.normalize();
  54437. }
  54438. }
  54439. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54440. var idx = 0; // current position index in the global array positions32
  54441. var index = 0; // position start index in the global array positions32 of the current particle
  54442. var colidx = 0; // current color index in the global array colors32
  54443. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54444. var uvidx = 0; // current uv index in the global array uvs32
  54445. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54446. var pt = 0; // current index in the particle model shape
  54447. if (this.mesh.isFacetDataEnabled) {
  54448. this._computeBoundingBox = true;
  54449. }
  54450. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54451. if (this._computeBoundingBox) {
  54452. if (start == 0 && end == this.nbParticles - 1) {
  54453. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54454. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54455. }
  54456. else {
  54457. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54458. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54459. }
  54460. }
  54461. // particle loop
  54462. index = this.particles[start]._pos;
  54463. var vpos = (index / 3) | 0;
  54464. colorIndex = vpos * 4;
  54465. uvIndex = vpos * 2;
  54466. for (var p = start; p <= end; p++) {
  54467. this._particle = this.particles[p];
  54468. this._shape = this._particle._model._shape;
  54469. this._shapeUV = this._particle._model._shapeUV;
  54470. // call to custom user function to update the particle properties
  54471. this.updateParticle(this._particle);
  54472. if (this._particle.isVisible) {
  54473. // particle rotation matrix
  54474. if (this.billboard) {
  54475. this._particle.rotation.x = 0.0;
  54476. this._particle.rotation.y = 0.0;
  54477. }
  54478. if (this._computeParticleRotation || this.billboard) {
  54479. if (this._particle.rotationQuaternion) {
  54480. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54481. }
  54482. else {
  54483. this._yaw = this._particle.rotation.y;
  54484. this._pitch = this._particle.rotation.x;
  54485. this._roll = this._particle.rotation.z;
  54486. this._quaternionRotationYPR();
  54487. }
  54488. this._quaternionToRotationMatrix();
  54489. }
  54490. // particle vertex loop
  54491. for (pt = 0; pt < this._shape.length; pt++) {
  54492. idx = index + pt * 3;
  54493. colidx = colorIndex + pt * 4;
  54494. uvidx = uvIndex + pt * 2;
  54495. this._vertex.x = this._shape[pt].x;
  54496. this._vertex.y = this._shape[pt].y;
  54497. this._vertex.z = this._shape[pt].z;
  54498. if (this._computeParticleVertex) {
  54499. this.updateParticleVertex(this._particle, this._vertex, pt);
  54500. }
  54501. // positions
  54502. this._vertex.x *= this._particle.scaling.x;
  54503. this._vertex.y *= this._particle.scaling.y;
  54504. this._vertex.z *= this._particle.scaling.z;
  54505. 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];
  54506. 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;
  54507. 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;
  54508. 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;
  54509. 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;
  54510. 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;
  54511. 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;
  54512. if (this._computeBoundingBox) {
  54513. if (this._positions32[idx] < this._minimum.x) {
  54514. this._minimum.x = this._positions32[idx];
  54515. }
  54516. if (this._positions32[idx] > this._maximum.x) {
  54517. this._maximum.x = this._positions32[idx];
  54518. }
  54519. if (this._positions32[idx + 1] < this._minimum.y) {
  54520. this._minimum.y = this._positions32[idx + 1];
  54521. }
  54522. if (this._positions32[idx + 1] > this._maximum.y) {
  54523. this._maximum.y = this._positions32[idx + 1];
  54524. }
  54525. if (this._positions32[idx + 2] < this._minimum.z) {
  54526. this._minimum.z = this._positions32[idx + 2];
  54527. }
  54528. if (this._positions32[idx + 2] > this._maximum.z) {
  54529. this._maximum.z = this._positions32[idx + 2];
  54530. }
  54531. }
  54532. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54533. if (!this._computeParticleVertex) {
  54534. this._normal.x = this._fixedNormal32[idx];
  54535. this._normal.y = this._fixedNormal32[idx + 1];
  54536. this._normal.z = this._fixedNormal32[idx + 2];
  54537. 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]);
  54538. 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]);
  54539. 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]);
  54540. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54541. 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;
  54542. 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;
  54543. }
  54544. if (this._computeParticleColor) {
  54545. this._colors32[colidx] = this._particle.color.r;
  54546. this._colors32[colidx + 1] = this._particle.color.g;
  54547. this._colors32[colidx + 2] = this._particle.color.b;
  54548. this._colors32[colidx + 3] = this._particle.color.a;
  54549. }
  54550. if (this._computeParticleTexture) {
  54551. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54552. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54553. }
  54554. }
  54555. }
  54556. else {
  54557. for (pt = 0; pt < this._shape.length; pt++) {
  54558. idx = index + pt * 3;
  54559. colidx = colorIndex + pt * 4;
  54560. uvidx = uvIndex + pt * 2;
  54561. this._positions32[idx] = this._camera.position.x;
  54562. this._positions32[idx + 1] = this._camera.position.y;
  54563. this._positions32[idx + 2] = this._camera.position.z;
  54564. this._normals32[idx] = 0.0;
  54565. this._normals32[idx + 1] = 0.0;
  54566. this._normals32[idx + 2] = 0.0;
  54567. if (this._computeParticleColor) {
  54568. this._colors32[colidx] = this._particle.color.r;
  54569. this._colors32[colidx + 1] = this._particle.color.g;
  54570. this._colors32[colidx + 2] = this._particle.color.b;
  54571. this._colors32[colidx + 3] = this._particle.color.a;
  54572. }
  54573. if (this._computeParticleTexture) {
  54574. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54575. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54576. }
  54577. }
  54578. }
  54579. // if the particle intersections must be computed : update the bbInfo
  54580. if (this._particlesIntersect) {
  54581. var bInfo = this._particle._boundingInfo;
  54582. var bBox = bInfo.boundingBox;
  54583. var bSphere = bInfo.boundingSphere;
  54584. if (!this._bSphereOnly) {
  54585. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54586. for (var b = 0; b < bBox.vectors.length; b++) {
  54587. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54588. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54589. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54590. 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];
  54591. 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;
  54592. 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;
  54593. 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;
  54594. bBox.vectors[b].x = 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;
  54595. bBox.vectors[b].y = 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;
  54596. bBox.vectors[b].z = 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;
  54597. }
  54598. bBox._update(this.mesh._worldMatrix);
  54599. }
  54600. // place and scale the particle bouding sphere in the SPS local system, then update it
  54601. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54602. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54603. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54604. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54605. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54606. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54607. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54608. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54609. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54610. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  54611. bSphere._update(this.mesh._worldMatrix);
  54612. }
  54613. // increment indexes for the next particle
  54614. index = idx + 3;
  54615. colorIndex = colidx + 4;
  54616. uvIndex = uvidx + 2;
  54617. }
  54618. // if the VBO must be updated
  54619. if (update) {
  54620. if (this._computeParticleColor) {
  54621. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54622. }
  54623. if (this._computeParticleTexture) {
  54624. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54625. }
  54626. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54627. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54628. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54629. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54630. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54631. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  54632. for (var i = 0; i < this._normals32.length; i++) {
  54633. this._fixedNormal32[i] = this._normals32[i];
  54634. }
  54635. }
  54636. if (!this.mesh.areNormalsFrozen) {
  54637. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54638. }
  54639. }
  54640. }
  54641. if (this._computeBoundingBox) {
  54642. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54643. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54644. }
  54645. this.afterUpdateParticles(start, end, update);
  54646. return this;
  54647. };
  54648. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54649. this._halfroll = this._roll * 0.5;
  54650. this._halfpitch = this._pitch * 0.5;
  54651. this._halfyaw = this._yaw * 0.5;
  54652. this._sinRoll = Math.sin(this._halfroll);
  54653. this._cosRoll = Math.cos(this._halfroll);
  54654. this._sinPitch = Math.sin(this._halfpitch);
  54655. this._cosPitch = Math.cos(this._halfpitch);
  54656. this._sinYaw = Math.sin(this._halfyaw);
  54657. this._cosYaw = Math.cos(this._halfyaw);
  54658. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  54659. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  54660. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  54661. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  54662. };
  54663. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54664. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54665. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54666. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54667. this._rotMatrix.m[3] = 0;
  54668. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54669. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54670. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54671. this._rotMatrix.m[7] = 0;
  54672. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54673. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54674. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54675. this._rotMatrix.m[11] = 0;
  54676. this._rotMatrix.m[12] = 0;
  54677. this._rotMatrix.m[13] = 0;
  54678. this._rotMatrix.m[14] = 0;
  54679. this._rotMatrix.m[15] = 1.0;
  54680. };
  54681. /**
  54682. * Disposes the SPS.
  54683. * Returns nothing.
  54684. */
  54685. SolidParticleSystem.prototype.dispose = function () {
  54686. this.mesh.dispose();
  54687. this.vars = null;
  54688. // drop references to internal big arrays for the GC
  54689. this._positions = null;
  54690. this._indices = null;
  54691. this._normals = null;
  54692. this._uvs = null;
  54693. this._colors = null;
  54694. this._positions32 = null;
  54695. this._normals32 = null;
  54696. this._fixedNormal32 = null;
  54697. this._uvs32 = null;
  54698. this._colors32 = null;
  54699. this.pickedParticles = null;
  54700. };
  54701. /**
  54702. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54703. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54704. * Returns the SPS.
  54705. */
  54706. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54707. if (!this._isVisibilityBoxLocked) {
  54708. this.mesh.refreshBoundingInfo();
  54709. }
  54710. return this;
  54711. };
  54712. /**
  54713. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54714. * @param size the size (float) of the visibility box
  54715. * note : this doesn't lock the SPS mesh bounding box.
  54716. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54717. */
  54718. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54719. var vis = size / 2;
  54720. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54721. };
  54722. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54723. // getter and setter
  54724. get: function () {
  54725. return this._alwaysVisible;
  54726. },
  54727. /**
  54728. * Sets the SPS as always visible or not
  54729. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54730. */
  54731. set: function (val) {
  54732. this._alwaysVisible = val;
  54733. this.mesh.alwaysSelectAsActiveMesh = val;
  54734. },
  54735. enumerable: true,
  54736. configurable: true
  54737. });
  54738. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54739. get: function () {
  54740. return this._isVisibilityBoxLocked;
  54741. },
  54742. /**
  54743. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54744. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54745. */
  54746. set: function (val) {
  54747. this._isVisibilityBoxLocked = val;
  54748. this.mesh.getBoundingInfo().isLocked = val;
  54749. },
  54750. enumerable: true,
  54751. configurable: true
  54752. });
  54753. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54754. // getters
  54755. get: function () {
  54756. return this._computeParticleRotation;
  54757. },
  54758. // Optimizer setters
  54759. /**
  54760. * Tells to `setParticles()` to compute the particle rotations or not.
  54761. * Default value : true. The SPS is faster when it's set to false.
  54762. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54763. */
  54764. set: function (val) {
  54765. this._computeParticleRotation = val;
  54766. },
  54767. enumerable: true,
  54768. configurable: true
  54769. });
  54770. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54771. get: function () {
  54772. return this._computeParticleColor;
  54773. },
  54774. /**
  54775. * Tells to `setParticles()` to compute the particle colors or not.
  54776. * Default value : true. The SPS is faster when it's set to false.
  54777. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54778. */
  54779. set: function (val) {
  54780. this._computeParticleColor = val;
  54781. },
  54782. enumerable: true,
  54783. configurable: true
  54784. });
  54785. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54786. get: function () {
  54787. return this._computeParticleTexture;
  54788. },
  54789. /**
  54790. * Tells to `setParticles()` to compute the particle textures or not.
  54791. * Default value : true. The SPS is faster when it's set to false.
  54792. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54793. */
  54794. set: function (val) {
  54795. this._computeParticleTexture = val;
  54796. },
  54797. enumerable: true,
  54798. configurable: true
  54799. });
  54800. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54801. get: function () {
  54802. return this._computeParticleVertex;
  54803. },
  54804. /**
  54805. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54806. * Default value : false. The SPS is faster when it's set to false.
  54807. * Note : the particle custom vertex positions aren't stored values.
  54808. */
  54809. set: function (val) {
  54810. this._computeParticleVertex = val;
  54811. },
  54812. enumerable: true,
  54813. configurable: true
  54814. });
  54815. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54816. get: function () {
  54817. return this._computeBoundingBox;
  54818. },
  54819. /**
  54820. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54821. */
  54822. set: function (val) {
  54823. this._computeBoundingBox = val;
  54824. },
  54825. enumerable: true,
  54826. configurable: true
  54827. });
  54828. // =======================================================================
  54829. // Particle behavior logic
  54830. // these following methods may be overwritten by the user to fit his needs
  54831. /**
  54832. * This function does nothing. It may be overwritten to set all the particle first values.
  54833. * The SPS doesn't call this function, you may have to call it by your own.
  54834. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54835. */
  54836. SolidParticleSystem.prototype.initParticles = function () {
  54837. };
  54838. /**
  54839. * This function does nothing. It may be overwritten to recycle a particle.
  54840. * The SPS doesn't call this function, you may have to call it by your own.
  54841. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54842. */
  54843. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54844. return particle;
  54845. };
  54846. /**
  54847. * Updates a particle : this function should be overwritten by the user.
  54848. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54849. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54850. * ex : just set a particle position or velocity and recycle conditions
  54851. */
  54852. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54853. return particle;
  54854. };
  54855. /**
  54856. * Updates a vertex of a particle : it can be overwritten by the user.
  54857. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54858. * @param particle the current particle
  54859. * @param vertex the current index of the current particle
  54860. * @param pt the index of the current vertex in the particle shape
  54861. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54862. * ex : just set a vertex particle position
  54863. */
  54864. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54865. return vertex;
  54866. };
  54867. /**
  54868. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54869. * This does nothing and may be overwritten by the user.
  54870. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54871. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54872. * @param update the boolean update value actually passed to setParticles()
  54873. */
  54874. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54875. };
  54876. /**
  54877. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54878. * This will be passed three parameters.
  54879. * This does nothing and may be overwritten by the user.
  54880. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54881. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54882. * @param update the boolean update value actually passed to setParticles()
  54883. */
  54884. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54885. };
  54886. return SolidParticleSystem;
  54887. }());
  54888. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54889. })(BABYLON || (BABYLON = {}));
  54890. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54891. var BABYLON;
  54892. (function (BABYLON) {
  54893. var Internals;
  54894. (function (Internals) {
  54895. var FileFaceOrientation = (function () {
  54896. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  54897. this.name = name;
  54898. this.worldAxisForNormal = worldAxisForNormal;
  54899. this.worldAxisForFileX = worldAxisForFileX;
  54900. this.worldAxisForFileY = worldAxisForFileY;
  54901. }
  54902. return FileFaceOrientation;
  54903. }());
  54904. ;
  54905. /**
  54906. * Helper class dealing with the extraction of spherical polynomial dataArray
  54907. * from a cube map.
  54908. */
  54909. var CubeMapToSphericalPolynomialTools = (function () {
  54910. function CubeMapToSphericalPolynomialTools() {
  54911. }
  54912. /**
  54913. * Converts a cubemap to the according Spherical Polynomial data.
  54914. * This extracts the first 3 orders only as they are the only one used in the lighting.
  54915. *
  54916. * @param cubeInfo The Cube map to extract the information from.
  54917. * @return The Spherical Polynomial data.
  54918. */
  54919. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  54920. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  54921. var totalSolidAngle = 0.0;
  54922. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  54923. var du = 2.0 / cubeInfo.size;
  54924. var dv = du;
  54925. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  54926. var minUV = du * 0.5 - 1.0;
  54927. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54928. var fileFace = this.FileFaces[faceIndex];
  54929. var dataArray = cubeInfo[fileFace.name];
  54930. var v = minUV;
  54931. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  54932. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  54933. // Because SP is still linear, so summation is fine in that basis.
  54934. for (var y = 0; y < cubeInfo.size; y++) {
  54935. var u = minUV;
  54936. for (var x = 0; x < cubeInfo.size; x++) {
  54937. // World direction (not normalised)
  54938. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  54939. worldDirection.normalize();
  54940. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  54941. if (1) {
  54942. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  54943. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  54944. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  54945. var color = new BABYLON.Color3(r, g, b);
  54946. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54947. }
  54948. else {
  54949. if (faceIndex == 0) {
  54950. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54951. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54952. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54953. }
  54954. else if (faceIndex == 1) {
  54955. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54956. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54957. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54958. }
  54959. else if (faceIndex == 2) {
  54960. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54961. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54962. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54963. }
  54964. else if (faceIndex == 3) {
  54965. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54966. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54967. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54968. }
  54969. else if (faceIndex == 4) {
  54970. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54971. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54972. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54973. }
  54974. else if (faceIndex == 5) {
  54975. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54976. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54977. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54978. }
  54979. 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]);
  54980. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54981. }
  54982. totalSolidAngle += deltaSolidAngle;
  54983. u += du;
  54984. }
  54985. v += dv;
  54986. }
  54987. }
  54988. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  54989. var correction = correctSolidAngle / totalSolidAngle;
  54990. sphericalHarmonics.scale(correction);
  54991. // Additionally scale by pi -- audit needed
  54992. sphericalHarmonics.scale(1.0 / Math.PI);
  54993. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  54994. };
  54995. return CubeMapToSphericalPolynomialTools;
  54996. }());
  54997. CubeMapToSphericalPolynomialTools.FileFaces = [
  54998. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  54999. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  55000. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  55001. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  55002. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  55003. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  55004. ];
  55005. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  55006. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55007. })(BABYLON || (BABYLON = {}));
  55008. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  55009. var BABYLON;
  55010. (function (BABYLON) {
  55011. var Internals;
  55012. (function (Internals) {
  55013. /**
  55014. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  55015. */
  55016. var PanoramaToCubeMapTools = (function () {
  55017. function PanoramaToCubeMapTools() {
  55018. }
  55019. /**
  55020. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  55021. *
  55022. * @param float32Array The source data.
  55023. * @param inputWidth The width of the input panorama.
  55024. * @param inputhHeight The height of the input panorama.
  55025. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  55026. * @return The cubemap data
  55027. */
  55028. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  55029. if (!float32Array) {
  55030. throw "ConvertPanoramaToCubemap: input cannot be null";
  55031. }
  55032. if (float32Array.length != inputWidth * inputHeight * 3) {
  55033. throw "ConvertPanoramaToCubemap: input size is wrong";
  55034. }
  55035. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  55036. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  55037. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  55038. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  55039. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  55040. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  55041. return {
  55042. front: textureFront,
  55043. back: textureBack,
  55044. left: textureLeft,
  55045. right: textureRight,
  55046. up: textureUp,
  55047. down: textureDown,
  55048. size: size
  55049. };
  55050. };
  55051. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  55052. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  55053. var textureArray = new Float32Array(buffer);
  55054. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  55055. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  55056. var dy = 1 / texSize;
  55057. var fy = 0;
  55058. for (var y = 0; y < texSize; y++) {
  55059. var xv1 = faceData[0];
  55060. var xv2 = faceData[2];
  55061. for (var x = 0; x < texSize; x++) {
  55062. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  55063. v.normalize();
  55064. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  55065. // 3 channels per pixels
  55066. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  55067. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  55068. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  55069. xv1 = xv1.add(rotDX1);
  55070. xv2 = xv2.add(rotDX2);
  55071. }
  55072. fy += dy;
  55073. }
  55074. return textureArray;
  55075. };
  55076. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  55077. var theta = Math.atan2(vDir.z, vDir.x);
  55078. var phi = Math.acos(vDir.y);
  55079. while (theta < -Math.PI)
  55080. theta += 2 * Math.PI;
  55081. while (theta > Math.PI)
  55082. theta -= 2 * Math.PI;
  55083. var dx = theta / Math.PI;
  55084. var dy = phi / Math.PI;
  55085. // recenter.
  55086. dx = dx * 0.5 + 0.5;
  55087. var px = Math.round(dx * inputWidth);
  55088. if (px < 0)
  55089. px = 0;
  55090. else if (px >= inputWidth)
  55091. px = inputWidth - 1;
  55092. var py = Math.round(dy * inputHeight);
  55093. if (py < 0)
  55094. py = 0;
  55095. else if (py >= inputHeight)
  55096. py = inputHeight - 1;
  55097. var inputY = (inputHeight - py - 1);
  55098. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  55099. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  55100. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  55101. return {
  55102. r: r,
  55103. g: g,
  55104. b: b
  55105. };
  55106. };
  55107. return PanoramaToCubeMapTools;
  55108. }());
  55109. PanoramaToCubeMapTools.FACE_FRONT = [
  55110. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55111. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55112. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55113. new BABYLON.Vector3(1.0, 1.0, -1.0)
  55114. ];
  55115. PanoramaToCubeMapTools.FACE_BACK = [
  55116. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55117. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55118. new BABYLON.Vector3(1.0, 1.0, 1.0),
  55119. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  55120. ];
  55121. PanoramaToCubeMapTools.FACE_RIGHT = [
  55122. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55123. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55124. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55125. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55126. ];
  55127. PanoramaToCubeMapTools.FACE_LEFT = [
  55128. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55129. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55130. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55131. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  55132. ];
  55133. PanoramaToCubeMapTools.FACE_DOWN = [
  55134. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55135. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55136. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55137. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55138. ];
  55139. PanoramaToCubeMapTools.FACE_UP = [
  55140. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55141. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55142. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55143. new BABYLON.Vector3(1.0, -1.0, -1.0)
  55144. ];
  55145. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  55146. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55147. })(BABYLON || (BABYLON = {}));
  55148. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  55149. var BABYLON;
  55150. (function (BABYLON) {
  55151. var Internals;
  55152. (function (Internals) {
  55153. ;
  55154. /**
  55155. * This groups tools to convert HDR texture to native colors array.
  55156. */
  55157. var HDRTools = (function () {
  55158. function HDRTools() {
  55159. }
  55160. HDRTools.Ldexp = function (mantissa, exponent) {
  55161. if (exponent > 1023) {
  55162. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  55163. }
  55164. if (exponent < -1074) {
  55165. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  55166. }
  55167. return mantissa * Math.pow(2, exponent);
  55168. };
  55169. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  55170. if (exponent > 0) {
  55171. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  55172. float32array[index + 0] = red * exponent;
  55173. float32array[index + 1] = green * exponent;
  55174. float32array[index + 2] = blue * exponent;
  55175. }
  55176. else {
  55177. float32array[index + 0] = 0;
  55178. float32array[index + 1] = 0;
  55179. float32array[index + 2] = 0;
  55180. }
  55181. };
  55182. HDRTools.readStringLine = function (uint8array, startIndex) {
  55183. var line = "";
  55184. var character = "";
  55185. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  55186. character = String.fromCharCode(uint8array[i]);
  55187. if (character == "\n") {
  55188. break;
  55189. }
  55190. line += character;
  55191. }
  55192. return line;
  55193. };
  55194. /**
  55195. * Reads header information from an RGBE texture stored in a native array.
  55196. * More information on this format are available here:
  55197. * https://en.wikipedia.org/wiki/RGBE_image_format
  55198. *
  55199. * @param uint8array The binary file stored in native array.
  55200. * @return The header information.
  55201. */
  55202. HDRTools.RGBE_ReadHeader = function (uint8array) {
  55203. var height = 0;
  55204. var width = 0;
  55205. var line = this.readStringLine(uint8array, 0);
  55206. if (line[0] != '#' || line[1] != '?') {
  55207. throw "Bad HDR Format.";
  55208. }
  55209. var endOfHeader = false;
  55210. var findFormat = false;
  55211. var lineIndex = 0;
  55212. do {
  55213. lineIndex += (line.length + 1);
  55214. line = this.readStringLine(uint8array, lineIndex);
  55215. if (line == "FORMAT=32-bit_rle_rgbe") {
  55216. findFormat = true;
  55217. }
  55218. else if (line.length == 0) {
  55219. endOfHeader = true;
  55220. }
  55221. } while (!endOfHeader);
  55222. if (!findFormat) {
  55223. throw "HDR Bad header format, unsupported FORMAT";
  55224. }
  55225. lineIndex += (line.length + 1);
  55226. line = this.readStringLine(uint8array, lineIndex);
  55227. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  55228. var match = sizeRegexp.exec(line);
  55229. // TODO. Support +Y and -X if needed.
  55230. if (match.length < 3) {
  55231. throw "HDR Bad header format, no size";
  55232. }
  55233. width = parseInt(match[2]);
  55234. height = parseInt(match[1]);
  55235. if (width < 8 || width > 0x7fff) {
  55236. throw "HDR Bad header format, unsupported size";
  55237. }
  55238. lineIndex += (line.length + 1);
  55239. return {
  55240. height: height,
  55241. width: width,
  55242. dataPosition: lineIndex
  55243. };
  55244. };
  55245. /**
  55246. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  55247. * This RGBE texture needs to store the information as a panorama.
  55248. *
  55249. * More information on this format are available here:
  55250. * https://en.wikipedia.org/wiki/RGBE_image_format
  55251. *
  55252. * @param buffer The binary file stored in an array buffer.
  55253. * @param size The expected size of the extracted cubemap.
  55254. * @return The Cube Map information.
  55255. */
  55256. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  55257. var uint8array = new Uint8Array(buffer);
  55258. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  55259. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55260. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  55261. return cubeMapData;
  55262. };
  55263. /**
  55264. * Returns the pixels data extracted from an RGBE texture.
  55265. * This pixels will be stored left to right up to down in the R G B order in one array.
  55266. *
  55267. * More information on this format are available here:
  55268. * https://en.wikipedia.org/wiki/RGBE_image_format
  55269. *
  55270. * @param uint8array The binary file stored in an array buffer.
  55271. * @param hdrInfo The header information of the file.
  55272. * @return The pixels data in RGB right to left up to down order.
  55273. */
  55274. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  55275. // Keep for multi format supports.
  55276. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55277. };
  55278. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  55279. var num_scanlines = hdrInfo.height;
  55280. var scanline_width = hdrInfo.width;
  55281. var a, b, c, d, count;
  55282. var dataIndex = hdrInfo.dataPosition;
  55283. var index = 0, endIndex = 0, i = 0;
  55284. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  55285. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  55286. // 3 channels of 4 bytes per pixel in float.
  55287. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  55288. var resultArray = new Float32Array(resultBuffer);
  55289. // read in each successive scanline
  55290. while (num_scanlines > 0) {
  55291. a = uint8array[dataIndex++];
  55292. b = uint8array[dataIndex++];
  55293. c = uint8array[dataIndex++];
  55294. d = uint8array[dataIndex++];
  55295. if (a != 2 || b != 2 || (c & 0x80)) {
  55296. // this file is not run length encoded
  55297. throw "HDR Bad header format, not RLE";
  55298. }
  55299. if (((c << 8) | d) != scanline_width) {
  55300. throw "HDR Bad header format, wrong scan line width";
  55301. }
  55302. index = 0;
  55303. // read each of the four channels for the scanline into the buffer
  55304. for (i = 0; i < 4; i++) {
  55305. endIndex = (i + 1) * scanline_width;
  55306. while (index < endIndex) {
  55307. a = uint8array[dataIndex++];
  55308. b = uint8array[dataIndex++];
  55309. if (a > 128) {
  55310. // a run of the same value
  55311. count = a - 128;
  55312. if ((count == 0) || (count > endIndex - index)) {
  55313. throw "HDR Bad Format, bad scanline data (run)";
  55314. }
  55315. while (count-- > 0) {
  55316. scanLineArray[index++] = b;
  55317. }
  55318. }
  55319. else {
  55320. // a non-run
  55321. count = a;
  55322. if ((count == 0) || (count > endIndex - index)) {
  55323. throw "HDR Bad Format, bad scanline data (non-run)";
  55324. }
  55325. scanLineArray[index++] = b;
  55326. if (--count > 0) {
  55327. for (var j = 0; j < count; j++) {
  55328. scanLineArray[index++] = uint8array[dataIndex++];
  55329. }
  55330. }
  55331. }
  55332. }
  55333. }
  55334. // now convert data from buffer into floats
  55335. for (i = 0; i < scanline_width; i++) {
  55336. a = scanLineArray[i];
  55337. b = scanLineArray[i + scanline_width];
  55338. c = scanLineArray[i + 2 * scanline_width];
  55339. d = scanLineArray[i + 3 * scanline_width];
  55340. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  55341. }
  55342. num_scanlines--;
  55343. }
  55344. return resultArray;
  55345. };
  55346. return HDRTools;
  55347. }());
  55348. Internals.HDRTools = HDRTools;
  55349. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55350. })(BABYLON || (BABYLON = {}));
  55351. //# sourceMappingURL=babylon.tools.hdr.js.map
  55352. //_______________________________________________________________
  55353. // Extracted from CubeMapGen:
  55354. // https://code.google.com/archive/p/cubemapgen/
  55355. //
  55356. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55357. //_______________________________________________________________
  55358. var BABYLON;
  55359. (function (BABYLON) {
  55360. var Internals;
  55361. (function (Internals) {
  55362. /**
  55363. * The bounding box information used during the conversion process.
  55364. */
  55365. var CMGBoundinBox = (function () {
  55366. function CMGBoundinBox() {
  55367. this.min = new BABYLON.Vector3(0, 0, 0);
  55368. this.max = new BABYLON.Vector3(0, 0, 0);
  55369. this.clear();
  55370. }
  55371. CMGBoundinBox.prototype.clear = function () {
  55372. this.min.x = CMGBoundinBox.MAX;
  55373. this.min.y = CMGBoundinBox.MAX;
  55374. this.min.z = CMGBoundinBox.MAX;
  55375. this.max.x = CMGBoundinBox.MIN;
  55376. this.max.y = CMGBoundinBox.MIN;
  55377. this.max.z = CMGBoundinBox.MIN;
  55378. };
  55379. CMGBoundinBox.prototype.augment = function (x, y, z) {
  55380. this.min.x = Math.min(this.min.x, x);
  55381. this.min.y = Math.min(this.min.y, y);
  55382. this.min.z = Math.min(this.min.z, z);
  55383. this.max.x = Math.max(this.max.x, x);
  55384. this.max.y = Math.max(this.max.y, y);
  55385. this.max.z = Math.max(this.max.z, z);
  55386. };
  55387. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  55388. this.min.x = Math.max(this.min.x, x);
  55389. this.min.y = Math.max(this.min.y, y);
  55390. this.min.z = Math.max(this.min.z, z);
  55391. };
  55392. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  55393. this.max.x = Math.min(this.max.x, x);
  55394. this.max.y = Math.min(this.max.y, y);
  55395. this.max.z = Math.min(this.max.z, z);
  55396. };
  55397. CMGBoundinBox.prototype.empty = function () {
  55398. if ((this.min.x > this.max.y) ||
  55399. (this.min.y > this.max.y) ||
  55400. (this.min.z > this.max.y)) {
  55401. return true;
  55402. }
  55403. else {
  55404. return false;
  55405. }
  55406. };
  55407. return CMGBoundinBox;
  55408. }());
  55409. CMGBoundinBox.MAX = Number.MAX_VALUE;
  55410. CMGBoundinBox.MIN = Number.MIN_VALUE;
  55411. /**
  55412. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  55413. * required by the glossinees of a material.
  55414. *
  55415. * This only supports the cosine drop power as well as Warp fixup generation method.
  55416. *
  55417. * This is using the process from CubeMapGen described here:
  55418. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55419. */
  55420. var PMREMGenerator = (function () {
  55421. /**
  55422. * Constructor of the generator.
  55423. *
  55424. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  55425. * @param inputSize The size of the cubemap faces
  55426. * @param outputSize The size of the output cubemap faces
  55427. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  55428. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  55429. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  55430. * @param specularPower The max specular level of the desired cubemap
  55431. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  55432. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  55433. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  55434. */
  55435. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  55436. this.input = input;
  55437. this.inputSize = inputSize;
  55438. this.outputSize = outputSize;
  55439. this.maxNumMipLevels = maxNumMipLevels;
  55440. this.numChannels = numChannels;
  55441. this.isFloat = isFloat;
  55442. this.specularPower = specularPower;
  55443. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  55444. this.excludeBase = excludeBase;
  55445. this.fixup = fixup;
  55446. this._outputSurface = [];
  55447. this._numMipLevels = 0;
  55448. }
  55449. /**
  55450. * Launches the filter process and return the result.
  55451. *
  55452. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  55453. */
  55454. PMREMGenerator.prototype.filterCubeMap = function () {
  55455. // Init cubemap processor
  55456. this.init();
  55457. // Filters the cubemap
  55458. this.filterCubeMapMipChain();
  55459. // Returns the filtered mips.
  55460. return this._outputSurface;
  55461. };
  55462. PMREMGenerator.prototype.init = function () {
  55463. var i;
  55464. var j;
  55465. var mipLevelSize;
  55466. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  55467. if (this.maxNumMipLevels == 0) {
  55468. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  55469. }
  55470. //first miplevel size
  55471. mipLevelSize = this.outputSize;
  55472. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  55473. for (j = 0; j < this.maxNumMipLevels; j++) {
  55474. this._outputSurface.length++;
  55475. this._outputSurface[j] = [];
  55476. //Iterate over faces for output images
  55477. for (i = 0; i < 6; i++) {
  55478. this._outputSurface[j].length++;
  55479. // Initializes a new array for the output.
  55480. if (this.isFloat) {
  55481. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55482. }
  55483. else {
  55484. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55485. }
  55486. }
  55487. //next mip level is half size
  55488. mipLevelSize >>= 1;
  55489. this._numMipLevels++;
  55490. //terminate if mip chain becomes too small
  55491. if (mipLevelSize == 0) {
  55492. this.maxNumMipLevels = j;
  55493. return;
  55494. }
  55495. }
  55496. };
  55497. //--------------------------------------------------------------------------------------
  55498. //Cube map filtering and mip chain generation.
  55499. // the cube map filtereing is specified using a number of parameters:
  55500. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  55501. // indicates the region of the hemisphere to filter over for each tap.
  55502. //
  55503. // Note that the top mip level is also a filtered version of the original input images
  55504. // as well in order to create mip chains for diffuse environment illumination.
  55505. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  55506. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  55507. //
  55508. // Then the mip angle used to genreate the next level of the mip chain from the first level
  55509. // is a_InitialMipAngle
  55510. //
  55511. // The angle for the subsequent levels of the mip chain are specified by their parents
  55512. // filtering angle and a per-level scale and bias
  55513. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  55514. //
  55515. //--------------------------------------------------------------------------------------
  55516. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  55517. // First, take count of the lighting model to modify SpecularPower
  55518. // 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;
  55519. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  55520. //Cone angle start (for generating subsequent mip levels)
  55521. var currentSpecularPower = this.specularPower;
  55522. //Build filter lookup tables based on the source miplevel size
  55523. this.precomputeFilterLookupTables(this.inputSize);
  55524. // Note that we need to filter the first level before generating mipmap
  55525. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  55526. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  55527. // TODO : Write a function to copy and scale the base mipmap in output
  55528. // I am just lazy here and just put a high specular power value, and do some if.
  55529. if (this.excludeBase && (levelIndex == 0)) {
  55530. // 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).
  55531. currentSpecularPower = 100000.0;
  55532. }
  55533. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  55534. var srcCubeImage = this.input;
  55535. var dstCubeImage = this._outputSurface[levelIndex];
  55536. var dstSize = this.outputSize >> levelIndex;
  55537. // Compute required angle.
  55538. var angle = this.getBaseFilterAngle(currentSpecularPower);
  55539. // filter cube surfaces
  55540. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  55541. // fix seams
  55542. if (this.fixup) {
  55543. this.fixupCubeEdges(dstCubeImage, dstSize);
  55544. }
  55545. // Decrease the specular power to generate the mipmap chain
  55546. // TODO : Use another method for Exclude (see first comment at start of the function
  55547. if (this.excludeBase && (levelIndex == 0)) {
  55548. currentSpecularPower = this.specularPower;
  55549. }
  55550. currentSpecularPower *= this.cosinePowerDropPerMip;
  55551. }
  55552. };
  55553. //--------------------------------------------------------------------------------------
  55554. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  55555. // It allow to optimize the texel to access base on the specular power.
  55556. //--------------------------------------------------------------------------------------
  55557. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  55558. // We want to find the alpha such that:
  55559. // cos(alpha)^cosinePower = epsilon
  55560. // That's: acos(epsilon^(1/cosinePower))
  55561. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  55562. var angle = 180.0;
  55563. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  55564. angle *= 180.0 / Math.PI; // Convert to degree
  55565. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  55566. return angle;
  55567. };
  55568. //--------------------------------------------------------------------------------------
  55569. //Builds the following lookup tables prior to filtering:
  55570. // -normalizer cube map
  55571. // -tap weight lookup table
  55572. //
  55573. //--------------------------------------------------------------------------------------
  55574. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  55575. var srcTexelAngle;
  55576. var iCubeFace;
  55577. //clear pre-existing normalizer cube map
  55578. this._normCubeMap = [];
  55579. //Normalized vectors per cubeface and per-texel solid angle
  55580. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  55581. };
  55582. //--------------------------------------------------------------------------------------
  55583. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  55584. //
  55585. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  55586. //
  55587. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  55588. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  55589. // below
  55590. //--------------------------------------------------------------------------------------
  55591. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  55592. var iCubeFace;
  55593. var u;
  55594. var v;
  55595. //iterate over cube faces
  55596. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55597. //First three channels for norm cube, and last channel for solid angle
  55598. this._normCubeMap.push(new Float32Array(size * size * 4));
  55599. //fast texture walk, build normalizer cube map
  55600. var facesData = this.input[iCubeFace];
  55601. for (v = 0; v < size; v++) {
  55602. for (u = 0; u < size; u++) {
  55603. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  55604. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  55605. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  55606. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  55607. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  55608. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  55609. }
  55610. }
  55611. }
  55612. };
  55613. //--------------------------------------------------------------------------------------
  55614. // Convert cubemap face texel coordinates and face idx to 3D vector
  55615. // note the U and V coords are integer coords and range from 0 to size-1
  55616. // this routine can be used to generate a normalizer cube map
  55617. //--------------------------------------------------------------------------------------
  55618. // SL BEGIN
  55619. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  55620. var nvcU;
  55621. var nvcV;
  55622. var tempVec;
  55623. // Change from original AMD code
  55624. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55625. // + 0.5f is for texel center addressing
  55626. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  55627. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  55628. // warp fixup
  55629. if (fixup && size > 1) {
  55630. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  55631. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  55632. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  55633. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  55634. }
  55635. // Get current vector
  55636. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  55637. // U contribution
  55638. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55639. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  55640. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  55641. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  55642. // V contribution and Sum
  55643. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55644. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  55645. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  55646. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  55647. //add face axis
  55648. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  55649. PMREMGenerator._vectorTemp.x += faceAxis[0];
  55650. PMREMGenerator._vectorTemp.y += faceAxis[1];
  55651. PMREMGenerator._vectorTemp.z += faceAxis[2];
  55652. //normalize vector
  55653. PMREMGenerator._vectorTemp.normalize();
  55654. return PMREMGenerator._vectorTemp;
  55655. };
  55656. //--------------------------------------------------------------------------------------
  55657. // Convert 3D vector to cubemap face texel coordinates and face idx
  55658. // note the U and V coords are integer coords and range from 0 to size-1
  55659. // this routine can be used to generate a normalizer cube map
  55660. //
  55661. // returns face IDX and texel coords
  55662. //--------------------------------------------------------------------------------------
  55663. // SL BEGIN
  55664. /*
  55665. Mapping Texture Coordinates to Cube Map Faces
  55666. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  55667. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  55668. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  55669. map arrangement in Pixar's RenderMan package.
  55670. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  55671. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  55672. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  55673. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  55674. the major axis direction). The target column in the table below explains how the major axis direction
  55675. maps to the 2D image of a particular cube map target.
  55676. major axis
  55677. direction target sc tc ma
  55678. ---------- --------------------------------- --- --- ---
  55679. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  55680. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  55681. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  55682. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  55683. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  55684. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  55685. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  55686. an updated (s,t) is calculated as follows
  55687. s = ( sc/|ma| + 1 ) / 2
  55688. t = ( tc/|ma| + 1 ) / 2
  55689. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  55690. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  55691. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  55692. */
  55693. // Note this method return U and V in range from 0 to size-1
  55694. // SL END
  55695. // Store the information in vector3 for convenience (faceindex, u, v)
  55696. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  55697. var maxCoord;
  55698. var faceIdx;
  55699. //absolute value 3
  55700. var absX = Math.abs(x);
  55701. var absY = Math.abs(y);
  55702. var absZ = Math.abs(z);
  55703. if (absX >= absY && absX >= absZ) {
  55704. maxCoord = absX;
  55705. if (x >= 0) {
  55706. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  55707. }
  55708. else {
  55709. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55710. }
  55711. }
  55712. else if (absY >= absX && absY >= absZ) {
  55713. maxCoord = absY;
  55714. if (y >= 0) {
  55715. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55716. }
  55717. else {
  55718. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55719. }
  55720. }
  55721. else {
  55722. maxCoord = absZ;
  55723. if (z >= 0) {
  55724. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55725. }
  55726. else {
  55727. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55728. }
  55729. }
  55730. //divide through by max coord so face vector lies on cube face
  55731. var scale = 1 / maxCoord;
  55732. x *= scale;
  55733. y *= scale;
  55734. z *= scale;
  55735. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55736. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  55737. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55738. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  55739. // Modify original AMD code to return value from 0 to Size - 1
  55740. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  55741. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  55742. PMREMGenerator._vectorTemp.x = faceIdx;
  55743. PMREMGenerator._vectorTemp.y = u;
  55744. PMREMGenerator._vectorTemp.z = v;
  55745. return PMREMGenerator._vectorTemp;
  55746. };
  55747. //--------------------------------------------------------------------------------------
  55748. //Original code from Ignacio CastaÒo
  55749. // This formula is from Manne ÷hrstrˆm's thesis.
  55750. // Take two coordiantes in the range [-1, 1] that define a portion of a
  55751. // cube face and return the area of the projection of that portion on the
  55752. // surface of the sphere.
  55753. //--------------------------------------------------------------------------------------
  55754. PMREMGenerator.prototype.areaElement = function (x, y) {
  55755. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  55756. };
  55757. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  55758. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55759. // (+ 0.5f is for texel center addressing)
  55760. u = (2.0 * (u + 0.5) / size) - 1.0;
  55761. v = (2.0 * (v + 0.5) / size) - 1.0;
  55762. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  55763. var invResolution = 1.0 / size;
  55764. // U and V are the -1..1 texture coordinate on the current face.
  55765. // Get projected area for this texel
  55766. var x0 = u - invResolution;
  55767. var y0 = v - invResolution;
  55768. var x1 = u + invResolution;
  55769. var y1 = v + invResolution;
  55770. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  55771. return solidAngle;
  55772. };
  55773. //--------------------------------------------------------------------------------------
  55774. //The key to the speed of these filtering routines is to quickly define a per-face
  55775. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  55776. // Later these pixels are selectively processed based on their dot products to see if
  55777. // they reside within the filtering cone.
  55778. //
  55779. //This is done by computing the smallest per-texel angle to get a conservative estimate
  55780. // of the number of texels needed to be covered in width and height order to filter the
  55781. // region. the bounding box for the center taps face is defined first, and if the
  55782. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  55783. // defined next
  55784. //--------------------------------------------------------------------------------------
  55785. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  55786. // note that pixels within these regions may be rejected
  55787. // based on the anlge
  55788. var iCubeFace;
  55789. var u;
  55790. var v;
  55791. // bounding box per face to specify region to process
  55792. var filterExtents = [];
  55793. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55794. filterExtents.push(new CMGBoundinBox());
  55795. }
  55796. // min angle a src texel can cover (in degrees)
  55797. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  55798. // angle about center tap to define filter cone
  55799. // filter angle is 1/2 the cone angle
  55800. var filterAngle = filterConeAngle / 2.0;
  55801. //ensure filter angle is larger than a texel
  55802. if (filterAngle < srcTexelAngle) {
  55803. filterAngle = srcTexelAngle;
  55804. }
  55805. //ensure filter cone is always smaller than the hemisphere
  55806. if (filterAngle > 90.0) {
  55807. filterAngle = 90.0;
  55808. }
  55809. // the maximum number of texels in 1D the filter cone angle will cover
  55810. // used to determine bounding box size for filter extents
  55811. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  55812. // ensure conservative region always covers at least one texel
  55813. if (filterSize < 1) {
  55814. filterSize = 1;
  55815. }
  55816. // dotProdThresh threshold based on cone angle to determine whether or not taps
  55817. // reside within the cone angle
  55818. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  55819. // process required faces
  55820. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55821. //iterate over dst cube map face texel
  55822. for (v = 0; v < dstSize; v++) {
  55823. for (u = 0; u < dstSize; u++) {
  55824. //get center tap direction
  55825. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  55826. //clear old per-face filter extents
  55827. this.clearFilterExtents(filterExtents);
  55828. //define per-face filter extents
  55829. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  55830. //perform filtering of src faces using filter extents
  55831. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  55832. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  55833. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  55834. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  55835. }
  55836. }
  55837. }
  55838. };
  55839. //--------------------------------------------------------------------------------------
  55840. //Clear filter extents for the 6 cube map faces
  55841. //--------------------------------------------------------------------------------------
  55842. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  55843. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  55844. filterExtents[iCubeFaces].clear();
  55845. }
  55846. };
  55847. //--------------------------------------------------------------------------------------
  55848. //Define per-face bounding box filter extents
  55849. //
  55850. // These define conservative texel regions in each of the faces the filter can possibly
  55851. // process. When the pixels in the regions are actually processed, the dot product
  55852. // between the tap vector and the center tap vector is used to determine the weight of
  55853. // the tap and whether or not the tap is within the cone.
  55854. //
  55855. //--------------------------------------------------------------------------------------
  55856. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  55857. //neighboring face and bleed over amount, and width of BBOX for
  55858. // left, right, top, and bottom edges of this face
  55859. var bleedOverAmount = [0, 0, 0, 0];
  55860. var bleedOverBBoxMin = [0, 0, 0, 0];
  55861. var bleedOverBBoxMax = [0, 0, 0, 0];
  55862. var neighborFace;
  55863. var neighborEdge;
  55864. var oppositeFaceIdx;
  55865. //get face idx, and u, v info from center tap dir
  55866. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  55867. var faceIdx = result.x;
  55868. var u = result.y;
  55869. var v = result.z;
  55870. //define bbox size within face
  55871. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  55872. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  55873. filterExtents[faceIdx].clampMin(0, 0, 0);
  55874. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  55875. //u and v extent in face corresponding to center tap
  55876. var minU = filterExtents[faceIdx].min.x;
  55877. var minV = filterExtents[faceIdx].min.y;
  55878. var maxU = filterExtents[faceIdx].max.x;
  55879. var maxV = filterExtents[faceIdx].max.y;
  55880. //bleed over amounts for face across u=0 edge (left)
  55881. bleedOverAmount[0] = (bboxSize - u);
  55882. bleedOverBBoxMin[0] = minV;
  55883. bleedOverBBoxMax[0] = maxV;
  55884. //bleed over amounts for face across u=1 edge (right)
  55885. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  55886. bleedOverBBoxMin[1] = minV;
  55887. bleedOverBBoxMax[1] = maxV;
  55888. //bleed over to face across v=0 edge (up)
  55889. bleedOverAmount[2] = (bboxSize - v);
  55890. bleedOverBBoxMin[2] = minU;
  55891. bleedOverBBoxMax[2] = maxU;
  55892. //bleed over to face across v=1 edge (down)
  55893. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  55894. bleedOverBBoxMin[3] = minU;
  55895. bleedOverBBoxMax[3] = maxU;
  55896. //compute bleed over regions in neighboring faces
  55897. for (var i = 0; i < 4; i++) {
  55898. if (bleedOverAmount[i] > 0) {
  55899. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  55900. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  55901. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  55902. // be flipped: the cases are
  55903. // if a left edge mates with a left or bottom edge on the neighbor
  55904. // if a top edge mates with a top or right edge on the neighbor
  55905. // if a right edge mates with a right or top edge on the neighbor
  55906. // if a bottom edge mates with a bottom or left edge on the neighbor
  55907. //Seeing as the edges are enumerated as follows
  55908. // left =0
  55909. // right =1
  55910. // top =2
  55911. // bottom =3
  55912. //
  55913. // so if the edge enums are the same, or the sum of the enums == 3,
  55914. // the bbox needs to be flipped
  55915. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  55916. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  55917. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  55918. }
  55919. //The way the bounding box is extended onto the neighboring face
  55920. // depends on which edge of neighboring face abuts with this one
  55921. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  55922. case PMREMGenerator.CP_EDGE_LEFT:
  55923. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  55924. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55925. break;
  55926. case PMREMGenerator.CP_EDGE_RIGHT:
  55927. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  55928. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55929. break;
  55930. case PMREMGenerator.CP_EDGE_TOP:
  55931. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  55932. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  55933. break;
  55934. case PMREMGenerator.CP_EDGE_BOTTOM:
  55935. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  55936. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  55937. break;
  55938. }
  55939. //clamp filter extents in non-center tap faces to remain within surface
  55940. filterExtents[neighborFace].clampMin(0, 0, 0);
  55941. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  55942. }
  55943. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  55944. // from the center tap face, then process the opposite face entirely for now.
  55945. //Note that the cases in which this happens, what usually happens is that
  55946. // more than one edge bleeds onto the opposite face, and the bounding box
  55947. // encompasses the entire cube map face.
  55948. if (bleedOverAmount[i] > srcSize) {
  55949. //determine opposite face
  55950. switch (faceIdx) {
  55951. case PMREMGenerator.CP_FACE_X_POS:
  55952. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55953. break;
  55954. case PMREMGenerator.CP_FACE_X_NEG:
  55955. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  55956. break;
  55957. case PMREMGenerator.CP_FACE_Y_POS:
  55958. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55959. break;
  55960. case PMREMGenerator.CP_FACE_Y_NEG:
  55961. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55962. break;
  55963. case PMREMGenerator.CP_FACE_Z_POS:
  55964. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55965. break;
  55966. case PMREMGenerator.CP_FACE_Z_NEG:
  55967. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55968. break;
  55969. default:
  55970. break;
  55971. }
  55972. //just encompass entire face for now
  55973. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  55974. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  55975. }
  55976. }
  55977. };
  55978. //--------------------------------------------------------------------------------------
  55979. //ProcessFilterExtents
  55980. // Process bounding box in each cube face
  55981. //
  55982. //--------------------------------------------------------------------------------------
  55983. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  55984. //accumulators are 64-bit floats in order to have the precision needed
  55985. // over a summation of a large number of pixels
  55986. var dstAccum = [0, 0, 0, 0];
  55987. var weightAccum = 0;
  55988. var k = 0;
  55989. var nSrcChannels = this.numChannels;
  55990. // norm cube map and srcCubeMap have same face width
  55991. var faceWidth = srcSize;
  55992. //amount to add to pointer to move to next scanline in images
  55993. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  55994. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  55995. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  55996. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  55997. // iterate over cubefaces
  55998. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  55999. //if bbox is non empty
  56000. if (!filterExtents[iFaceIdx].empty()) {
  56001. var uStart = filterExtents[iFaceIdx].min.x;
  56002. var vStart = filterExtents[iFaceIdx].min.y;
  56003. var uEnd = filterExtents[iFaceIdx].max.x;
  56004. var vEnd = filterExtents[iFaceIdx].max.y;
  56005. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  56006. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  56007. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  56008. for (var v = vStart; v <= vEnd; v++) {
  56009. var normCubeRowWalk = 0;
  56010. var srcCubeRowWalk = 0;
  56011. for (var u = uStart; u <= uEnd; u++) {
  56012. //pointer to direction in cube map associated with texel
  56013. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  56014. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  56015. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  56016. //check dot product to see if texel is within cone
  56017. var tapDotProd = texelVectX * centerTapDir.x +
  56018. texelVectY * centerTapDir.y +
  56019. texelVectZ * centerTapDir.z;
  56020. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  56021. //solid angle stored in 4th channel of normalizer/solid angle cube map
  56022. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  56023. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  56024. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  56025. // so just adding one to specularpower do the trick.
  56026. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  56027. //iterate over channels
  56028. for (k = 0; k < nSrcChannels; k++) {
  56029. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  56030. srcCubeRowWalk++;
  56031. }
  56032. weightAccum += weight; //accumulate weight
  56033. }
  56034. else {
  56035. //step across source pixel
  56036. srcCubeRowWalk += nSrcChannels;
  56037. }
  56038. normCubeRowWalk += 4; // 4 channels per norm cube map.
  56039. }
  56040. startIndexNormCubeMap += normCubePitch;
  56041. startIndexSrcCubeMap += srcCubePitch;
  56042. }
  56043. }
  56044. }
  56045. //divide through by weights if weight is non zero
  56046. if (weightAccum != 0.0) {
  56047. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  56048. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  56049. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  56050. if (this.numChannels > 3) {
  56051. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  56052. }
  56053. }
  56054. else {
  56055. // otherwise sample nearest
  56056. // get face idx and u, v texel coordinate in face
  56057. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  56058. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  56059. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  56060. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  56061. if (this.numChannels > 3) {
  56062. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  56063. }
  56064. }
  56065. return PMREMGenerator._vectorTemp;
  56066. };
  56067. //--------------------------------------------------------------------------------------
  56068. // Fixup cube edges
  56069. //
  56070. // average texels on cube map faces across the edges
  56071. // WARP/BENT Method Only.
  56072. //--------------------------------------------------------------------------------------
  56073. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  56074. var k;
  56075. var j;
  56076. var i;
  56077. var iFace;
  56078. var iCorner = 0;
  56079. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  56080. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  56081. // note that if functionality to filter across the three texels for each corner, then
  56082. //indexed by corner and face idx. the array contains the face the start points belongs to.
  56083. var cornerPtr = [
  56084. [[], [], []],
  56085. [[], [], []],
  56086. [[], [], []],
  56087. [[], [], []],
  56088. [[], [], []],
  56089. [[], [], []],
  56090. [[], [], []],
  56091. [[], [], []]
  56092. ];
  56093. //if there is no fixup, or fixup width = 0, do nothing
  56094. if (cubeMapSize < 1) {
  56095. return;
  56096. }
  56097. //special case 1x1 cubemap, average face colors
  56098. if (cubeMapSize == 1) {
  56099. //iterate over channels
  56100. for (k = 0; k < this.numChannels; k++) {
  56101. var accum = 0.0;
  56102. //iterate over faces to accumulate face colors
  56103. for (iFace = 0; iFace < 6; iFace++) {
  56104. accum += cubeMap[iFace][k];
  56105. }
  56106. //compute average over 6 face colors
  56107. accum /= 6.0;
  56108. //iterate over faces to distribute face colors
  56109. for (iFace = 0; iFace < 6; iFace++) {
  56110. cubeMap[iFace][k] = accum;
  56111. }
  56112. }
  56113. return;
  56114. }
  56115. //iterate over faces to collect list of corner texel pointers
  56116. for (iFace = 0; iFace < 6; iFace++) {
  56117. //the 4 corner pointers for this face
  56118. faceCornerStartIndicies[0] = [iFace, 0];
  56119. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  56120. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  56121. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  56122. //iterate over face corners to collect cube corner pointers
  56123. for (iCorner = 0; iCorner < 4; iCorner++) {
  56124. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  56125. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  56126. cornerNumPtrs[corner]++;
  56127. }
  56128. }
  56129. //iterate over corners to average across corner tap values
  56130. for (iCorner = 0; iCorner < 8; iCorner++) {
  56131. for (k = 0; k < this.numChannels; k++) {
  56132. var cornerTapAccum = 0.0;
  56133. //iterate over corner texels and average results
  56134. for (i = 0; i < 3; i++) {
  56135. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  56136. }
  56137. //divide by 3 to compute average of corner tap values
  56138. cornerTapAccum *= (1.0 / 3.0);
  56139. //iterate over corner texels and average results
  56140. for (i = 0; i < 3; i++) {
  56141. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  56142. }
  56143. }
  56144. }
  56145. //iterate over the twelve edges of the cube to average across edges
  56146. for (i = 0; i < 12; i++) {
  56147. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  56148. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  56149. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  56150. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  56151. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  56152. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  56153. var edgeWalk = 0;
  56154. var neighborEdgeWalk = 0;
  56155. //Determine walking pointers based on edge type
  56156. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  56157. switch (edge) {
  56158. case PMREMGenerator.CP_EDGE_LEFT:
  56159. // no change to faceEdgeStartPtr
  56160. edgeWalk = this.numChannels * cubeMapSize;
  56161. break;
  56162. case PMREMGenerator.CP_EDGE_RIGHT:
  56163. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56164. edgeWalk = this.numChannels * cubeMapSize;
  56165. break;
  56166. case PMREMGenerator.CP_EDGE_TOP:
  56167. // no change to faceEdgeStartPtr
  56168. edgeWalk = this.numChannels;
  56169. break;
  56170. case PMREMGenerator.CP_EDGE_BOTTOM:
  56171. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56172. edgeWalk = this.numChannels;
  56173. break;
  56174. }
  56175. //For certain types of edge abutments, the neighbor edge walk needs to
  56176. // be flipped: the cases are
  56177. // if a left edge mates with a left or bottom edge on the neighbor
  56178. // if a top edge mates with a top or right edge on the neighbor
  56179. // if a right edge mates with a right or top edge on the neighbor
  56180. // if a bottom edge mates with a bottom or left edge on the neighbor
  56181. //Seeing as the edges are enumerated as follows
  56182. // left =0
  56183. // right =1
  56184. // top =2
  56185. // bottom =3
  56186. //
  56187. //If the edge enums are the same, or the sum of the enums == 3,
  56188. // the neighbor edge walk needs to be flipped
  56189. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  56190. switch (neighborEdge) {
  56191. case PMREMGenerator.CP_EDGE_LEFT:
  56192. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  56193. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56194. break;
  56195. case PMREMGenerator.CP_EDGE_RIGHT:
  56196. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56197. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56198. break;
  56199. case PMREMGenerator.CP_EDGE_TOP:
  56200. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56201. neighborEdgeWalk = -this.numChannels;
  56202. break;
  56203. case PMREMGenerator.CP_EDGE_BOTTOM:
  56204. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56205. neighborEdgeWalk = -this.numChannels;
  56206. break;
  56207. }
  56208. }
  56209. else {
  56210. //swapped direction neighbor edge walk
  56211. switch (neighborEdge) {
  56212. case PMREMGenerator.CP_EDGE_LEFT:
  56213. //no change to neighborEdgeStartPtr for this case since it points
  56214. // to the upper left corner already
  56215. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56216. break;
  56217. case PMREMGenerator.CP_EDGE_RIGHT:
  56218. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56219. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56220. break;
  56221. case PMREMGenerator.CP_EDGE_TOP:
  56222. //no change to neighborEdgeStartPtr for this case since it points
  56223. // to the upper left corner already
  56224. neighborEdgeWalk = this.numChannels;
  56225. break;
  56226. case PMREMGenerator.CP_EDGE_BOTTOM:
  56227. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56228. neighborEdgeWalk = this.numChannels;
  56229. break;
  56230. }
  56231. }
  56232. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  56233. //nearby neighborhood
  56234. //step ahead one texel on edge
  56235. edgeStartIndex += edgeWalk;
  56236. neighborEdgeStartIndex += neighborEdgeWalk;
  56237. // note that this loop does not process the corner texels, since they have already been
  56238. // averaged across faces across earlier
  56239. for (j = 1; j < (cubeMapSize - 1); j++) {
  56240. //for each set of taps along edge, average them
  56241. // and rewrite the results into the edges
  56242. for (k = 0; k < this.numChannels; k++) {
  56243. var edgeTap = cubeMap[face][edgeStartIndex + k];
  56244. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  56245. //compute average of tap intensity values
  56246. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  56247. //propagate average of taps to edge taps
  56248. cubeMap[face][edgeStartIndex + k] = avgTap;
  56249. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  56250. }
  56251. edgeStartIndex += edgeWalk;
  56252. neighborEdgeStartIndex += neighborEdgeWalk;
  56253. }
  56254. }
  56255. };
  56256. return PMREMGenerator;
  56257. }());
  56258. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  56259. PMREMGenerator.CP_UDIR = 0;
  56260. PMREMGenerator.CP_VDIR = 1;
  56261. PMREMGenerator.CP_FACEAXIS = 2;
  56262. //used to index cube faces
  56263. PMREMGenerator.CP_FACE_X_POS = 0;
  56264. PMREMGenerator.CP_FACE_X_NEG = 1;
  56265. PMREMGenerator.CP_FACE_Y_POS = 2;
  56266. PMREMGenerator.CP_FACE_Y_NEG = 3;
  56267. PMREMGenerator.CP_FACE_Z_POS = 4;
  56268. PMREMGenerator.CP_FACE_Z_NEG = 5;
  56269. //used to index image edges
  56270. // NOTE.. the actual number corresponding to the edge is important
  56271. // do not change these, or the code will break
  56272. //
  56273. // CP_EDGE_LEFT is u = 0
  56274. // CP_EDGE_RIGHT is u = width-1
  56275. // CP_EDGE_TOP is v = 0
  56276. // CP_EDGE_BOTTOM is v = height-1
  56277. PMREMGenerator.CP_EDGE_LEFT = 0;
  56278. PMREMGenerator.CP_EDGE_RIGHT = 1;
  56279. PMREMGenerator.CP_EDGE_TOP = 2;
  56280. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  56281. //corners of CUBE map (P or N specifys if it corresponds to the
  56282. // positive or negative direction each of X, Y, and Z
  56283. PMREMGenerator.CP_CORNER_NNN = 0;
  56284. PMREMGenerator.CP_CORNER_NNP = 1;
  56285. PMREMGenerator.CP_CORNER_NPN = 2;
  56286. PMREMGenerator.CP_CORNER_NPP = 3;
  56287. PMREMGenerator.CP_CORNER_PNN = 4;
  56288. PMREMGenerator.CP_CORNER_PNP = 5;
  56289. PMREMGenerator.CP_CORNER_PPN = 6;
  56290. PMREMGenerator.CP_CORNER_PPP = 7;
  56291. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  56292. //3x2 matrices that map cube map indexing vectors in 3d
  56293. // (after face selection and divide through by the
  56294. // _ABSOLUTE VALUE_ of the max coord)
  56295. // into NVC space
  56296. //Note this currently assumes the D3D cube face ordering and orientation
  56297. PMREMGenerator._sgFace2DMapping = [
  56298. //XPOS face
  56299. [[0, 0, -1],
  56300. [0, -1, 0],
  56301. [1, 0, 0]],
  56302. //XNEG face
  56303. [[0, 0, 1],
  56304. [0, -1, 0],
  56305. [-1, 0, 0]],
  56306. //YPOS face
  56307. [[1, 0, 0],
  56308. [0, 0, 1],
  56309. [0, 1, 0]],
  56310. //YNEG face
  56311. [[1, 0, 0],
  56312. [0, 0, -1],
  56313. [0, -1, 0]],
  56314. //ZPOS face
  56315. [[1, 0, 0],
  56316. [0, -1, 0],
  56317. [0, 0, 1]],
  56318. //ZNEG face
  56319. [[-1, 0, 0],
  56320. [0, -1, 0],
  56321. [0, 0, -1]],
  56322. ];
  56323. //------------------------------------------------------------------------------
  56324. // D3D cube map face specification
  56325. // mapping from 3D x,y,z cube map lookup coordinates
  56326. // to 2D within face u,v coordinates
  56327. //
  56328. // --------------------> U direction
  56329. // | (within-face texture space)
  56330. // | _____
  56331. // | | |
  56332. // | | +Y |
  56333. // | _____|_____|_____ _____
  56334. // | | | | | |
  56335. // | | -X | +Z | +X | -Z |
  56336. // | |_____|_____|_____|_____|
  56337. // | | |
  56338. // | | -Y |
  56339. // | |_____|
  56340. // |
  56341. // v V direction
  56342. // (within-face texture space)
  56343. //------------------------------------------------------------------------------
  56344. //Information about neighbors and how texture coorrdinates change across faces
  56345. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  56346. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  56347. //Note this currently assumes the D3D cube face ordering and orientation
  56348. PMREMGenerator._sgCubeNgh = [
  56349. //XPOS face
  56350. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56351. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56352. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56353. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  56354. //XNEG face
  56355. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56356. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  56357. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  56358. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  56359. //YPOS face
  56360. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56361. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56362. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56363. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  56364. //YNEG face
  56365. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56366. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56367. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56368. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  56369. //ZPOS face
  56370. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56371. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56372. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56373. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  56374. //ZNEG face
  56375. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56376. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56377. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  56378. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  56379. ];
  56380. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  56381. // this table is used to average over the edges.
  56382. PMREMGenerator._sgCubeEdgeList = [
  56383. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56384. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56385. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56386. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56387. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56388. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56389. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56390. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56391. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  56392. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56393. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56394. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  56395. ];
  56396. //Information about which of the 8 cube corners are correspond to the
  56397. // the 4 corners in each cube face
  56398. // the order is upper left, upper right, lower left, lower right
  56399. PMREMGenerator._sgCubeCornerList = [
  56400. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  56401. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  56402. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  56403. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  56404. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  56405. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  56406. ];
  56407. Internals.PMREMGenerator = PMREMGenerator;
  56408. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56409. })(BABYLON || (BABYLON = {}));
  56410. //# sourceMappingURL=babylon.tools.pmremgenerator.js.map
  56411. var BABYLON;
  56412. (function (BABYLON) {
  56413. /**
  56414. * This represents a texture coming from an HDR input.
  56415. *
  56416. * The only supported format is currently panorama picture stored in RGBE format.
  56417. * Example of such files can be found on HDRLib: http://hdrlib.com/
  56418. */
  56419. var HDRCubeTexture = (function (_super) {
  56420. __extends(HDRCubeTexture, _super);
  56421. /**
  56422. * Instantiates an HDRTexture from the following parameters.
  56423. *
  56424. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  56425. * @param scene The scene the texture will be used in
  56426. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  56427. * @param noMipmap Forces to not generate the mipmap if true
  56428. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  56429. * @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)
  56430. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  56431. */
  56432. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  56433. if (noMipmap === void 0) { noMipmap = false; }
  56434. if (generateHarmonics === void 0) { generateHarmonics = true; }
  56435. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  56436. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  56437. if (onLoad === void 0) { onLoad = null; }
  56438. if (onError === void 0) { onError = null; }
  56439. var _this = _super.call(this, scene) || this;
  56440. _this._useInGammaSpace = false;
  56441. _this._generateHarmonics = true;
  56442. _this._isBABYLONPreprocessed = false;
  56443. _this._onLoad = null;
  56444. _this._onError = null;
  56445. /**
  56446. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  56447. */
  56448. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56449. /**
  56450. * The spherical polynomial data extracted from the texture.
  56451. */
  56452. _this.sphericalPolynomial = null;
  56453. /**
  56454. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  56455. * This is usefull at run time to apply the good shader.
  56456. */
  56457. _this.isPMREM = false;
  56458. if (!url) {
  56459. return _this;
  56460. }
  56461. _this.name = url;
  56462. _this.url = url;
  56463. _this.hasAlpha = false;
  56464. _this.isCube = true;
  56465. _this._textureMatrix = BABYLON.Matrix.Identity();
  56466. _this._onLoad = onLoad;
  56467. _this._onError = onError;
  56468. if (size) {
  56469. _this._isBABYLONPreprocessed = false;
  56470. _this._noMipmap = noMipmap;
  56471. _this._size = size;
  56472. _this._useInGammaSpace = useInGammaSpace;
  56473. _this._usePMREMGenerator = usePMREMGenerator &&
  56474. scene.getEngine().getCaps().textureLOD &&
  56475. _this.getScene().getEngine().getCaps().textureFloat &&
  56476. !_this._useInGammaSpace;
  56477. }
  56478. else {
  56479. _this._isBABYLONPreprocessed = true;
  56480. _this._noMipmap = false;
  56481. _this._useInGammaSpace = false;
  56482. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  56483. _this.getScene().getEngine().getCaps().textureFloat &&
  56484. !_this._useInGammaSpace;
  56485. }
  56486. _this.isPMREM = _this._usePMREMGenerator;
  56487. _this._texture = _this._getFromCache(url, _this._noMipmap);
  56488. if (!_this._texture) {
  56489. if (!scene.useDelayedTextureLoading) {
  56490. _this.loadTexture();
  56491. }
  56492. else {
  56493. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56494. }
  56495. }
  56496. return _this;
  56497. }
  56498. /**
  56499. * Occurs when the file is a preprocessed .babylon.hdr file.
  56500. */
  56501. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  56502. var _this = this;
  56503. var mipLevels = 0;
  56504. var floatArrayView = null;
  56505. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  56506. var mips = [];
  56507. var startIndex = 30;
  56508. for (var level = 0; level < mipLevels; level++) {
  56509. mips.push([]);
  56510. // Fill each pixel of the mip level.
  56511. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  56512. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56513. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  56514. mips[level].push(faceData);
  56515. startIndex += faceSize;
  56516. }
  56517. }
  56518. return mips;
  56519. } : null;
  56520. var callback = function (buffer) {
  56521. // Create Native Array Views
  56522. var intArrayView = new Int32Array(buffer);
  56523. floatArrayView = new Float32Array(buffer);
  56524. // Fill header.
  56525. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  56526. _this._size = intArrayView[1]; // CubeMap max mip face size.
  56527. // Update Texture Information.
  56528. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  56529. // Fill polynomial information.
  56530. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  56531. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  56532. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  56533. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  56534. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  56535. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  56536. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  56537. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  56538. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  56539. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  56540. // Fill pixel data.
  56541. mipLevels = intArrayView[29]; // Number of mip levels.
  56542. var startIndex = 30;
  56543. var data = [];
  56544. var faceSize = Math.pow(_this._size, 2) * 3;
  56545. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56546. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  56547. startIndex += faceSize;
  56548. }
  56549. var results = [];
  56550. var byteArray = null;
  56551. // Push each faces.
  56552. for (var k = 0; k < 6; k++) {
  56553. var dataFace = null;
  56554. // If special cases.
  56555. if (!mipmapGenerator) {
  56556. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  56557. dataFace = data[j];
  56558. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56559. // 3 channels of 1 bytes per pixel in bytes.
  56560. var byteBuffer = new ArrayBuffer(faceSize);
  56561. byteArray = new Uint8Array(byteBuffer);
  56562. }
  56563. for (var i = 0; i < _this._size * _this._size; i++) {
  56564. // Put in gamma space if requested.
  56565. if (_this._useInGammaSpace) {
  56566. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56567. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56568. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56569. }
  56570. // Convert to int texture for fallback.
  56571. if (byteArray) {
  56572. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56573. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56574. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56575. // May use luminance instead if the result is not accurate.
  56576. var max = Math.max(Math.max(r, g), b);
  56577. if (max > 255) {
  56578. var scale = 255 / max;
  56579. r *= scale;
  56580. g *= scale;
  56581. b *= scale;
  56582. }
  56583. byteArray[(i * 3) + 0] = r;
  56584. byteArray[(i * 3) + 1] = g;
  56585. byteArray[(i * 3) + 2] = b;
  56586. }
  56587. }
  56588. }
  56589. else {
  56590. dataFace = data[k];
  56591. }
  56592. // Fill the array accordingly.
  56593. if (byteArray) {
  56594. results.push(byteArray);
  56595. }
  56596. else {
  56597. results.push(dataFace);
  56598. }
  56599. }
  56600. return results;
  56601. };
  56602. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  56603. };
  56604. /**
  56605. * Occurs when the file is raw .hdr file.
  56606. */
  56607. HDRCubeTexture.prototype.loadHDRTexture = function () {
  56608. var _this = this;
  56609. var callback = function (buffer) {
  56610. // Extract the raw linear data.
  56611. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  56612. // Generate harmonics if needed.
  56613. if (_this._generateHarmonics) {
  56614. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  56615. }
  56616. var results = [];
  56617. var byteArray = null;
  56618. // Push each faces.
  56619. for (var j = 0; j < 6; j++) {
  56620. // Create uintarray fallback.
  56621. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56622. // 3 channels of 1 bytes per pixel in bytes.
  56623. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  56624. byteArray = new Uint8Array(byteBuffer);
  56625. }
  56626. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  56627. // If special cases.
  56628. if (_this._useInGammaSpace || byteArray) {
  56629. for (var i = 0; i < _this._size * _this._size; i++) {
  56630. // Put in gamma space if requested.
  56631. if (_this._useInGammaSpace) {
  56632. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56633. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56634. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56635. }
  56636. // Convert to int texture for fallback.
  56637. if (byteArray) {
  56638. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56639. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56640. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56641. // May use luminance instead if the result is not accurate.
  56642. var max = Math.max(Math.max(r, g), b);
  56643. if (max > 255) {
  56644. var scale = 255 / max;
  56645. r *= scale;
  56646. g *= scale;
  56647. b *= scale;
  56648. }
  56649. byteArray[(i * 3) + 0] = r;
  56650. byteArray[(i * 3) + 1] = g;
  56651. byteArray[(i * 3) + 2] = b;
  56652. }
  56653. }
  56654. }
  56655. if (byteArray) {
  56656. results.push(byteArray);
  56657. }
  56658. else {
  56659. results.push(dataFace);
  56660. }
  56661. }
  56662. return results;
  56663. };
  56664. var mipmapGenerator = null;
  56665. if (!this._noMipmap &&
  56666. this._usePMREMGenerator) {
  56667. mipmapGenerator = function (data) {
  56668. // Custom setup of the generator matching with the PBR shader values.
  56669. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  56670. return generator.filterCubeMap();
  56671. };
  56672. }
  56673. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  56674. };
  56675. /**
  56676. * Starts the loading process of the texture.
  56677. */
  56678. HDRCubeTexture.prototype.loadTexture = function () {
  56679. if (this._isBABYLONPreprocessed) {
  56680. this.loadBabylonTexture();
  56681. }
  56682. else {
  56683. this.loadHDRTexture();
  56684. }
  56685. };
  56686. HDRCubeTexture.prototype.clone = function () {
  56687. var size = this._isBABYLONPreprocessed ? null : this._size;
  56688. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  56689. // Base texture
  56690. newTexture.level = this.level;
  56691. newTexture.wrapU = this.wrapU;
  56692. newTexture.wrapV = this.wrapV;
  56693. newTexture.coordinatesIndex = this.coordinatesIndex;
  56694. newTexture.coordinatesMode = this.coordinatesMode;
  56695. return newTexture;
  56696. };
  56697. // Methods
  56698. HDRCubeTexture.prototype.delayLoad = function () {
  56699. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56700. return;
  56701. }
  56702. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56703. this._texture = this._getFromCache(this.url, this._noMipmap);
  56704. if (!this._texture) {
  56705. this.loadTexture();
  56706. }
  56707. };
  56708. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  56709. return this._textureMatrix;
  56710. };
  56711. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56712. var texture = null;
  56713. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56714. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  56715. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  56716. texture.name = parsedTexture.name;
  56717. texture.hasAlpha = parsedTexture.hasAlpha;
  56718. texture.level = parsedTexture.level;
  56719. texture.coordinatesMode = parsedTexture.coordinatesMode;
  56720. }
  56721. return texture;
  56722. };
  56723. HDRCubeTexture.prototype.serialize = function () {
  56724. if (!this.name) {
  56725. return null;
  56726. }
  56727. var serializationObject = {};
  56728. serializationObject.name = this.name;
  56729. serializationObject.hasAlpha = this.hasAlpha;
  56730. serializationObject.isCube = true;
  56731. serializationObject.level = this.level;
  56732. serializationObject.size = this._size;
  56733. serializationObject.coordinatesMode = this.coordinatesMode;
  56734. serializationObject.useInGammaSpace = this._useInGammaSpace;
  56735. serializationObject.generateHarmonics = this._generateHarmonics;
  56736. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  56737. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  56738. serializationObject.customType = "BABYLON.HDRCubeTexture";
  56739. serializationObject.noMipmap = this._noMipmap;
  56740. return serializationObject;
  56741. };
  56742. /**
  56743. * Saves as a file the data contained in the texture in a binary format.
  56744. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56745. * as the spherical used in the lighting.
  56746. * @param url The HDR file url.
  56747. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56748. * @param onError Method called if any error happens during download.
  56749. * @return The packed binary data.
  56750. */
  56751. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  56752. if (onError === void 0) { onError = null; }
  56753. var callback = function (buffer) {
  56754. var data = new Blob([buffer], { type: 'application/octet-stream' });
  56755. // Returns a URL you can use as a href.
  56756. var objUrl = window.URL.createObjectURL(data);
  56757. // Simulates a link to it and click to dowload.
  56758. var a = document.createElement("a");
  56759. document.body.appendChild(a);
  56760. a.style.display = "none";
  56761. a.href = objUrl;
  56762. a.download = "envmap.babylon.hdr";
  56763. a.click();
  56764. };
  56765. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  56766. };
  56767. /**
  56768. * Serializes the data contained in the texture in a binary format.
  56769. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56770. * as the spherical used in the lighting.
  56771. * @param url The HDR file url.
  56772. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56773. * @param onError Method called if any error happens during download.
  56774. * @return The packed binary data.
  56775. */
  56776. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  56777. if (onError === void 0) { onError = null; }
  56778. // Needs the url tho create the texture.
  56779. if (!url) {
  56780. return null;
  56781. }
  56782. // Check Power of two size.
  56783. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  56784. return null;
  56785. }
  56786. var getDataCallback = function (dataBuffer) {
  56787. // Extract the raw linear data.
  56788. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  56789. // Generate harmonics if needed.
  56790. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  56791. // Generate seamless faces
  56792. var mipGeneratorArray = [];
  56793. // Data are known to be in +X +Y +Z -X -Y -Z
  56794. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  56795. mipGeneratorArray.push(cubeData.right); // +X
  56796. mipGeneratorArray.push(cubeData.left); // -X
  56797. mipGeneratorArray.push(cubeData.up); // +Y
  56798. mipGeneratorArray.push(cubeData.down); // -Y
  56799. mipGeneratorArray.push(cubeData.front); // +Z
  56800. mipGeneratorArray.push(cubeData.back); // -Z
  56801. // Custom setup of the generator matching with the PBR shader values.
  56802. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  56803. var mippedData = generator.filterCubeMap();
  56804. // Compute required byte length.
  56805. var byteLength = 1 * 4; // Raw Data Version int32.
  56806. byteLength += 4; // CubeMap max mip face size int32.
  56807. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  56808. // Add data size.
  56809. byteLength += 4; // Number of mip levels int32.
  56810. for (var level = 0; level < mippedData.length; level++) {
  56811. var mipSize = size >> level;
  56812. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  56813. }
  56814. // Prepare binary structure.
  56815. var buffer = new ArrayBuffer(byteLength);
  56816. var intArrayView = new Int32Array(buffer);
  56817. var floatArrayView = new Float32Array(buffer);
  56818. // Fill header.
  56819. intArrayView[0] = 1; // Version 1.
  56820. intArrayView[1] = size; // CubeMap max mip face size.
  56821. // Fill polynomial information.
  56822. sphericalPolynomial.x.toArray(floatArrayView, 2);
  56823. sphericalPolynomial.y.toArray(floatArrayView, 5);
  56824. sphericalPolynomial.z.toArray(floatArrayView, 8);
  56825. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  56826. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  56827. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  56828. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  56829. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  56830. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  56831. // Fill pixel data.
  56832. intArrayView[29] = mippedData.length; // Number of mip levels.
  56833. var startIndex = 30;
  56834. for (var level = 0; level < mippedData.length; level++) {
  56835. // Fill each pixel of the mip level.
  56836. var faceSize = Math.pow(size >> level, 2) * 3;
  56837. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56838. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  56839. startIndex += faceSize;
  56840. }
  56841. }
  56842. // Callback.
  56843. callback(buffer);
  56844. };
  56845. // Download and process.
  56846. BABYLON.Tools.LoadFile(url, function (data) {
  56847. getDataCallback(data);
  56848. }, null, null, true, onError);
  56849. };
  56850. return HDRCubeTexture;
  56851. }(BABYLON.BaseTexture));
  56852. HDRCubeTexture._facesMapping = [
  56853. "right",
  56854. "up",
  56855. "front",
  56856. "left",
  56857. "down",
  56858. "back"
  56859. ];
  56860. BABYLON.HDRCubeTexture = HDRCubeTexture;
  56861. })(BABYLON || (BABYLON = {}));
  56862. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  56863. var BABYLON;
  56864. (function (BABYLON) {
  56865. var Debug;
  56866. (function (Debug) {
  56867. /**
  56868. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  56869. */
  56870. var SkeletonViewer = (function () {
  56871. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  56872. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  56873. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  56874. this.skeleton = skeleton;
  56875. this.mesh = mesh;
  56876. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  56877. this.renderingGroupId = renderingGroupId;
  56878. this.color = BABYLON.Color3.White();
  56879. this._debugLines = [];
  56880. this._isEnabled = false;
  56881. this._scene = scene;
  56882. this.update();
  56883. this._renderFunction = this.update.bind(this);
  56884. }
  56885. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  56886. get: function () {
  56887. return this._isEnabled;
  56888. },
  56889. set: function (value) {
  56890. if (this._isEnabled === value) {
  56891. return;
  56892. }
  56893. this._isEnabled = value;
  56894. if (value) {
  56895. this._scene.registerBeforeRender(this._renderFunction);
  56896. }
  56897. else {
  56898. this._scene.unregisterBeforeRender(this._renderFunction);
  56899. }
  56900. },
  56901. enumerable: true,
  56902. configurable: true
  56903. });
  56904. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  56905. if (x === void 0) { x = 0; }
  56906. if (y === void 0) { y = 0; }
  56907. if (z === void 0) { z = 0; }
  56908. var tmat = BABYLON.Tmp.Matrix[0];
  56909. var parentBone = bone.getParent();
  56910. tmat.copyFrom(bone.getLocalMatrix());
  56911. if (x !== 0 || y !== 0 || z !== 0) {
  56912. var tmat2 = BABYLON.Tmp.Matrix[1];
  56913. BABYLON.Matrix.IdentityToRef(tmat2);
  56914. tmat2.m[12] = x;
  56915. tmat2.m[13] = y;
  56916. tmat2.m[14] = z;
  56917. tmat2.multiplyToRef(tmat, tmat);
  56918. }
  56919. if (parentBone) {
  56920. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  56921. }
  56922. tmat.multiplyToRef(meshMat, tmat);
  56923. position.x = tmat.m[12];
  56924. position.y = tmat.m[13];
  56925. position.z = tmat.m[14];
  56926. };
  56927. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  56928. var len = bones.length;
  56929. for (var i = 0; i < len; i++) {
  56930. var bone = bones[i];
  56931. var points = this._debugLines[i];
  56932. if (!points) {
  56933. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56934. this._debugLines[i] = points;
  56935. }
  56936. this._getBonePosition(points[0], bone, meshMat);
  56937. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  56938. }
  56939. };
  56940. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  56941. var len = bones.length;
  56942. var boneNum = 0;
  56943. for (var i = len - 1; i >= 0; i--) {
  56944. var childBone = bones[i];
  56945. var parentBone = childBone.getParent();
  56946. if (!parentBone) {
  56947. continue;
  56948. }
  56949. var points = this._debugLines[boneNum];
  56950. if (!points) {
  56951. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56952. this._debugLines[boneNum] = points;
  56953. }
  56954. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  56955. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  56956. boneNum++;
  56957. }
  56958. };
  56959. SkeletonViewer.prototype.update = function () {
  56960. if (this.autoUpdateBonesMatrices) {
  56961. this.skeleton.computeAbsoluteTransforms();
  56962. }
  56963. if (this.skeleton.bones[0].length === undefined) {
  56964. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56965. }
  56966. else {
  56967. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56968. }
  56969. if (!this._debugMesh) {
  56970. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  56971. this._debugMesh.renderingGroupId = this.renderingGroupId;
  56972. }
  56973. else {
  56974. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  56975. }
  56976. this._debugMesh.color = this.color;
  56977. };
  56978. SkeletonViewer.prototype.dispose = function () {
  56979. if (this._debugMesh) {
  56980. this.isEnabled = false;
  56981. this._debugMesh.dispose();
  56982. this._debugMesh = null;
  56983. }
  56984. };
  56985. return SkeletonViewer;
  56986. }());
  56987. Debug.SkeletonViewer = SkeletonViewer;
  56988. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56989. })(BABYLON || (BABYLON = {}));
  56990. //# sourceMappingURL=babylon.skeletonViewer.js.map
  56991. var BABYLON;
  56992. (function (BABYLON) {
  56993. var Debug;
  56994. (function (Debug) {
  56995. var AxesViewer = (function () {
  56996. function AxesViewer(scene, scaleLines) {
  56997. if (scaleLines === void 0) { scaleLines = 1; }
  56998. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56999. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57000. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57001. this.scaleLines = 1;
  57002. this.scaleLines = scaleLines;
  57003. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  57004. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  57005. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  57006. this._xmesh.renderingGroupId = 2;
  57007. this._ymesh.renderingGroupId = 2;
  57008. this._zmesh.renderingGroupId = 2;
  57009. this._xmesh.material.checkReadyOnlyOnce = true;
  57010. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  57011. this._ymesh.material.checkReadyOnlyOnce = true;
  57012. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  57013. this._zmesh.material.checkReadyOnlyOnce = true;
  57014. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  57015. this.scene = scene;
  57016. }
  57017. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  57018. var scaleLines = this.scaleLines;
  57019. var point1 = this._xline[0];
  57020. var point2 = this._xline[1];
  57021. point1.x = position.x;
  57022. point1.y = position.y;
  57023. point1.z = position.z;
  57024. point2.x = point1.x + xaxis.x * scaleLines;
  57025. point2.y = point1.y + xaxis.y * scaleLines;
  57026. point2.z = point1.z + xaxis.z * scaleLines;
  57027. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  57028. point1 = this._yline[0];
  57029. point2 = this._yline[1];
  57030. point1.x = position.x;
  57031. point1.y = position.y;
  57032. point1.z = position.z;
  57033. point2.x = point1.x + yaxis.x * scaleLines;
  57034. point2.y = point1.y + yaxis.y * scaleLines;
  57035. point2.z = point1.z + yaxis.z * scaleLines;
  57036. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  57037. point1 = this._zline[0];
  57038. point2 = this._zline[1];
  57039. point1.x = position.x;
  57040. point1.y = position.y;
  57041. point1.z = position.z;
  57042. point2.x = point1.x + zaxis.x * scaleLines;
  57043. point2.y = point1.y + zaxis.y * scaleLines;
  57044. point2.z = point1.z + zaxis.z * scaleLines;
  57045. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  57046. };
  57047. AxesViewer.prototype.dispose = function () {
  57048. if (this._xmesh) {
  57049. this._xmesh.dispose();
  57050. this._ymesh.dispose();
  57051. this._zmesh.dispose();
  57052. this._xmesh = null;
  57053. this._ymesh = null;
  57054. this._zmesh = null;
  57055. this._xline = null;
  57056. this._yline = null;
  57057. this._zline = null;
  57058. this.scene = null;
  57059. }
  57060. };
  57061. return AxesViewer;
  57062. }());
  57063. Debug.AxesViewer = AxesViewer;
  57064. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57065. })(BABYLON || (BABYLON = {}));
  57066. //# sourceMappingURL=babylon.axesViewer.js.map
  57067. var BABYLON;
  57068. (function (BABYLON) {
  57069. var Debug;
  57070. (function (Debug) {
  57071. var BoneAxesViewer = (function (_super) {
  57072. __extends(BoneAxesViewer, _super);
  57073. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  57074. if (scaleLines === void 0) { scaleLines = 1; }
  57075. var _this = _super.call(this, scene, scaleLines) || this;
  57076. _this.pos = BABYLON.Vector3.Zero();
  57077. _this.xaxis = BABYLON.Vector3.Zero();
  57078. _this.yaxis = BABYLON.Vector3.Zero();
  57079. _this.zaxis = BABYLON.Vector3.Zero();
  57080. _this.mesh = mesh;
  57081. _this.bone = bone;
  57082. return _this;
  57083. }
  57084. BoneAxesViewer.prototype.update = function () {
  57085. var bone = this.bone;
  57086. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  57087. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  57088. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  57089. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  57090. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  57091. };
  57092. BoneAxesViewer.prototype.dispose = function () {
  57093. if (this.pos) {
  57094. this.pos = null;
  57095. this.xaxis = null;
  57096. this.yaxis = null;
  57097. this.zaxis = null;
  57098. this.mesh = null;
  57099. this.bone = null;
  57100. _super.prototype.dispose.call(this);
  57101. }
  57102. };
  57103. return BoneAxesViewer;
  57104. }(Debug.AxesViewer));
  57105. Debug.BoneAxesViewer = BoneAxesViewer;
  57106. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57107. })(BABYLON || (BABYLON = {}));
  57108. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  57109. var BABYLON;
  57110. (function (BABYLON) {
  57111. /**
  57112. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  57113. * It can help converting any input color in a desired output one. This can then be used to create effects
  57114. * from sepia, black and white to sixties or futuristic rendering...
  57115. *
  57116. * The only supported format is currently 3dl.
  57117. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  57118. */
  57119. var ColorGradingTexture = (function (_super) {
  57120. __extends(ColorGradingTexture, _super);
  57121. /**
  57122. * Instantiates a ColorGradingTexture from the following parameters.
  57123. *
  57124. * @param url The location of the color gradind data (currently only supporting 3dl)
  57125. * @param scene The scene the texture will be used in
  57126. */
  57127. function ColorGradingTexture(url, scene) {
  57128. var _this = _super.call(this, scene) || this;
  57129. if (!url) {
  57130. return _this;
  57131. }
  57132. _this._textureMatrix = BABYLON.Matrix.Identity();
  57133. _this.name = url;
  57134. _this.url = url;
  57135. _this.hasAlpha = false;
  57136. _this.isCube = false;
  57137. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57138. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57139. _this.anisotropicFilteringLevel = 1;
  57140. _this._texture = _this._getFromCache(url, true);
  57141. if (!_this._texture) {
  57142. if (!scene.useDelayedTextureLoading) {
  57143. _this.loadTexture();
  57144. }
  57145. else {
  57146. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57147. }
  57148. }
  57149. return _this;
  57150. }
  57151. /**
  57152. * Returns the texture matrix used in most of the material.
  57153. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  57154. */
  57155. ColorGradingTexture.prototype.getTextureMatrix = function () {
  57156. return this._textureMatrix;
  57157. };
  57158. /**
  57159. * Occurs when the file being loaded is a .3dl LUT file.
  57160. */
  57161. ColorGradingTexture.prototype.load3dlTexture = function () {
  57162. var _this = this;
  57163. var mipLevels = 0;
  57164. var floatArrayView = null;
  57165. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57166. this._texture = texture;
  57167. var callback = function (text) {
  57168. var data;
  57169. var tempData;
  57170. var line;
  57171. var lines = text.split('\n');
  57172. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  57173. var maxColor = 0;
  57174. for (var i = 0; i < lines.length; i++) {
  57175. line = lines[i];
  57176. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  57177. continue;
  57178. if (line.indexOf('#') === 0)
  57179. continue;
  57180. var words = line.split(" ");
  57181. if (size === 0) {
  57182. // Number of space + one
  57183. size = words.length;
  57184. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  57185. tempData = new Float32Array(size * size * size * 4);
  57186. continue;
  57187. }
  57188. if (size != 0) {
  57189. var r = Math.max(parseInt(words[0]), 0);
  57190. var g = Math.max(parseInt(words[1]), 0);
  57191. var b = Math.max(parseInt(words[2]), 0);
  57192. maxColor = Math.max(r, maxColor);
  57193. maxColor = Math.max(g, maxColor);
  57194. maxColor = Math.max(b, maxColor);
  57195. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  57196. tempData[pixelStorageIndex + 0] = r;
  57197. tempData[pixelStorageIndex + 1] = g;
  57198. tempData[pixelStorageIndex + 2] = b;
  57199. tempData[pixelStorageIndex + 3] = 0;
  57200. pixelIndexSlice++;
  57201. if (pixelIndexSlice % size == 0) {
  57202. pixelIndexH++;
  57203. pixelIndexSlice = 0;
  57204. if (pixelIndexH % size == 0) {
  57205. pixelIndexW++;
  57206. pixelIndexH = 0;
  57207. }
  57208. }
  57209. }
  57210. }
  57211. for (var i = 0; i < tempData.length; i++) {
  57212. var value = tempData[i];
  57213. data[i] = (value / maxColor * 255);
  57214. }
  57215. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  57216. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  57217. };
  57218. BABYLON.Tools.LoadFile(this.url, callback);
  57219. return this._texture;
  57220. };
  57221. /**
  57222. * Starts the loading process of the texture.
  57223. */
  57224. ColorGradingTexture.prototype.loadTexture = function () {
  57225. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  57226. this.load3dlTexture();
  57227. }
  57228. };
  57229. /**
  57230. * Clones the color gradind texture.
  57231. */
  57232. ColorGradingTexture.prototype.clone = function () {
  57233. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  57234. // Base texture
  57235. newTexture.level = this.level;
  57236. return newTexture;
  57237. };
  57238. /**
  57239. * Called during delayed load for textures.
  57240. */
  57241. ColorGradingTexture.prototype.delayLoad = function () {
  57242. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57243. return;
  57244. }
  57245. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57246. this._texture = this._getFromCache(this.url, true);
  57247. if (!this._texture) {
  57248. this.loadTexture();
  57249. }
  57250. };
  57251. /**
  57252. * Binds the color grading to the shader.
  57253. * @param colorGrading The texture to bind
  57254. * @param effect The effect to bind to
  57255. */
  57256. ColorGradingTexture.Bind = function (colorGrading, effect) {
  57257. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  57258. var x = colorGrading.level; // Texture Level
  57259. var y = colorGrading.getSize().height; // Texture Size example with 8
  57260. var z = y - 1.0; // SizeMinusOne 8 - 1
  57261. var w = 1 / y; // Space of 1 slice 1 / 8
  57262. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  57263. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  57264. var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8 // Space of 1 pixel in V direction, e.g. 1/8
  57265. var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  57266. var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  57267. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  57268. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  57269. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  57270. };
  57271. /**
  57272. * Prepare the list of uniforms associated with the ColorGrading effects.
  57273. * @param uniformsList The list of uniforms used in the effect
  57274. * @param samplersList The list of samplers used in the effect
  57275. */
  57276. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  57277. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  57278. samplersList.push("cameraColorGrading2DSampler");
  57279. };
  57280. /**
  57281. * Parses a color grading texture serialized by Babylon.
  57282. * @param parsedTexture The texture information being parsedTexture
  57283. * @param scene The scene to load the texture in
  57284. * @param rootUrl The root url of the data assets to load
  57285. * @return A color gradind texture
  57286. */
  57287. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57288. var texture = null;
  57289. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57290. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  57291. texture.name = parsedTexture.name;
  57292. texture.level = parsedTexture.level;
  57293. }
  57294. return texture;
  57295. };
  57296. /**
  57297. * Serializes the LUT texture to json format.
  57298. */
  57299. ColorGradingTexture.prototype.serialize = function () {
  57300. if (!this.name) {
  57301. return null;
  57302. }
  57303. var serializationObject = {};
  57304. serializationObject.name = this.name;
  57305. serializationObject.level = this.level;
  57306. serializationObject.customType = "BABYLON.ColorGradingTexture";
  57307. return serializationObject;
  57308. };
  57309. return ColorGradingTexture;
  57310. }(BABYLON.BaseTexture));
  57311. /**
  57312. * Empty line regex stored for GC.
  57313. */
  57314. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  57315. BABYLON.ColorGradingTexture = ColorGradingTexture;
  57316. })(BABYLON || (BABYLON = {}));
  57317. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  57318. var BABYLON;
  57319. (function (BABYLON) {
  57320. /**
  57321. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57322. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57323. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  57324. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57325. */
  57326. var ColorCurves = (function () {
  57327. function ColorCurves() {
  57328. this._dirty = true;
  57329. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  57330. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  57331. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57332. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  57333. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57334. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  57335. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  57336. this._globalHue = 30;
  57337. this._globalDensity = 0;
  57338. this._globalSaturation = 0;
  57339. this._globalExposure = 0;
  57340. this._highlightsHue = 30;
  57341. this._highlightsDensity = 0;
  57342. this._highlightsSaturation = 0;
  57343. this._highlightsExposure = 0;
  57344. this._midtonesHue = 30;
  57345. this._midtonesDensity = 0;
  57346. this._midtonesSaturation = 0;
  57347. this._midtonesExposure = 0;
  57348. this._shadowsHue = 30;
  57349. this._shadowsDensity = 0;
  57350. this._shadowsSaturation = 0;
  57351. this._shadowsExposure = 0;
  57352. }
  57353. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  57354. /**
  57355. * Gets the global Hue value.
  57356. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57357. */
  57358. get: function () {
  57359. return this._globalHue;
  57360. },
  57361. /**
  57362. * Sets the global Hue value.
  57363. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57364. */
  57365. set: function (value) {
  57366. this._globalHue = value;
  57367. this._dirty = true;
  57368. },
  57369. enumerable: true,
  57370. configurable: true
  57371. });
  57372. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  57373. /**
  57374. * Gets the global Density value.
  57375. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57376. * Values less than zero provide a filter of opposite hue.
  57377. */
  57378. get: function () {
  57379. return this._globalDensity;
  57380. },
  57381. /**
  57382. * Sets the global Density value.
  57383. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57384. * Values less than zero provide a filter of opposite hue.
  57385. */
  57386. set: function (value) {
  57387. this._globalDensity = value;
  57388. this._dirty = true;
  57389. },
  57390. enumerable: true,
  57391. configurable: true
  57392. });
  57393. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  57394. /**
  57395. * Gets the global Saturation value.
  57396. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57397. */
  57398. get: function () {
  57399. return this._globalSaturation;
  57400. },
  57401. /**
  57402. * Sets the global Saturation value.
  57403. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57404. */
  57405. set: function (value) {
  57406. this._globalSaturation = value;
  57407. this._dirty = true;
  57408. },
  57409. enumerable: true,
  57410. configurable: true
  57411. });
  57412. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  57413. /**
  57414. * Gets the highlights Hue value.
  57415. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57416. */
  57417. get: function () {
  57418. return this._highlightsHue;
  57419. },
  57420. /**
  57421. * Sets the highlights Hue value.
  57422. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57423. */
  57424. set: function (value) {
  57425. this._highlightsHue = value;
  57426. this._dirty = true;
  57427. },
  57428. enumerable: true,
  57429. configurable: true
  57430. });
  57431. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  57432. /**
  57433. * Gets the highlights Density value.
  57434. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57435. * Values less than zero provide a filter of opposite hue.
  57436. */
  57437. get: function () {
  57438. return this._highlightsDensity;
  57439. },
  57440. /**
  57441. * Sets the highlights Density value.
  57442. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57443. * Values less than zero provide a filter of opposite hue.
  57444. */
  57445. set: function (value) {
  57446. this._highlightsDensity = value;
  57447. this._dirty = true;
  57448. },
  57449. enumerable: true,
  57450. configurable: true
  57451. });
  57452. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  57453. /**
  57454. * Gets the highlights Saturation value.
  57455. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57456. */
  57457. get: function () {
  57458. return this._highlightsSaturation;
  57459. },
  57460. /**
  57461. * Sets the highlights Saturation value.
  57462. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57463. */
  57464. set: function (value) {
  57465. this._highlightsSaturation = value;
  57466. this._dirty = true;
  57467. },
  57468. enumerable: true,
  57469. configurable: true
  57470. });
  57471. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  57472. /**
  57473. * Gets the highlights Exposure value.
  57474. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  57475. */
  57476. get: function () {
  57477. return this._highlightsExposure;
  57478. },
  57479. /**
  57480. * Sets the highlights Exposure value.
  57481. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  57482. */
  57483. set: function (value) {
  57484. this._highlightsExposure = value;
  57485. this._dirty = true;
  57486. },
  57487. enumerable: true,
  57488. configurable: true
  57489. });
  57490. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  57491. /**
  57492. * Gets the midtones Hue value.
  57493. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57494. */
  57495. get: function () {
  57496. return this._midtonesHue;
  57497. },
  57498. /**
  57499. * Sets the midtones Hue value.
  57500. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57501. */
  57502. set: function (value) {
  57503. this._midtonesHue = value;
  57504. this._dirty = true;
  57505. },
  57506. enumerable: true,
  57507. configurable: true
  57508. });
  57509. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  57510. /**
  57511. * Gets the midtones Density value.
  57512. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57513. * Values less than zero provide a filter of opposite hue.
  57514. */
  57515. get: function () {
  57516. return this._midtonesDensity;
  57517. },
  57518. /**
  57519. * Sets the midtones Density value.
  57520. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57521. * Values less than zero provide a filter of opposite hue.
  57522. */
  57523. set: function (value) {
  57524. this._midtonesDensity = value;
  57525. this._dirty = true;
  57526. },
  57527. enumerable: true,
  57528. configurable: true
  57529. });
  57530. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  57531. /**
  57532. * Gets the midtones Saturation value.
  57533. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57534. */
  57535. get: function () {
  57536. return this._midtonesSaturation;
  57537. },
  57538. /**
  57539. * Sets the midtones Saturation value.
  57540. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57541. */
  57542. set: function (value) {
  57543. this._midtonesSaturation = value;
  57544. this._dirty = true;
  57545. },
  57546. enumerable: true,
  57547. configurable: true
  57548. });
  57549. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  57550. /**
  57551. * Gets the midtones Exposure value.
  57552. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  57553. */
  57554. get: function () {
  57555. return this._midtonesExposure;
  57556. },
  57557. /**
  57558. * Sets the midtones Exposure value.
  57559. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  57560. */
  57561. set: function (value) {
  57562. this._midtonesExposure = value;
  57563. this._dirty = true;
  57564. },
  57565. enumerable: true,
  57566. configurable: true
  57567. });
  57568. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  57569. /**
  57570. * Gets the shadows Hue value.
  57571. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57572. */
  57573. get: function () {
  57574. return this._shadowsHue;
  57575. },
  57576. /**
  57577. * Sets the shadows Hue value.
  57578. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57579. */
  57580. set: function (value) {
  57581. this._shadowsHue = value;
  57582. this._dirty = true;
  57583. },
  57584. enumerable: true,
  57585. configurable: true
  57586. });
  57587. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  57588. /**
  57589. * Gets the shadows Density value.
  57590. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57591. * Values less than zero provide a filter of opposite hue.
  57592. */
  57593. get: function () {
  57594. return this._shadowsDensity;
  57595. },
  57596. /**
  57597. * Sets the shadows Density value.
  57598. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57599. * Values less than zero provide a filter of opposite hue.
  57600. */
  57601. set: function (value) {
  57602. this._shadowsDensity = value;
  57603. this._dirty = true;
  57604. },
  57605. enumerable: true,
  57606. configurable: true
  57607. });
  57608. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  57609. /**
  57610. * Gets the shadows Saturation value.
  57611. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57612. */
  57613. get: function () {
  57614. return this._shadowsSaturation;
  57615. },
  57616. /**
  57617. * Sets the shadows Saturation value.
  57618. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57619. */
  57620. set: function (value) {
  57621. this._shadowsSaturation = value;
  57622. this._dirty = true;
  57623. },
  57624. enumerable: true,
  57625. configurable: true
  57626. });
  57627. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  57628. /**
  57629. * Gets the shadows Exposure value.
  57630. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  57631. */
  57632. get: function () {
  57633. return this._shadowsExposure;
  57634. },
  57635. /**
  57636. * Sets the shadows Exposure value.
  57637. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  57638. */
  57639. set: function (value) {
  57640. this._shadowsExposure = value;
  57641. this._dirty = true;
  57642. },
  57643. enumerable: true,
  57644. configurable: true
  57645. });
  57646. /**
  57647. * Binds the color curves to the shader.
  57648. * @param colorCurves The color curve to bind
  57649. * @param effect The effect to bind to
  57650. */
  57651. ColorCurves.Bind = function (colorCurves, effect) {
  57652. if (colorCurves._dirty) {
  57653. colorCurves._dirty = false;
  57654. // Fill in global info.
  57655. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  57656. // Compute highlights info.
  57657. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  57658. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  57659. // Compute midtones info.
  57660. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  57661. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  57662. // Compute shadows info.
  57663. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  57664. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  57665. // Compute deltas (neutral is midtones).
  57666. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  57667. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  57668. }
  57669. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  57670. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  57671. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  57672. };
  57673. /**
  57674. * Prepare the list of uniforms associated with the ColorCurves effects.
  57675. * @param uniformsList The list of uniforms used in the effect
  57676. */
  57677. ColorCurves.PrepareUniforms = function (uniformsList) {
  57678. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  57679. };
  57680. /**
  57681. * Returns color grading data based on a hue, density, saturation and exposure value.
  57682. * @param filterHue The hue of the color filter.
  57683. * @param filterDensity The density of the color filter.
  57684. * @param saturation The saturation.
  57685. * @param exposure The exposure.
  57686. * @param result The result data container.
  57687. */
  57688. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  57689. if (hue == null) {
  57690. return;
  57691. }
  57692. hue = ColorCurves.clamp(hue, 0, 360);
  57693. density = ColorCurves.clamp(density, -100, 100);
  57694. saturation = ColorCurves.clamp(saturation, -100, 100);
  57695. exposure = ColorCurves.clamp(exposure, -100, 100);
  57696. // Remap the slider/config filter density with non-linear mapping and also scale by half
  57697. // so that the maximum filter density is only 50% control. This provides fine control
  57698. // for small values and reasonable range.
  57699. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  57700. density *= 0.5;
  57701. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  57702. if (density < 0) {
  57703. density *= -1;
  57704. hue = (hue + 180) % 360;
  57705. }
  57706. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  57707. result.scaleToRef(2, result);
  57708. result.a = 1 + 0.01 * saturation;
  57709. };
  57710. /**
  57711. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  57712. * @param value The input slider value in range [-100,100].
  57713. * @returns Adjusted value.
  57714. */
  57715. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  57716. value /= 100;
  57717. var x = Math.abs(value);
  57718. x = Math.pow(x, 2);
  57719. if (value < 0) {
  57720. x *= -1;
  57721. }
  57722. x *= 100;
  57723. return x;
  57724. };
  57725. /**
  57726. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  57727. * @param hue The hue (H) input.
  57728. * @param saturation The saturation (S) input.
  57729. * @param brightness The brightness (B) input.
  57730. * @result An RGBA color represented as Vector4.
  57731. */
  57732. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  57733. var h = ColorCurves.clamp(hue, 0, 360);
  57734. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  57735. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  57736. if (s === 0) {
  57737. result.r = v;
  57738. result.g = v;
  57739. result.b = v;
  57740. }
  57741. else {
  57742. // sector 0 to 5
  57743. h /= 60;
  57744. var i = Math.floor(h);
  57745. // fractional part of h
  57746. var f = h - i;
  57747. var p = v * (1 - s);
  57748. var q = v * (1 - s * f);
  57749. var t = v * (1 - s * (1 - f));
  57750. switch (i) {
  57751. case 0:
  57752. result.r = v;
  57753. result.g = t;
  57754. result.b = p;
  57755. break;
  57756. case 1:
  57757. result.r = q;
  57758. result.g = v;
  57759. result.b = p;
  57760. break;
  57761. case 2:
  57762. result.r = p;
  57763. result.g = v;
  57764. result.b = t;
  57765. break;
  57766. case 3:
  57767. result.r = p;
  57768. result.g = q;
  57769. result.b = v;
  57770. break;
  57771. case 4:
  57772. result.r = t;
  57773. result.g = p;
  57774. result.b = v;
  57775. break;
  57776. default:
  57777. result.r = v;
  57778. result.g = p;
  57779. result.b = q;
  57780. break;
  57781. }
  57782. }
  57783. result.a = 1;
  57784. };
  57785. /**
  57786. * Returns a value clamped between min and max
  57787. * @param value The value to clamp
  57788. * @param min The minimum of value
  57789. * @param max The maximum of value
  57790. * @returns The clamped value.
  57791. */
  57792. ColorCurves.clamp = function (value, min, max) {
  57793. return Math.min(Math.max(value, min), max);
  57794. };
  57795. /**
  57796. * Clones the current color curve instance.
  57797. * @return The cloned curves
  57798. */
  57799. ColorCurves.prototype.clone = function () {
  57800. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  57801. };
  57802. /**
  57803. * Serializes the current color curve instance to a json representation.
  57804. * @return a JSON representation
  57805. */
  57806. ColorCurves.prototype.serialize = function () {
  57807. return BABYLON.SerializationHelper.Serialize(this);
  57808. };
  57809. /**
  57810. * Parses the color curve from a json representation.
  57811. * @param source the JSON source to parse
  57812. * @return The parsed curves
  57813. */
  57814. ColorCurves.Parse = function (source) {
  57815. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  57816. };
  57817. return ColorCurves;
  57818. }());
  57819. __decorate([
  57820. BABYLON.serialize()
  57821. ], ColorCurves.prototype, "_globalHue", void 0);
  57822. __decorate([
  57823. BABYLON.serialize()
  57824. ], ColorCurves.prototype, "_globalDensity", void 0);
  57825. __decorate([
  57826. BABYLON.serialize()
  57827. ], ColorCurves.prototype, "_globalSaturation", void 0);
  57828. __decorate([
  57829. BABYLON.serialize()
  57830. ], ColorCurves.prototype, "_globalExposure", void 0);
  57831. __decorate([
  57832. BABYLON.serialize()
  57833. ], ColorCurves.prototype, "_highlightsHue", void 0);
  57834. __decorate([
  57835. BABYLON.serialize()
  57836. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  57837. __decorate([
  57838. BABYLON.serialize()
  57839. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  57840. __decorate([
  57841. BABYLON.serialize()
  57842. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  57843. __decorate([
  57844. BABYLON.serialize()
  57845. ], ColorCurves.prototype, "_midtonesHue", void 0);
  57846. __decorate([
  57847. BABYLON.serialize()
  57848. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  57849. __decorate([
  57850. BABYLON.serialize()
  57851. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  57852. __decorate([
  57853. BABYLON.serialize()
  57854. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  57855. BABYLON.ColorCurves = ColorCurves;
  57856. })(BABYLON || (BABYLON = {}));
  57857. //# sourceMappingURL=babylon.colorCurves.js.map
  57858. var BABYLON;
  57859. (function (BABYLON) {
  57860. var PBRMaterialDefines = (function (_super) {
  57861. __extends(PBRMaterialDefines, _super);
  57862. function PBRMaterialDefines() {
  57863. var _this = _super.call(this) || this;
  57864. _this.ALBEDO = false;
  57865. _this.AMBIENT = false;
  57866. _this.OPACITY = false;
  57867. _this.OPACITYRGB = false;
  57868. _this.REFLECTION = false;
  57869. _this.EMISSIVE = false;
  57870. _this.REFLECTIVITY = false;
  57871. _this.BUMP = false;
  57872. _this.PARALLAX = false;
  57873. _this.PARALLAXOCCLUSION = false;
  57874. _this.SPECULAROVERALPHA = false;
  57875. _this.CLIPPLANE = false;
  57876. _this.ALPHATEST = false;
  57877. _this.ALPHAFROMALBEDO = false;
  57878. _this.POINTSIZE = false;
  57879. _this.FOG = false;
  57880. _this.SPECULARTERM = false;
  57881. _this.OPACITYFRESNEL = false;
  57882. _this.EMISSIVEFRESNEL = false;
  57883. _this.FRESNEL = false;
  57884. _this.NORMAL = false;
  57885. _this.TANGENT = false;
  57886. _this.UV1 = false;
  57887. _this.UV2 = false;
  57888. _this.VERTEXCOLOR = false;
  57889. _this.VERTEXALPHA = false;
  57890. _this.NUM_BONE_INFLUENCERS = 0;
  57891. _this.BonesPerMesh = 0;
  57892. _this.INSTANCES = false;
  57893. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  57894. _this.MICROSURFACEAUTOMATIC = false;
  57895. _this.EMISSIVEASILLUMINATION = false;
  57896. _this.LINKEMISSIVEWITHALBEDO = false;
  57897. _this.LIGHTMAP = false;
  57898. _this.USELIGHTMAPASSHADOWMAP = false;
  57899. _this.REFLECTIONMAP_3D = false;
  57900. _this.REFLECTIONMAP_SPHERICAL = false;
  57901. _this.REFLECTIONMAP_PLANAR = false;
  57902. _this.REFLECTIONMAP_CUBIC = false;
  57903. _this.REFLECTIONMAP_PROJECTION = false;
  57904. _this.REFLECTIONMAP_SKYBOX = false;
  57905. _this.REFLECTIONMAP_EXPLICIT = false;
  57906. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  57907. _this.INVERTCUBICMAP = false;
  57908. _this.LOGARITHMICDEPTH = false;
  57909. _this.CAMERATONEMAP = false;
  57910. _this.CAMERACONTRAST = false;
  57911. _this.CAMERACOLORGRADING = false;
  57912. _this.CAMERACOLORCURVES = false;
  57913. _this.OVERLOADEDVALUES = false;
  57914. _this.OVERLOADEDSHADOWVALUES = false;
  57915. _this.USESPHERICALFROMREFLECTIONMAP = false;
  57916. _this.REFRACTION = false;
  57917. _this.REFRACTIONMAP_3D = false;
  57918. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  57919. _this.REFRACTIONMAPINLINEARSPACE = false;
  57920. _this.LODBASEDMICROSFURACE = false;
  57921. _this.USEPHYSICALLIGHTFALLOFF = false;
  57922. _this.RADIANCEOVERALPHA = false;
  57923. _this.USEPMREMREFLECTION = false;
  57924. _this.USEPMREMREFRACTION = false;
  57925. _this.OPENGLNORMALMAP = false;
  57926. _this.INVERTNORMALMAPX = false;
  57927. _this.INVERTNORMALMAPY = false;
  57928. _this.SHADOWFULLFLOAT = false;
  57929. _this.METALLICWORKFLOW = false;
  57930. _this.METALLICROUGHNESSMAP = false;
  57931. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  57932. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  57933. _this.rebuild();
  57934. return _this;
  57935. }
  57936. return PBRMaterialDefines;
  57937. }(BABYLON.MaterialDefines));
  57938. /**
  57939. * The Physically based material of BJS.
  57940. *
  57941. * This offers the main features of a standard PBR material.
  57942. * For more information, please refer to the documentation :
  57943. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  57944. */
  57945. var PBRMaterial = (function (_super) {
  57946. __extends(PBRMaterial, _super);
  57947. /**
  57948. * Instantiates a new PBRMaterial instance.
  57949. *
  57950. * @param name The material name
  57951. * @param scene The scene the material will be use in.
  57952. */
  57953. function PBRMaterial(name, scene) {
  57954. var _this = _super.call(this, name, scene) || this;
  57955. /**
  57956. * Intensity of the direct lights e.g. the four lights available in your scene.
  57957. * This impacts both the direct diffuse and specular highlights.
  57958. */
  57959. _this.directIntensity = 1.0;
  57960. /**
  57961. * Intensity of the emissive part of the material.
  57962. * This helps controlling the emissive effect without modifying the emissive color.
  57963. */
  57964. _this.emissiveIntensity = 1.0;
  57965. /**
  57966. * Intensity of the environment e.g. how much the environment will light the object
  57967. * either through harmonics for rough material or through the refelction for shiny ones.
  57968. */
  57969. _this.environmentIntensity = 1.0;
  57970. /**
  57971. * This is a special control allowing the reduction of the specular highlights coming from the
  57972. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  57973. */
  57974. _this.specularIntensity = 1.0;
  57975. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  57976. /**
  57977. * Debug Control allowing disabling the bump map on this material.
  57978. */
  57979. _this.disableBumpMap = false;
  57980. /**
  57981. * Debug Control helping enforcing or dropping the darkness of shadows.
  57982. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  57983. */
  57984. _this.overloadedShadowIntensity = 1.0;
  57985. /**
  57986. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  57987. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  57988. */
  57989. _this.overloadedShadeIntensity = 1.0;
  57990. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  57991. /**
  57992. * The camera exposure used on this material.
  57993. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  57994. * This corresponds to a photographic exposure.
  57995. */
  57996. _this.cameraExposure = 1.0;
  57997. /**
  57998. * The camera contrast used on this material.
  57999. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  58000. */
  58001. _this.cameraContrast = 1.0;
  58002. /**
  58003. * Color Grading 2D Lookup Texture.
  58004. * This allows special effects like sepia, black and white to sixties rendering style.
  58005. */
  58006. _this.cameraColorGradingTexture = null;
  58007. /**
  58008. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58009. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58010. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  58011. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58012. */
  58013. _this.cameraColorCurves = null;
  58014. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  58015. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  58016. /**
  58017. * Debug Control allowing to overload the ambient color.
  58018. * This as to be use with the overloadedAmbientIntensity parameter.
  58019. */
  58020. _this.overloadedAmbient = BABYLON.Color3.White();
  58021. /**
  58022. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  58023. */
  58024. _this.overloadedAmbientIntensity = 0.0;
  58025. /**
  58026. * Debug Control allowing to overload the albedo color.
  58027. * This as to be use with the overloadedAlbedoIntensity parameter.
  58028. */
  58029. _this.overloadedAlbedo = BABYLON.Color3.White();
  58030. /**
  58031. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  58032. */
  58033. _this.overloadedAlbedoIntensity = 0.0;
  58034. /**
  58035. * Debug Control allowing to overload the reflectivity color.
  58036. * This as to be use with the overloadedReflectivityIntensity parameter.
  58037. */
  58038. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  58039. /**
  58040. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  58041. */
  58042. _this.overloadedReflectivityIntensity = 0.0;
  58043. /**
  58044. * Debug Control allowing to overload the emissive color.
  58045. * This as to be use with the overloadedEmissiveIntensity parameter.
  58046. */
  58047. _this.overloadedEmissive = BABYLON.Color3.White();
  58048. /**
  58049. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  58050. */
  58051. _this.overloadedEmissiveIntensity = 0.0;
  58052. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  58053. /**
  58054. * Debug Control allowing to overload the reflection color.
  58055. * This as to be use with the overloadedReflectionIntensity parameter.
  58056. */
  58057. _this.overloadedReflection = BABYLON.Color3.White();
  58058. /**
  58059. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  58060. */
  58061. _this.overloadedReflectionIntensity = 0.0;
  58062. /**
  58063. * Debug Control allowing to overload the microsurface.
  58064. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  58065. */
  58066. _this.overloadedMicroSurface = 0.0;
  58067. /**
  58068. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  58069. */
  58070. _this.overloadedMicroSurfaceIntensity = 0.0;
  58071. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  58072. /**
  58073. * AKA Occlusion Texture Intensity in other nomenclature.
  58074. */
  58075. _this.ambientTextureStrength = 1.0;
  58076. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  58077. /**
  58078. * AKA Diffuse Color in other nomenclature.
  58079. */
  58080. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  58081. /**
  58082. * AKA Specular Color in other nomenclature.
  58083. */
  58084. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  58085. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  58086. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  58087. /**
  58088. * AKA Glossiness in other nomenclature.
  58089. */
  58090. _this.microSurface = 0.9;
  58091. /**
  58092. * source material index of refraction (IOR)' / 'destination material IOR.
  58093. */
  58094. _this.indexOfRefraction = 0.66;
  58095. /**
  58096. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  58097. */
  58098. _this.invertRefractionY = false;
  58099. /**
  58100. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  58101. * Materials half opaque for instance using refraction could benefit from this control.
  58102. */
  58103. _this.linkRefractionWithTransparency = false;
  58104. /**
  58105. * The emissive and albedo are linked to never be more than one (Energy conservation).
  58106. */
  58107. _this.linkEmissiveWithAlbedo = false;
  58108. _this.useLightmapAsShadowmap = false;
  58109. /**
  58110. * In this mode, the emissive informtaion will always be added to the lighting once.
  58111. * A light for instance can be thought as emissive.
  58112. */
  58113. _this.useEmissiveAsIllumination = false;
  58114. /**
  58115. * Secifies that the alpha is coming form the albedo channel alpha channel.
  58116. */
  58117. _this.useAlphaFromAlbedoTexture = false;
  58118. /**
  58119. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  58120. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  58121. */
  58122. _this.useSpecularOverAlpha = true;
  58123. /**
  58124. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  58125. */
  58126. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  58127. /**
  58128. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  58129. */
  58130. _this.useRoughnessFromMetallicTextureAlpha = true;
  58131. /**
  58132. * Specifies if the metallic texture contains the roughness information in its green channel.
  58133. */
  58134. _this.useRoughnessFromMetallicTextureGreen = false;
  58135. /**
  58136. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  58137. * The material will try to infer what glossiness each pixel should be.
  58138. */
  58139. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  58140. /**
  58141. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  58142. * the creation of the material.
  58143. */
  58144. _this.useScalarInLinearSpace = false;
  58145. /**
  58146. * BJS is using an harcoded light falloff based on a manually sets up range.
  58147. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  58148. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  58149. */
  58150. _this.usePhysicalLightFalloff = true;
  58151. /**
  58152. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  58153. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  58154. */
  58155. _this.useRadianceOverAlpha = true;
  58156. /**
  58157. * Allows using the bump map in parallax mode.
  58158. */
  58159. _this.useParallax = false;
  58160. /**
  58161. * Allows using the bump map in parallax occlusion mode.
  58162. */
  58163. _this.useParallaxOcclusion = false;
  58164. /**
  58165. * Controls the scale bias of the parallax mode.
  58166. */
  58167. _this.parallaxScaleBias = 0.05;
  58168. /**
  58169. * If sets to true, disables all the lights affecting the material.
  58170. */
  58171. _this.disableLighting = false;
  58172. /**
  58173. * Number of Simultaneous lights allowed on the material.
  58174. */
  58175. _this.maxSimultaneousLights = 4;
  58176. /**
  58177. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  58178. */
  58179. _this.invertNormalMapX = false;
  58180. /**
  58181. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  58182. */
  58183. _this.invertNormalMapY = false;
  58184. _this._renderTargets = new BABYLON.SmartArray(16);
  58185. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  58186. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  58187. _this._tempColor = new BABYLON.Color3();
  58188. _this._defines = new PBRMaterialDefines();
  58189. _this._cachedDefines = new PBRMaterialDefines();
  58190. _this._myScene = null;
  58191. _this._myShadowGenerator = null;
  58192. _this._cachedDefines.BonesPerMesh = -1;
  58193. _this.getRenderTargetTextures = function () {
  58194. _this._renderTargets.reset();
  58195. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  58196. _this._renderTargets.push(_this.reflectionTexture);
  58197. }
  58198. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  58199. _this._renderTargets.push(_this.refractionTexture);
  58200. }
  58201. return _this._renderTargets;
  58202. };
  58203. return _this;
  58204. }
  58205. PBRMaterial.prototype.getClassName = function () {
  58206. return "PBRMaterial";
  58207. };
  58208. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  58209. get: function () {
  58210. return this._useLogarithmicDepth;
  58211. },
  58212. set: function (value) {
  58213. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  58214. },
  58215. enumerable: true,
  58216. configurable: true
  58217. });
  58218. PBRMaterial.prototype.needAlphaBlending = function () {
  58219. if (this.linkRefractionWithTransparency) {
  58220. return false;
  58221. }
  58222. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  58223. };
  58224. PBRMaterial.prototype.needAlphaTesting = function () {
  58225. if (this.linkRefractionWithTransparency) {
  58226. return false;
  58227. }
  58228. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  58229. };
  58230. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  58231. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  58232. };
  58233. PBRMaterial.prototype.getAlphaTestTexture = function () {
  58234. return this.albedoTexture;
  58235. };
  58236. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58237. if (!mesh) {
  58238. return true;
  58239. }
  58240. if (this._defines.INSTANCES !== useInstances) {
  58241. return false;
  58242. }
  58243. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  58244. return true;
  58245. }
  58246. return false;
  58247. };
  58248. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  58249. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  58250. };
  58251. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  58252. if (!useScalarInLinear) {
  58253. color.toLinearSpaceToRef(ref);
  58254. }
  58255. else {
  58256. ref.r = color.r;
  58257. ref.g = color.g;
  58258. ref.b = color.b;
  58259. }
  58260. };
  58261. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  58262. var lightIndex = 0;
  58263. var depthValuesAlreadySet = false;
  58264. for (var index = 0; index < scene.lights.length; index++) {
  58265. var light = scene.lights[index];
  58266. if (!light.isEnabled()) {
  58267. continue;
  58268. }
  58269. if (!light.canAffectMesh(mesh)) {
  58270. continue;
  58271. }
  58272. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  58273. // GAMMA CORRECTION.
  58274. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  58275. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  58276. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  58277. if (defines["SPECULARTERM"]) {
  58278. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  58279. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  58280. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  58281. }
  58282. // Shadows
  58283. if (scene.shadowsEnabled) {
  58284. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  58285. }
  58286. lightIndex++;
  58287. if (lightIndex === maxSimultaneousLights)
  58288. break;
  58289. }
  58290. };
  58291. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  58292. if (this.isFrozen) {
  58293. if (this._wasPreviouslyReady) {
  58294. return true;
  58295. }
  58296. }
  58297. var scene = this.getScene();
  58298. var engine = scene.getEngine();
  58299. var needNormals = false;
  58300. var needUVs = false;
  58301. this._defines.reset();
  58302. if (scene.lightsEnabled && !this.disableLighting) {
  58303. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  58304. }
  58305. if (!this.checkReadyOnEveryCall) {
  58306. if (this._renderId === scene.getRenderId()) {
  58307. if (this._checkCache(scene, mesh, useInstances)) {
  58308. return true;
  58309. }
  58310. }
  58311. }
  58312. if (scene.texturesEnabled) {
  58313. if (scene.getEngine().getCaps().textureLOD) {
  58314. this._defines.LODBASEDMICROSFURACE = true;
  58315. }
  58316. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58317. if (!this.albedoTexture.isReady()) {
  58318. return false;
  58319. }
  58320. else {
  58321. needUVs = true;
  58322. this._defines.ALBEDO = true;
  58323. }
  58324. }
  58325. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  58326. if (!this.ambientTexture.isReady()) {
  58327. return false;
  58328. }
  58329. else {
  58330. needUVs = true;
  58331. this._defines.AMBIENT = true;
  58332. }
  58333. }
  58334. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  58335. if (!this.opacityTexture.isReady()) {
  58336. return false;
  58337. }
  58338. else {
  58339. needUVs = true;
  58340. this._defines.OPACITY = true;
  58341. if (this.opacityTexture.getAlphaFromRGB) {
  58342. this._defines.OPACITYRGB = true;
  58343. }
  58344. }
  58345. }
  58346. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  58347. if (!this.reflectionTexture.isReady()) {
  58348. return false;
  58349. }
  58350. else {
  58351. needNormals = true;
  58352. this._defines.REFLECTION = true;
  58353. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  58354. this._defines.INVERTCUBICMAP = true;
  58355. }
  58356. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  58357. switch (this.reflectionTexture.coordinatesMode) {
  58358. case BABYLON.Texture.CUBIC_MODE:
  58359. case BABYLON.Texture.INVCUBIC_MODE:
  58360. this._defines.REFLECTIONMAP_CUBIC = true;
  58361. break;
  58362. case BABYLON.Texture.EXPLICIT_MODE:
  58363. this._defines.REFLECTIONMAP_EXPLICIT = true;
  58364. break;
  58365. case BABYLON.Texture.PLANAR_MODE:
  58366. this._defines.REFLECTIONMAP_PLANAR = true;
  58367. break;
  58368. case BABYLON.Texture.PROJECTION_MODE:
  58369. this._defines.REFLECTIONMAP_PROJECTION = true;
  58370. break;
  58371. case BABYLON.Texture.SKYBOX_MODE:
  58372. this._defines.REFLECTIONMAP_SKYBOX = true;
  58373. break;
  58374. case BABYLON.Texture.SPHERICAL_MODE:
  58375. this._defines.REFLECTIONMAP_SPHERICAL = true;
  58376. break;
  58377. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  58378. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  58379. break;
  58380. }
  58381. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  58382. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  58383. needNormals = true;
  58384. if (this.reflectionTexture.isPMREM) {
  58385. this._defines.USEPMREMREFLECTION = true;
  58386. }
  58387. }
  58388. }
  58389. }
  58390. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  58391. if (!this.lightmapTexture.isReady()) {
  58392. return false;
  58393. }
  58394. else {
  58395. needUVs = true;
  58396. this._defines.LIGHTMAP = true;
  58397. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  58398. }
  58399. }
  58400. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  58401. if (!this.emissiveTexture.isReady()) {
  58402. return false;
  58403. }
  58404. else {
  58405. needUVs = true;
  58406. this._defines.EMISSIVE = true;
  58407. }
  58408. }
  58409. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  58410. if (this.metallicTexture) {
  58411. if (!this.metallicTexture.isReady()) {
  58412. return false;
  58413. }
  58414. else {
  58415. needUVs = true;
  58416. this._defines.METALLICWORKFLOW = true;
  58417. this._defines.METALLICROUGHNESSMAP = true;
  58418. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  58419. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  58420. }
  58421. }
  58422. else if (this.reflectivityTexture) {
  58423. if (!this.reflectivityTexture.isReady()) {
  58424. return false;
  58425. }
  58426. else {
  58427. needUVs = true;
  58428. this._defines.REFLECTIVITY = true;
  58429. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  58430. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  58431. }
  58432. }
  58433. }
  58434. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  58435. if (!this.bumpTexture.isReady()) {
  58436. return false;
  58437. }
  58438. else {
  58439. needUVs = true;
  58440. this._defines.BUMP = true;
  58441. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58442. this._defines.PARALLAX = true;
  58443. if (this.useParallaxOcclusion) {
  58444. this._defines.PARALLAXOCCLUSION = true;
  58445. }
  58446. }
  58447. if (this.invertNormalMapX) {
  58448. this._defines.INVERTNORMALMAPX = true;
  58449. }
  58450. if (this.invertNormalMapY) {
  58451. this._defines.INVERTNORMALMAPY = true;
  58452. }
  58453. if (scene._mirroredCameraPosition) {
  58454. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  58455. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  58456. }
  58457. }
  58458. }
  58459. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  58460. if (!this.refractionTexture.isReady()) {
  58461. return false;
  58462. }
  58463. else {
  58464. needUVs = true;
  58465. this._defines.REFRACTION = true;
  58466. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  58467. if (this.linkRefractionWithTransparency) {
  58468. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  58469. }
  58470. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  58471. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  58472. if (this.refractionTexture.isPMREM) {
  58473. this._defines.USEPMREMREFRACTION = true;
  58474. }
  58475. }
  58476. }
  58477. }
  58478. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  58479. if (!this.cameraColorGradingTexture.isReady()) {
  58480. return false;
  58481. }
  58482. else {
  58483. this._defines.CAMERACOLORGRADING = true;
  58484. }
  58485. }
  58486. }
  58487. // Effect
  58488. if (scene.clipPlane) {
  58489. this._defines.CLIPPLANE = true;
  58490. }
  58491. if (engine.getAlphaTesting()) {
  58492. this._defines.ALPHATEST = true;
  58493. }
  58494. if (this._shouldUseAlphaFromAlbedoTexture()) {
  58495. this._defines.ALPHAFROMALBEDO = true;
  58496. }
  58497. if (this.useEmissiveAsIllumination) {
  58498. this._defines.EMISSIVEASILLUMINATION = true;
  58499. }
  58500. if (this.linkEmissiveWithAlbedo) {
  58501. this._defines.LINKEMISSIVEWITHALBEDO = true;
  58502. }
  58503. if (this.useLogarithmicDepth) {
  58504. this._defines.LOGARITHMICDEPTH = true;
  58505. }
  58506. if (this.cameraContrast != 1) {
  58507. this._defines.CAMERACONTRAST = true;
  58508. }
  58509. if (this.cameraExposure != 1) {
  58510. this._defines.CAMERATONEMAP = true;
  58511. }
  58512. if (this.cameraColorCurves) {
  58513. this._defines.CAMERACOLORCURVES = true;
  58514. }
  58515. if (this.overloadedShadeIntensity != 1 ||
  58516. this.overloadedShadowIntensity != 1) {
  58517. this._defines.OVERLOADEDSHADOWVALUES = true;
  58518. }
  58519. if (this.overloadedMicroSurfaceIntensity > 0 ||
  58520. this.overloadedEmissiveIntensity > 0 ||
  58521. this.overloadedReflectivityIntensity > 0 ||
  58522. this.overloadedAlbedoIntensity > 0 ||
  58523. this.overloadedAmbientIntensity > 0 ||
  58524. this.overloadedReflectionIntensity > 0) {
  58525. this._defines.OVERLOADEDVALUES = true;
  58526. }
  58527. // Point size
  58528. if (this.pointsCloud || scene.forcePointsCloud) {
  58529. this._defines.POINTSIZE = true;
  58530. }
  58531. // Fog
  58532. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  58533. this._defines.FOG = true;
  58534. }
  58535. if (BABYLON.StandardMaterial.FresnelEnabled) {
  58536. // Fresnel
  58537. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  58538. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58539. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  58540. this._defines.OPACITYFRESNEL = true;
  58541. }
  58542. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58543. this._defines.EMISSIVEFRESNEL = true;
  58544. }
  58545. needNormals = true;
  58546. this._defines.FRESNEL = true;
  58547. }
  58548. }
  58549. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  58550. this._defines.SPECULAROVERALPHA = true;
  58551. }
  58552. if (this.usePhysicalLightFalloff) {
  58553. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  58554. }
  58555. if (this.useRadianceOverAlpha) {
  58556. this._defines.RADIANCEOVERALPHA = true;
  58557. }
  58558. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  58559. this._defines.METALLICWORKFLOW = true;
  58560. }
  58561. // Attribs
  58562. if (mesh) {
  58563. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  58564. this._defines.NORMAL = true;
  58565. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  58566. this._defines.TANGENT = true;
  58567. }
  58568. }
  58569. if (needUVs) {
  58570. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58571. this._defines.UV1 = true;
  58572. }
  58573. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58574. this._defines.UV2 = true;
  58575. }
  58576. }
  58577. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58578. this._defines.VERTEXCOLOR = true;
  58579. if (mesh.hasVertexAlpha) {
  58580. this._defines.VERTEXALPHA = true;
  58581. }
  58582. }
  58583. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58584. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  58585. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  58586. }
  58587. // Instances
  58588. if (useInstances) {
  58589. this._defines.INSTANCES = true;
  58590. }
  58591. }
  58592. // Get correct effect
  58593. if (!this._defines.isEqual(this._cachedDefines)) {
  58594. this._defines.cloneTo(this._cachedDefines);
  58595. scene.resetCachedMaterial();
  58596. // Fallbacks
  58597. var fallbacks = new BABYLON.EffectFallbacks();
  58598. if (this._defines.REFLECTION) {
  58599. fallbacks.addFallback(0, "REFLECTION");
  58600. }
  58601. if (this._defines.REFRACTION) {
  58602. fallbacks.addFallback(0, "REFRACTION");
  58603. }
  58604. if (this._defines.REFLECTIVITY) {
  58605. fallbacks.addFallback(0, "REFLECTIVITY");
  58606. }
  58607. if (this._defines.BUMP) {
  58608. fallbacks.addFallback(0, "BUMP");
  58609. }
  58610. if (this._defines.PARALLAX) {
  58611. fallbacks.addFallback(1, "PARALLAX");
  58612. }
  58613. if (this._defines.PARALLAXOCCLUSION) {
  58614. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  58615. }
  58616. if (this._defines.SPECULAROVERALPHA) {
  58617. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  58618. }
  58619. if (this._defines.FOG) {
  58620. fallbacks.addFallback(1, "FOG");
  58621. }
  58622. if (this._defines.POINTSIZE) {
  58623. fallbacks.addFallback(0, "POINTSIZE");
  58624. }
  58625. if (this._defines.LOGARITHMICDEPTH) {
  58626. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  58627. }
  58628. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  58629. if (this._defines.SPECULARTERM) {
  58630. fallbacks.addFallback(0, "SPECULARTERM");
  58631. }
  58632. if (this._defines.OPACITYFRESNEL) {
  58633. fallbacks.addFallback(1, "OPACITYFRESNEL");
  58634. }
  58635. if (this._defines.EMISSIVEFRESNEL) {
  58636. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  58637. }
  58638. if (this._defines.FRESNEL) {
  58639. fallbacks.addFallback(3, "FRESNEL");
  58640. }
  58641. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  58642. fallbacks.addCPUSkinningFallback(0, mesh);
  58643. }
  58644. //Attributes
  58645. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58646. if (this._defines.NORMAL) {
  58647. attribs.push(BABYLON.VertexBuffer.NormalKind);
  58648. }
  58649. if (this._defines.TANGENT) {
  58650. attribs.push(BABYLON.VertexBuffer.TangentKind);
  58651. }
  58652. if (this._defines.UV1) {
  58653. attribs.push(BABYLON.VertexBuffer.UVKind);
  58654. }
  58655. if (this._defines.UV2) {
  58656. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58657. }
  58658. if (this._defines.VERTEXCOLOR) {
  58659. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58660. }
  58661. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  58662. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  58663. // Legacy browser patch
  58664. var join = this._defines.toString();
  58665. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  58666. "vFogInfos", "vFogColor", "pointSize",
  58667. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  58668. "mBones",
  58669. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  58670. "depthValues",
  58671. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  58672. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  58673. "logarithmicDepthConstant",
  58674. "vSphericalX", "vSphericalY", "vSphericalZ",
  58675. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  58676. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  58677. "vMicrosurfaceTextureLods",
  58678. "vCameraInfos"
  58679. ];
  58680. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  58681. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  58682. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  58683. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  58684. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  58685. }
  58686. if (!this._effect.isReady()) {
  58687. return false;
  58688. }
  58689. this._renderId = scene.getRenderId();
  58690. this._wasPreviouslyReady = true;
  58691. if (mesh) {
  58692. if (!mesh._materialDefines) {
  58693. mesh._materialDefines = new PBRMaterialDefines();
  58694. }
  58695. this._defines.cloneTo(mesh._materialDefines);
  58696. }
  58697. return true;
  58698. };
  58699. PBRMaterial.prototype.unbind = function () {
  58700. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  58701. this._effect.setTexture("reflection2DSampler", null);
  58702. }
  58703. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  58704. this._effect.setTexture("refraction2DSampler", null);
  58705. }
  58706. _super.prototype.unbind.call(this);
  58707. };
  58708. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58709. this._effect.setMatrix("world", world);
  58710. };
  58711. PBRMaterial.prototype.bind = function (world, mesh) {
  58712. this._myScene = this.getScene();
  58713. // Matrices
  58714. this.bindOnlyWorldMatrix(world);
  58715. // Bones
  58716. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58717. if (this._myScene.getCachedMaterial() !== this) {
  58718. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  58719. if (BABYLON.StandardMaterial.FresnelEnabled) {
  58720. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  58721. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  58722. }
  58723. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58724. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  58725. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  58726. }
  58727. }
  58728. // Textures
  58729. if (this._myScene.texturesEnabled) {
  58730. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58731. this._effect.setTexture("albedoSampler", this.albedoTexture);
  58732. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  58733. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  58734. }
  58735. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  58736. this._effect.setTexture("ambientSampler", this.ambientTexture);
  58737. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  58738. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  58739. }
  58740. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  58741. this._effect.setTexture("opacitySampler", this.opacityTexture);
  58742. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  58743. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  58744. }
  58745. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  58746. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  58747. if (this.reflectionTexture.isCube) {
  58748. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  58749. }
  58750. else {
  58751. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  58752. }
  58753. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  58754. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  58755. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  58756. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  58757. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  58758. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  58759. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  58760. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  58761. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  58762. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  58763. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  58764. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  58765. }
  58766. }
  58767. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  58768. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  58769. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  58770. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  58771. }
  58772. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  58773. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  58774. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  58775. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  58776. }
  58777. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  58778. if (this.metallicTexture) {
  58779. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  58780. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  58781. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  58782. }
  58783. else if (this.reflectivityTexture) {
  58784. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  58785. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  58786. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  58787. }
  58788. }
  58789. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  58790. this._effect.setTexture("bumpSampler", this.bumpTexture);
  58791. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  58792. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  58793. }
  58794. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  58795. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  58796. var depth = 1.0;
  58797. if (this.refractionTexture.isCube) {
  58798. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  58799. }
  58800. else {
  58801. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  58802. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  58803. if (this.refractionTexture.depth) {
  58804. depth = this.refractionTexture.depth;
  58805. }
  58806. }
  58807. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  58808. }
  58809. if ((this.reflectionTexture || this.refractionTexture)) {
  58810. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  58811. }
  58812. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  58813. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  58814. }
  58815. }
  58816. // Clip plane
  58817. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  58818. // Point size
  58819. if (this.pointsCloud) {
  58820. this._effect.setFloat("pointSize", this.pointSize);
  58821. }
  58822. // Colors
  58823. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  58824. if (this._defines.METALLICWORKFLOW) {
  58825. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  58826. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  58827. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  58828. }
  58829. else {
  58830. // GAMMA CORRECTION.
  58831. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  58832. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  58833. }
  58834. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  58835. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  58836. // GAMMA CORRECTION.
  58837. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  58838. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  58839. // GAMMA CORRECTION.
  58840. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  58841. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  58842. }
  58843. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  58844. // GAMMA CORRECTION.
  58845. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  58846. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  58847. // Lights
  58848. if (this._myScene.lightsEnabled && !this.disableLighting) {
  58849. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  58850. }
  58851. // View
  58852. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  58853. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  58854. }
  58855. // Fog
  58856. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  58857. this._lightingInfos.x = this.directIntensity;
  58858. this._lightingInfos.y = this.emissiveIntensity;
  58859. this._lightingInfos.z = this.environmentIntensity;
  58860. this._lightingInfos.w = this.specularIntensity;
  58861. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  58862. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  58863. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  58864. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  58865. this._cameraInfos.x = this.cameraExposure;
  58866. this._cameraInfos.y = this.cameraContrast;
  58867. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  58868. if (this.cameraColorCurves) {
  58869. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  58870. }
  58871. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  58872. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  58873. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  58874. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  58875. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  58876. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  58877. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  58878. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  58879. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  58880. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  58881. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  58882. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  58883. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  58884. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  58885. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  58886. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  58887. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  58888. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  58889. // Log. depth
  58890. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  58891. }
  58892. _super.prototype.bind.call(this, world, mesh);
  58893. this._myScene = null;
  58894. };
  58895. PBRMaterial.prototype.getAnimatables = function () {
  58896. var results = [];
  58897. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  58898. results.push(this.albedoTexture);
  58899. }
  58900. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  58901. results.push(this.ambientTexture);
  58902. }
  58903. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  58904. results.push(this.opacityTexture);
  58905. }
  58906. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  58907. results.push(this.reflectionTexture);
  58908. }
  58909. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  58910. results.push(this.emissiveTexture);
  58911. }
  58912. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  58913. results.push(this.metallicTexture);
  58914. }
  58915. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  58916. results.push(this.reflectivityTexture);
  58917. }
  58918. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  58919. results.push(this.bumpTexture);
  58920. }
  58921. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  58922. results.push(this.lightmapTexture);
  58923. }
  58924. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  58925. results.push(this.refractionTexture);
  58926. }
  58927. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  58928. results.push(this.cameraColorGradingTexture);
  58929. }
  58930. return results;
  58931. };
  58932. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58933. if (forceDisposeTextures) {
  58934. if (this.albedoTexture) {
  58935. this.albedoTexture.dispose();
  58936. }
  58937. if (this.ambientTexture) {
  58938. this.ambientTexture.dispose();
  58939. }
  58940. if (this.opacityTexture) {
  58941. this.opacityTexture.dispose();
  58942. }
  58943. if (this.reflectionTexture) {
  58944. this.reflectionTexture.dispose();
  58945. }
  58946. if (this.emissiveTexture) {
  58947. this.emissiveTexture.dispose();
  58948. }
  58949. if (this.metallicTexture) {
  58950. this.metallicTexture.dispose();
  58951. }
  58952. if (this.reflectivityTexture) {
  58953. this.reflectivityTexture.dispose();
  58954. }
  58955. if (this.bumpTexture) {
  58956. this.bumpTexture.dispose();
  58957. }
  58958. if (this.lightmapTexture) {
  58959. this.lightmapTexture.dispose();
  58960. }
  58961. if (this.refractionTexture) {
  58962. this.refractionTexture.dispose();
  58963. }
  58964. if (this.cameraColorGradingTexture) {
  58965. this.cameraColorGradingTexture.dispose();
  58966. }
  58967. }
  58968. this._renderTargets.dispose();
  58969. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58970. };
  58971. PBRMaterial.prototype.clone = function (name) {
  58972. var _this = this;
  58973. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  58974. };
  58975. PBRMaterial.prototype.serialize = function () {
  58976. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58977. serializationObject.customType = "BABYLON.PBRMaterial";
  58978. return serializationObject;
  58979. };
  58980. // Statics
  58981. PBRMaterial.Parse = function (source, scene, rootUrl) {
  58982. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  58983. };
  58984. return PBRMaterial;
  58985. }(BABYLON.Material));
  58986. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  58987. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  58988. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  58989. PBRMaterial._scaledReflection = new BABYLON.Color3();
  58990. __decorate([
  58991. BABYLON.serialize()
  58992. ], PBRMaterial.prototype, "directIntensity", void 0);
  58993. __decorate([
  58994. BABYLON.serialize()
  58995. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  58996. __decorate([
  58997. BABYLON.serialize()
  58998. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  58999. __decorate([
  59000. BABYLON.serialize()
  59001. ], PBRMaterial.prototype, "specularIntensity", void 0);
  59002. __decorate([
  59003. BABYLON.serialize()
  59004. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  59005. __decorate([
  59006. BABYLON.serialize()
  59007. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  59008. __decorate([
  59009. BABYLON.serialize()
  59010. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  59011. __decorate([
  59012. BABYLON.serialize()
  59013. ], PBRMaterial.prototype, "cameraExposure", void 0);
  59014. __decorate([
  59015. BABYLON.serialize()
  59016. ], PBRMaterial.prototype, "cameraContrast", void 0);
  59017. __decorate([
  59018. BABYLON.serializeAsTexture()
  59019. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  59020. __decorate([
  59021. BABYLON.serializeAsColorCurves()
  59022. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  59023. __decorate([
  59024. BABYLON.serializeAsColor3()
  59025. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  59026. __decorate([
  59027. BABYLON.serialize()
  59028. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  59029. __decorate([
  59030. BABYLON.serializeAsColor3()
  59031. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  59032. __decorate([
  59033. BABYLON.serialize()
  59034. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  59035. __decorate([
  59036. BABYLON.serializeAsColor3()
  59037. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  59038. __decorate([
  59039. BABYLON.serialize()
  59040. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  59041. __decorate([
  59042. BABYLON.serializeAsColor3()
  59043. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  59044. __decorate([
  59045. BABYLON.serialize()
  59046. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  59047. __decorate([
  59048. BABYLON.serializeAsColor3()
  59049. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  59050. __decorate([
  59051. BABYLON.serialize()
  59052. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  59053. __decorate([
  59054. BABYLON.serialize()
  59055. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  59056. __decorate([
  59057. BABYLON.serialize()
  59058. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  59059. __decorate([
  59060. BABYLON.serializeAsTexture()
  59061. ], PBRMaterial.prototype, "albedoTexture", void 0);
  59062. __decorate([
  59063. BABYLON.serializeAsTexture()
  59064. ], PBRMaterial.prototype, "ambientTexture", void 0);
  59065. __decorate([
  59066. BABYLON.serialize()
  59067. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  59068. __decorate([
  59069. BABYLON.serializeAsTexture()
  59070. ], PBRMaterial.prototype, "opacityTexture", void 0);
  59071. __decorate([
  59072. BABYLON.serializeAsTexture()
  59073. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  59074. __decorate([
  59075. BABYLON.serializeAsTexture()
  59076. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  59077. __decorate([
  59078. BABYLON.serializeAsTexture()
  59079. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  59080. __decorate([
  59081. BABYLON.serializeAsTexture()
  59082. ], PBRMaterial.prototype, "metallicTexture", void 0);
  59083. __decorate([
  59084. BABYLON.serialize()
  59085. ], PBRMaterial.prototype, "metallic", void 0);
  59086. __decorate([
  59087. BABYLON.serialize()
  59088. ], PBRMaterial.prototype, "roughness", void 0);
  59089. __decorate([
  59090. BABYLON.serializeAsTexture()
  59091. ], PBRMaterial.prototype, "bumpTexture", void 0);
  59092. __decorate([
  59093. BABYLON.serializeAsTexture()
  59094. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  59095. __decorate([
  59096. BABYLON.serializeAsTexture()
  59097. ], PBRMaterial.prototype, "refractionTexture", void 0);
  59098. __decorate([
  59099. BABYLON.serializeAsColor3("ambient")
  59100. ], PBRMaterial.prototype, "ambientColor", void 0);
  59101. __decorate([
  59102. BABYLON.serializeAsColor3("albedo")
  59103. ], PBRMaterial.prototype, "albedoColor", void 0);
  59104. __decorate([
  59105. BABYLON.serializeAsColor3("reflectivity")
  59106. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  59107. __decorate([
  59108. BABYLON.serializeAsColor3("reflection")
  59109. ], PBRMaterial.prototype, "reflectionColor", void 0);
  59110. __decorate([
  59111. BABYLON.serializeAsColor3("emissive")
  59112. ], PBRMaterial.prototype, "emissiveColor", void 0);
  59113. __decorate([
  59114. BABYLON.serialize()
  59115. ], PBRMaterial.prototype, "microSurface", void 0);
  59116. __decorate([
  59117. BABYLON.serialize()
  59118. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  59119. __decorate([
  59120. BABYLON.serialize()
  59121. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  59122. __decorate([
  59123. BABYLON.serializeAsFresnelParameters()
  59124. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  59125. __decorate([
  59126. BABYLON.serializeAsFresnelParameters()
  59127. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  59128. __decorate([
  59129. BABYLON.serialize()
  59130. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  59131. __decorate([
  59132. BABYLON.serialize()
  59133. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  59134. __decorate([
  59135. BABYLON.serialize()
  59136. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  59137. __decorate([
  59138. BABYLON.serialize()
  59139. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  59140. __decorate([
  59141. BABYLON.serialize()
  59142. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  59143. __decorate([
  59144. BABYLON.serialize()
  59145. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  59146. __decorate([
  59147. BABYLON.serialize()
  59148. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  59149. __decorate([
  59150. BABYLON.serialize()
  59151. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  59152. __decorate([
  59153. BABYLON.serialize()
  59154. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  59155. __decorate([
  59156. BABYLON.serialize()
  59157. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  59158. __decorate([
  59159. BABYLON.serialize()
  59160. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  59161. __decorate([
  59162. BABYLON.serialize()
  59163. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  59164. __decorate([
  59165. BABYLON.serialize()
  59166. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  59167. __decorate([
  59168. BABYLON.serialize()
  59169. ], PBRMaterial.prototype, "useParallax", void 0);
  59170. __decorate([
  59171. BABYLON.serialize()
  59172. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  59173. __decorate([
  59174. BABYLON.serialize()
  59175. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  59176. __decorate([
  59177. BABYLON.serialize()
  59178. ], PBRMaterial.prototype, "disableLighting", void 0);
  59179. __decorate([
  59180. BABYLON.serialize()
  59181. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  59182. __decorate([
  59183. BABYLON.serialize()
  59184. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  59185. __decorate([
  59186. BABYLON.serialize()
  59187. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  59188. __decorate([
  59189. BABYLON.serialize()
  59190. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  59191. BABYLON.PBRMaterial = PBRMaterial;
  59192. })(BABYLON || (BABYLON = {}));
  59193. //# sourceMappingURL=babylon.pbrMaterial.js.map
  59194. var BABYLON;
  59195. (function (BABYLON) {
  59196. var DebugLayer = (function () {
  59197. function DebugLayer(scene) {
  59198. this._scene = scene;
  59199. }
  59200. /** Creates the inspector window. */
  59201. DebugLayer.prototype._createInspector = function (config) {
  59202. if (config === void 0) { config = {}; }
  59203. var popup = config.popup || false;
  59204. var initialTab = config.initialTab || 0;
  59205. var parentElement = config.parentElement || null;
  59206. if (!this._inspector) {
  59207. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement);
  59208. } // else nothing to do,; instance is already existing
  59209. };
  59210. DebugLayer.prototype.isVisible = function () {
  59211. if (!this._inspector) {
  59212. return false;
  59213. }
  59214. return true;
  59215. };
  59216. DebugLayer.prototype.hide = function () {
  59217. if (this._inspector) {
  59218. this._inspector.dispose();
  59219. this._inspector = null;
  59220. }
  59221. };
  59222. DebugLayer.prototype.show = function (config) {
  59223. if (config === void 0) { config = {}; }
  59224. if (typeof INSPECTOR == 'undefined') {
  59225. // Load inspector and add it to the DOM
  59226. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  59227. }
  59228. else {
  59229. // Otherwise creates the inspector
  59230. this._createInspector(config);
  59231. }
  59232. };
  59233. return DebugLayer;
  59234. }());
  59235. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  59236. BABYLON.DebugLayer = DebugLayer;
  59237. })(BABYLON || (BABYLON = {}));
  59238. //# sourceMappingURL=babylon.debugLayer.js.map
  59239. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  59240. var BABYLON;
  59241. (function (BABYLON) {
  59242. var StandardRenderingPipeline = (function (_super) {
  59243. __extends(StandardRenderingPipeline, _super);
  59244. /**
  59245. * @constructor
  59246. * @param {string} name - The rendering pipeline name
  59247. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59248. * @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)
  59249. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  59250. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59251. */
  59252. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  59253. if (originalPostProcess === void 0) { originalPostProcess = null; }
  59254. var _this = _super.call(this, scene.getEngine(), name) || this;
  59255. _this.downSampleX4PostProcess = null;
  59256. _this.brightPassPostProcess = null;
  59257. _this.gaussianBlurHPostProcesses = [];
  59258. _this.gaussianBlurVPostProcesses = [];
  59259. _this.textureAdderPostProcess = null;
  59260. _this.textureAdderFinalPostProcess = null;
  59261. _this.lensFlareFinalPostProcess = null;
  59262. _this.lensFlarePostProcess = null;
  59263. _this.lensFlareComposePostProcess = null;
  59264. _this.depthOfFieldPostProcess = null;
  59265. // Values
  59266. _this.brightThreshold = 1.0;
  59267. _this.blurWidth = 2.0;
  59268. _this.horizontalBlur = false;
  59269. _this.gaussianCoefficient = 0.25;
  59270. _this.gaussianMean = 1.0;
  59271. _this.gaussianStandardDeviation = 1.0;
  59272. _this.exposure = 1.0;
  59273. _this.lensTexture = null;
  59274. _this.lensColorTexture = null;
  59275. _this.lensFlareStrength = 20.0;
  59276. _this.lensFlareGhostDispersal = 1.4;
  59277. _this.lensFlareHaloWidth = 0.7;
  59278. _this.lensFlareDistortionStrength = 16.0;
  59279. _this.lensStarTexture = null;
  59280. _this.lensFlareDirtTexture = null;
  59281. _this.depthOfFieldDistance = 10.0;
  59282. _this.depthOfFieldBlurWidth = 2.0;
  59283. // IAnimatable
  59284. _this.animations = [];
  59285. _this._depthRenderer = null;
  59286. _this._currentDepthOfFieldSource = null;
  59287. // Getters and setters
  59288. _this._depthOfFieldEnabled = true;
  59289. _this._lensFlareEnabled = true;
  59290. // Initialize
  59291. _this._scene = scene;
  59292. // Create pass post-processe
  59293. if (!originalPostProcess) {
  59294. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  59295. }
  59296. else {
  59297. _this.originalPostProcess = originalPostProcess;
  59298. }
  59299. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  59300. // Create down sample X4 post-process
  59301. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  59302. // Create bright pass post-process
  59303. _this._createBrightPassPostProcess(scene, ratio / 2);
  59304. // Create gaussian blur post-processes (down sampling blurs)
  59305. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  59306. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  59307. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  59308. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  59309. // Create texture adder post-process
  59310. _this._createTextureAdderPostProcess(scene, ratio);
  59311. // Create depth-of-field source post-process
  59312. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59313. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  59314. // Create lens flare post-process
  59315. _this._createLensFlarePostProcess(scene, ratio);
  59316. // Create depth-of-field source post-process post lens-flare and disable it now
  59317. _this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59318. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  59319. // Create gaussian blur used by depth-of-field
  59320. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  59321. // Create depth-of-field post-process
  59322. _this._createDepthOfFieldPostProcess(scene, ratio);
  59323. // Finish
  59324. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59325. if (cameras !== null) {
  59326. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59327. }
  59328. // Deactivate
  59329. _this.LensFlareEnabled = false;
  59330. _this.DepthOfFieldEnabled = false;
  59331. return _this;
  59332. }
  59333. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  59334. get: function () {
  59335. return this._depthOfFieldEnabled;
  59336. },
  59337. set: function (enabled) {
  59338. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  59339. if (enabled && !this._depthOfFieldEnabled) {
  59340. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59341. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59342. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  59343. this._depthRenderer = this._scene.enableDepthRenderer();
  59344. }
  59345. else if (!enabled && this._depthOfFieldEnabled) {
  59346. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59347. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59348. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  59349. }
  59350. this._depthOfFieldEnabled = enabled;
  59351. },
  59352. enumerable: true,
  59353. configurable: true
  59354. });
  59355. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  59356. get: function () {
  59357. return this._lensFlareEnabled;
  59358. },
  59359. set: function (enabled) {
  59360. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  59361. if (enabled && !this._lensFlareEnabled) {
  59362. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  59363. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  59364. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59365. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59366. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  59367. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  59368. }
  59369. else if (!enabled && this._lensFlareEnabled) {
  59370. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  59371. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  59372. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59373. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59374. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  59375. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  59376. }
  59377. this._lensFlareEnabled = enabled;
  59378. },
  59379. enumerable: true,
  59380. configurable: true
  59381. });
  59382. // Sets depth-of-field save post-process
  59383. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  59384. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  59385. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._scene.cameras);
  59386. switch (name) {
  59387. case "HDRBaseDepthOfFieldSource":
  59388. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  59389. break;
  59390. case "HDRPostLensFlareDepthOfFieldSource":
  59391. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  59392. break;
  59393. default: break;
  59394. }
  59395. };
  59396. // Down Sample X4 Post-Processs
  59397. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  59398. var _this = this;
  59399. var downSampleX4Offsets = new Array(32);
  59400. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59401. this.downSampleX4PostProcess.onApply = function (effect) {
  59402. var id = 0;
  59403. for (var i = -2; i < 2; i++) {
  59404. for (var j = -2; j < 2; j++) {
  59405. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  59406. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  59407. id += 2;
  59408. }
  59409. }
  59410. effect.setArray2("dsOffsets", downSampleX4Offsets);
  59411. };
  59412. // Add to pipeline
  59413. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  59414. };
  59415. // Brightpass Post-Process
  59416. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  59417. var _this = this;
  59418. var brightOffsets = new Array(8);
  59419. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59420. this.brightPassPostProcess.onApply = function (effect) {
  59421. var sU = (1.0 / _this.brightPassPostProcess.width);
  59422. var sV = (1.0 / _this.brightPassPostProcess.height);
  59423. brightOffsets[0] = -0.5 * sU;
  59424. brightOffsets[1] = 0.5 * sV;
  59425. brightOffsets[2] = 0.5 * sU;
  59426. brightOffsets[3] = 0.5 * sV;
  59427. brightOffsets[4] = -0.5 * sU;
  59428. brightOffsets[5] = -0.5 * sV;
  59429. brightOffsets[6] = 0.5 * sU;
  59430. brightOffsets[7] = -0.5 * sV;
  59431. effect.setArray2("dsOffsets", brightOffsets);
  59432. effect.setFloat("brightThreshold", _this.brightThreshold);
  59433. };
  59434. // Add to pipeline
  59435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59436. };
  59437. // Create gaussian blur H&V post-processes
  59438. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59439. var _this = this;
  59440. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59441. var blurOffsets = new Array(9);
  59442. var blurWeights = new Array(9);
  59443. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  59444. var callback = function (height) {
  59445. return function (effect) {
  59446. // Weights
  59447. var x = 0.0;
  59448. for (var i = 0; i < 9; i++) {
  59449. x = (i - 4.0) / 4.0;
  59450. blurWeights[i] =
  59451. _this.gaussianCoefficient
  59452. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  59453. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  59454. }
  59455. var lastOutputDimensions = {
  59456. width: scene.getEngine().getRenderWidth(),
  59457. height: scene.getEngine().getRenderHeight()
  59458. };
  59459. for (var i = 0; i < 9; i++) {
  59460. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  59461. blurOffsets[i] = value;
  59462. }
  59463. effect.setArray("blurOffsets", blurOffsets);
  59464. effect.setArray("blurWeights", blurWeights);
  59465. if (height) {
  59466. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  59467. }
  59468. else {
  59469. effect.setFloat("blurWidth", _this[blurWidthKey]);
  59470. }
  59471. };
  59472. };
  59473. // Create horizontal gaussian blur post-processes
  59474. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59475. gaussianBlurHPostProcess.onApply = callback(false);
  59476. // Create vertical gaussian blur post-process
  59477. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59478. gaussianBlurVPostProcess.onApply = callback(true);
  59479. // Add to pipeline
  59480. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  59481. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  59482. // Finish
  59483. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  59484. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  59485. };
  59486. // Create texture adder post-process
  59487. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59488. var _this = this;
  59489. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59490. this.textureAdderPostProcess.onApply = function (effect) {
  59491. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  59492. effect.setTexture("lensSampler", _this.lensTexture);
  59493. effect.setFloat("exposure", _this.exposure);
  59494. };
  59495. // Add to pipeline
  59496. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59497. };
  59498. // Create lens flare post-process
  59499. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59500. var _this = this;
  59501. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59502. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59503. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  59504. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59505. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59506. var resolution = new BABYLON.Vector2(0, 0);
  59507. // Lens flare
  59508. this.lensFlarePostProcess.onApply = function (effect) {
  59509. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  59510. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59511. effect.setFloat("strength", _this.lensFlareStrength);
  59512. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59513. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59514. // Shift
  59515. resolution.x = _this.lensFlarePostProcess.width;
  59516. resolution.y = _this.lensFlarePostProcess.height;
  59517. effect.setVector2("resolution", resolution);
  59518. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59519. };
  59520. // Compose
  59521. var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  59522. var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  59523. this.lensFlareComposePostProcess.onApply = function (effect) {
  59524. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  59525. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59526. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59527. // Lens start rotation matrix
  59528. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59529. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59530. var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
  59531. camRot *= 4.0;
  59532. var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  59533. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59534. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59535. };
  59536. };
  59537. // Create depth-of-field post-process
  59538. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59539. var _this = this;
  59540. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59541. this.depthOfFieldPostProcess.onApply = function (effect) {
  59542. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59543. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  59544. effect.setFloat("distance", _this.depthOfFieldDistance);
  59545. };
  59546. // Add to pipeline
  59547. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59548. };
  59549. // Dispose
  59550. StandardRenderingPipeline.prototype.dispose = function () {
  59551. for (var i = 0; i < this._scene.cameras.length; i++) {
  59552. var camera = this._scene.cameras[i];
  59553. this.originalPostProcess.dispose(camera);
  59554. this.downSampleX4PostProcess.dispose(camera);
  59555. this.brightPassPostProcess.dispose(camera);
  59556. this.textureAdderPostProcess.dispose(camera);
  59557. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  59558. this.gaussianBlurHPostProcesses[j].dispose(camera);
  59559. }
  59560. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  59561. this.gaussianBlurVPostProcesses[j].dispose(camera);
  59562. }
  59563. this.textureAdderFinalPostProcess.dispose(camera);
  59564. this.lensFlarePostProcess.dispose(camera);
  59565. this.lensFlareComposePostProcess.dispose(camera);
  59566. this.depthOfFieldPostProcess.dispose(camera);
  59567. }
  59568. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59569. _super.prototype.dispose.call(this);
  59570. };
  59571. // Serialize rendering pipeline
  59572. StandardRenderingPipeline.prototype.serialize = function () {
  59573. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59574. serializationObject.customType = "StandardRenderingPipeline";
  59575. return serializationObject;
  59576. };
  59577. // Parse serialized pipeline
  59578. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59579. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  59580. };
  59581. return StandardRenderingPipeline;
  59582. }(BABYLON.PostProcessRenderPipeline));
  59583. __decorate([
  59584. BABYLON.serialize()
  59585. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  59586. __decorate([
  59587. BABYLON.serialize()
  59588. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  59589. __decorate([
  59590. BABYLON.serialize()
  59591. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  59592. __decorate([
  59593. BABYLON.serialize()
  59594. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  59595. __decorate([
  59596. BABYLON.serialize()
  59597. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  59598. __decorate([
  59599. BABYLON.serialize()
  59600. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  59601. __decorate([
  59602. BABYLON.serialize()
  59603. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  59604. __decorate([
  59605. BABYLON.serializeAsTexture("lensTexture")
  59606. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  59607. __decorate([
  59608. BABYLON.serializeAsTexture("lensColorTexture")
  59609. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59610. __decorate([
  59611. BABYLON.serialize()
  59612. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59613. __decorate([
  59614. BABYLON.serialize()
  59615. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59616. __decorate([
  59617. BABYLON.serialize()
  59618. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59619. __decorate([
  59620. BABYLON.serialize()
  59621. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59622. __decorate([
  59623. BABYLON.serializeAsTexture("lensStarTexture")
  59624. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59625. __decorate([
  59626. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59627. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59628. __decorate([
  59629. BABYLON.serialize()
  59630. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59631. __decorate([
  59632. BABYLON.serialize()
  59633. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59634. __decorate([
  59635. BABYLON.serialize()
  59636. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  59637. __decorate([
  59638. BABYLON.serialize()
  59639. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  59640. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59641. })(BABYLON || (BABYLON = {}));
  59642. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59643. 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..maxSimultaneousLights]\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#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\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#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\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+uvOffset).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+uvOffset);\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#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\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+uvOffset);\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+uvOffset).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\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\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<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\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<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\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":"varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nvec2 sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nvec2 sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nvec2 sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nvec2 sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nvec2 sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nvec2 sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nvec2 sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\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{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\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 DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\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}","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}","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;\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..maxSimultaneousLights]\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 vec3 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) || defined(METALLICWORKFLOW) \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#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\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\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\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\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\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+uvOffset);\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 METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICROUGHNESSMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallicRoughness.r);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\nmicroSurface=1.0-metallicRoughness.g;\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.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\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 ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\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 ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\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 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\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).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\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\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#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\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 vec3 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) || defined(METALLICWORKFLOW) \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<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\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) || defined(METALLICWORKFLOW) \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<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\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;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\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":"#ifndef FULLFLOAT\nvec4 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}\n#endif\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;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\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\nvFogDistance=viewPos;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\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;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\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#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\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","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\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(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\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(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\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]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\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;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\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 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\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}"};
  59644. 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":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\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;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\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","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangent.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangent.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","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","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","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 vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\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#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\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#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else \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#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\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,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}\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,vec3 reflectance90)\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,reflectance90);\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#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\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}\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};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,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=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,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,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\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,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,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,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\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,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,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,specularEnvironmentR90,NdotL);\n#endif\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\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\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\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\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#endif\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;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\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;\n#ifndef SHADOWFULLFLOAT\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#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\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}\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}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\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;\n#ifndef SHADOWFULLFLOAT\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#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\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#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\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);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\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","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\n#ifndef SHADOWFULLFLOAT\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#endif\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;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\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;\n#ifndef SHADOWFULLFLOAT\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#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\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}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\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;\n#ifndef SHADOWFULLFLOAT\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#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\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);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nreturn 1.0;\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  59645. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),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(),this._collisionMask=-1}return Object.defineProperty(i.prototype,\"collisionMask\",{get:function(){return this._collisionMask},set:function(t){this._collisionMask=isNaN(t)?-1:t},enumerable:!0,configurable:!0}),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!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(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)&&!!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||V<0)return;h<0&&(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 f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,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(m,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(m,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(m=g*-f+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(m,T,b,P),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(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),m=g*-f+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(m,T,b,P),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(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),m=g*-f+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(m,T,b,P),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(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;c<s;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;c<a;++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;s<r;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;t<s;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;t<a;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(e){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(o){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\";var o;!function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(o=e.WorkerTaskType||(e.WorkerTaskType={}));var i;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(i=e.WorkerReplyType||(e.WorkerReplyType={}));var 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}();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 Uint32Array(o.getIndices()||[])}},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);var d=n?n.collisionMask:t.collisionMask;t._initialize(o,i,a);for(var l=0;l<this._scene.meshes.length;l++){var c=this._scene.meshes[l];c.isEnabled()&&c.checkCollisions&&c.subMeshes&&c!==n&&0!==(d&c.collisionGroup)&&c._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,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"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,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.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},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.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},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.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},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.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},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.set=function(t,i,r){return this.copyFromFloats(t,i,r)},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.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},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.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},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r.Random=function(){return new r(Math.random(),Math.random(),Math.random())},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}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.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=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,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},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.copyFromFloats=function(t,i,r,n){return this.r=t,this.g=i,this.b=r,this.a=n,this},t.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.set=function(t,i){return this.copyFromFloats(t,i)},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r(-this.x,-this.y)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.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},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.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},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.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},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r(-this.x,-this.y,-this.z)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,this},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.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},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.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},r.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},r.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},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.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},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.prototype.set=function(t,i,r){return this.copyFromFloats(t,i,r)},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r(-1,0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=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],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){A.Vector3[0].x=t.y*i.z-t.z*i.y,A.Vector3[0].y=t.z*i.x-t.x*i.z,A.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(A.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,.5,0,h+e/2,s/2+a,.5,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,-(t.y/o*2-1),2*t.z-1),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(t,i,r,n){var o=A.Quaternion[0];a.RotationQuaternionFromAxisToRef(t,i,r,o),o.toEulerAnglesToRef(n)},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.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},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.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},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.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},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r(-this.x,-this.y,-this.z,-this.w)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t,this},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.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},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.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},r.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},r.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},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.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},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e,r.w=t.w},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o,e){e.x=t*o.m[0]+i*o.m[4]+r*o.m[8],e.y=t*o.m[1]+i*o.m[5]+r*o.m[9],e.z=t*o.m[2]+i*o.m[6]+r*o.m[10],e.w=n},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){return this.width=t,this.height=i,this},t.prototype.set=function(t,i){return this.copyFromFloats(t,i)},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.subtract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function i(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},i.prototype.getClassName=function(){return\"Quaternion\"},i.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},i.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},i.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.multiply=function(t){var r=new i(0,0,0,1);return this.multiplyToRef(t,r),r},i.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-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,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},i.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},i.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},i.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},i.prototype.conjugate=function(){var t=new i(-this.x,-this.y,-this.z,this.w);return t},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},i.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r=this.z,n=this.x,o=this.y,e=this.w,s=e*e,h=r*r,a=n*n,u=o*o,m=o*r-n*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(n*o+r*e),-h-a+u+s),t.x=Math.asin(-2*(r*o-n*e)),t.y=Math.atan2(2*(r*n+o*e),h-a-u+s)),this},i.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=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*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},i.prototype.fromRotationMatrix=function(t){return i.FromRotationMatrixToRef(t,this),this},i.FromRotationMatrix=function(t){var r=new i;return i.FromRotationMatrixToRef(t,r),r},i.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},i.Zero=function(){return new i(0,0,0,0)},i.Inverse=function(t){return new i(-t.x,-t.y,-t.z,t.w)},i.Identity=function(){return new i(0,0,0,1)},i.IsIdentity=function(t){return t&&0===t.x&&0===t.y&&0===t.z&&1===t.w},i.RotationAxis=function(t,r){return i.RotationAxisToRef(t,r,new i)},i.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},i.FromArray=function(t,r){return r||(r=0),new i(t[r],t[r+1],t[r+2],t[r+3])},i.RotationYawPitchRoll=function(t,r,n){var o=new i;return i.RotationYawPitchRollToRef(t,r,n,o),o},i.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},i.RotationAlphaBetaGamma=function(t,r,n){var o=new i;return i.RotationAlphaBetaGammaToRef(t,r,n,o),o},i.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},i.RotationQuaternionFromAxis=function(t,r,n,o){var e=new i(0,0,0,0);return i.RotationQuaternionFromAxisToRef(t,r,n,e),e},i.RotationQuaternionFromAxisToRef=function(i,r,n,o){var e=A.Matrix[0];t.Matrix.FromXYZAxesToRef(i.normalize(),r.normalize(),n.normalize(),e),t.Quaternion.FromRotationMatrixToRef(e,o)},i.Slerp=function(t,r,n){var o=i.Identity();return i.SlerpToRef(t,r,n,o),o},i.SlerpToRef=function(t,i,r,n){var o,e,s=r,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}n.x=e*t.x+o*i.x,n.y=e*t.y+o*i.y,n.z=e*t.z+o*i.z,n.w=e*t.w+o*i.w},i}();t.Quaternion=a;var u=function(){function r(){this.m=new Float32Array(16)}return r.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(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])},r.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],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=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],e=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]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},r.prototype.toArray=function(){return this.m},r.prototype.asArray=function(){return this.toArray()},r.prototype.invert=function(){return this.invertToRef(this),this},r.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},r.prototype.add=function(t){var i=new r;return this.addToRef(t,i),i},r.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},r.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},r.prototype.invertToRef=function(t){var i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=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],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),F=e*w-s*d+a*R,M=-(e*v-s*g+h*R),A=1/(i*T+r*_+n*F+o*M),b=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,N=s*y-h*m,V=e*c-a*u,q=e*y-h*u,D=e*m-s*u;return t.m[0]=T*A,t.m[4]=_*A,\nt.m[8]=F*A,t.m[12]=M*A,t.m[1]=-(r*z-n*w+o*v)*A,t.m[5]=(i*z-n*d+o*g)*A,t.m[9]=-(i*w-r*d+o*R)*A,t.m[13]=(i*v-r*g+n*R)*A,t.m[2]=(r*b-n*L+o*C)*A,t.m[6]=-(i*b-n*P+o*Z)*A,t.m[10]=(i*L-r*P+o*S)*A,t.m[14]=-(i*C-r*Z+n*S)*A,t.m[3]=-(r*I-n*H+o*N)*A,t.m[7]=(i*I-n*V+o*q)*A,t.m[11]=-(i*H-r*V+o*D)*A,t.m[15]=(i*N-r*q+n*D)*A,this},r.prototype.setTranslationFromFloats=function(t,i,r){return this.m[12]=t,this.m[13]=i,this.m[14]=r,this},r.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},r.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},r.prototype.getTranslationToRef=function(t){return t.x=this.m[12],t.y=this.m[13],t.z=this.m[14],this},r.prototype.removeRotationAndScaling=function(){return this.setRowFromFloats(0,1,0,0,0),this.setRowFromFloats(1,0,1,0,0),this.setRowFromFloats(2,0,0,1,0),this},r.prototype.multiply=function(t){var i=new r;return this.multiplyToRef(t,i),i},r.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},r.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;r++)t[i+r]=this.m[r];return this},r.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},r.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=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],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],F=t.m[6],M=t.m[7],A=t.m[8],b=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*A+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*F+e*L+s*S,i[r+3]=n*R+o*M+e*C+s*I,i[r+4]=h*v+a*T+u*A+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*F+u*L+m*S,i[r+7]=h*R+a*M+u*C+m*I,i[r+8]=y*v+c*T+p*A+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*F+p*L+f*S,i[r+11]=y*R+c*M+p*C+f*I,i[r+12]=x*v+l*T+z*A+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*F+z*L+w*S,i[r+15]=x*R+l*M+z*C+w*I,this},r.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]},r.prototype.clone=function(){return r.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])},r.prototype.getClassName=function(){return\"Matrix\"},r.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},r.prototype.decompose=function(t,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return t.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===t.x||0===t.y||0===t.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(r.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,A.Matrix[0]),a.FromRotationMatrixToRef(A.Matrix[0],n),!0)},r.prototype.getRotationMatrix=function(){var t=r.Identity();return this.getRotationMatrixToRef(t),t},r.prototype.getRotationMatrixToRef=function(t){var i=this.m,n=i[0]*i[1]*i[2]*i[3]<0?-1:1,o=i[4]*i[5]*i[6]*i[7]<0?-1:1,e=i[8]*i[9]*i[10]*i[11]<0?-1:1,s=n*Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),h=o*Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),a=e*Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);return r.FromValuesToRef(i[0]/s,i[1]/s,i[2]/s,0,i[4]/h,i[5]/h,i[6]/h,0,i[8]/a,i[9]/a,i[10]/a,0,0,0,0,1,t),this},r.FromArray=function(t,i){var n=new r;return i||(i=0),r.FromArrayToRef(t,i,n),n},r.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i]},r.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r},r.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},r.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},r.prototype.setRow=function(t,i){if(t<0||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},r.prototype.setRowFromFloats=function(t,i,r,n,o){if(t<0||t>3)return this;var e=4*t;return this.m[e+0]=i,this.m[e+1]=r,this.m[e+2]=n,this.m[e+3]=o,this},r.FromValues=function(t,i,n,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new r;return z.m[0]=t,z.m[1]=i,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,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]=x,z.m[15]=l,z},r.Compose=function(t,i,n){var o=r.Identity();return r.ComposeToRef(t,i,n,o),o},r.ComposeToRef=function(t,i,n,o){r.FromValuesToRef(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1,A.Matrix[1]),i.toRotationMatrix(A.Matrix[0]),A.Matrix[1].multiplyToRef(A.Matrix[0],o),o.setTranslation(n)},r.Identity=function(){return r.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},r.IdentityToRef=function(t){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},r.Zero=function(){return r.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},r.RotationX=function(t){var i=new r;return r.RotationXToRef(t,i),i},r.Invert=function(t){var i=new r;return t.invertToRef(i),i},r.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,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},r.RotationY=function(t){var i=new r;return r.RotationYToRef(t,i),i},r.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,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},r.RotationZ=function(t){var i=new r;return r.RotationZToRef(t,i),i},r.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,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},r.RotationAxis=function(t,i){var n=r.Zero();return r.RotationAxisToRef(t,i,n),n},r.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},r.RotationYawPitchRoll=function(t,i,n){var o=new r;return r.RotationYawPitchRollToRef(t,i,n,o),o},r.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},r.Scaling=function(t,i,n){var o=r.Zero();return r.ScalingToRef(t,i,n,o),o},r.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.Translation=function(t,i,n){var o=r.Identity();return r.TranslationToRef(t,i,n,o),o},r.TranslationToRef=function(t,i,n,o){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,n,1,o)},r.Lerp=function(t,i,n){for(var o=r.Zero(),e=0;e<16;e++)o.m[e]=t.m[e]*(1-n)+i.m[e]*n;return o},r.DecomposeLerp=function(t,i,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);i.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return r.Compose(c,p,f)},r.LookAtLH=function(t,i,n){var o=r.Zero();return r.LookAtLHToRef(t,i,n,o),o},r.LookAtLHToRef=function(t,i,n,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.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,s,h,a,1,o)},r.LookAtRH=function(t,i,n){var o=r.Zero();return r.LookAtRHToRef(t,i,n,o),o},r.LookAtRHToRef=function(t,i,n,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.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,s,h,a,1,o)},r.OrthoLH=function(t,i,n,o){var e=r.Zero();return r.OrthoLHToRef(t,i,n,o,e),e},r.OrthoLHToRef=function(i,r,n,o,e){var s=n,h=o,a=2/i,u=2/r,m=2/(h-s),y=-(h+s)/(h-s);t.Matrix.FromValuesToRef(a,0,0,0,0,u,0,0,0,0,m,0,0,0,y,1,e)},r.OrthoOffCenterLH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterLHToRef=function(i,r,n,o,e,s,h){var a=e,u=s,m=2/(r-i),y=2/(o-n),c=2/(u-a),p=-(u+a)/(u-a),f=(i+r)/(i-r),x=(o+n)/(n-o);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,0,f,x,p,1,h)},r.OrthoOffCenterRH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterRHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterRHToRef=function(t,i,n,o,e,s,h){r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h.m[10]*=-1},r.PerspectiveLH=function(i,n,o,e){var s=r.Zero(),h=o,a=e,u=2*h/i,m=2*h/n,y=(a+h)/(a-h),c=-2*a*h/(a-h);return t.Matrix.FromValuesToRef(u,0,0,0,0,m,0,0,0,0,y,1,0,0,c,0,s),s},r.PerspectiveFovLH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovLHToRef(t,i,n,o,e),e},r.PerspectiveFovLHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,1,0,0,p,0,e)},r.PerspectiveFovRH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovRHToRef(t,i,n,o,e),e},r.PerspectiveFovRHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=-(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,-1,0,0,p,0,e)},r.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!1);var e=o?-1:1,s=Math.tan(t.upDegrees*Math.PI/180),h=Math.tan(t.downDegrees*Math.PI/180),a=Math.tan(t.leftDegrees*Math.PI/180),u=Math.tan(t.rightDegrees*Math.PI/180),m=2/(a+u),y=2/(s+h);n.m[0]=m,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=y,n.m[6]=n.m[7]=0,n.m[8]=(a-u)*m*.5*e,n.m[9]=-((s-h)*y*.5)*e,n.m[10]=-(i+r)/(r-i)*e,n.m[11]=1*e,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(2*r*i)/(r-i)},r.GetFinalMatrix=function(t,i,n,o,e,s){var h=t.width,a=t.height,u=t.x,m=t.y,y=r.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return i.multiply(n).multiply(o).multiply(y)},r.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},r.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]])},r.Transpose=function(t){var i=new r;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},r.Reflection=function(t){var i=new r;return r.ReflectionToRef(t,i),i},r.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},r.FromXYZAxesToRef=function(t,i,r,n){n.m[0]=t.x,n.m[1]=t.y,n.m[2]=t.z,n.m[3]=0,n.m[4]=i.x,n.m[5]=i.y,n.m[6]=i.z,n.m[7]=0,n.m[8]=r.x,n.m[9]=r.y,n.m[10]=r.z,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.FromQuaternionToRef=function(t,i){var r=t.x*t.x,n=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(n+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+r),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(n+r),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},r}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}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.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},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 r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,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,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,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 r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.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,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},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=c;var p;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\",t[t.BONE=2]=\"BONE\"}(p=t.Space||(t.Space={}));var f=function(){function t(){}return t}();f.X=new e(1,0,0),f.Y=new e(0,1,0),f.Z=new e(0,0,1),t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=x;var l;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(l=t.Orientation||(t.Orientation={}));var z=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,r){var n=r.subtract(i),o=Math.atan2(n.y,n.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=z;var w=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?l.CW:l.CCW,this.angle=z.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=w;var v=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 r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new w(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),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],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=v;var d=function(){function r(t,i,r){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 n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.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 r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),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]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,-1,0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=d;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.CreateCatmullRomSpline=function(i,r){var n=new Array;n.push(i[0].clone()),Array.prototype.push.apply(n,i),n.push(i[i.length-1].clone());for(var o=new Array,s=1/r,h=0;h<n.length-3;h++)for(var a=0,u=0;u<r;u++)o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),a+=s;return h--,o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),new t(o)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype.continue=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=g;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);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=R;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(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 r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=T;var _=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=_;var F=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=F;var M=function(){function t(){}return t}();M.Color3=[r.Black(),r.Black(),r.Black()],M.Vector2=[o.Zero(),o.Zero(),o.Zero()],M.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],M.Vector4=[s.Zero(),s.Zero(),s.Zero()],M.Quaternion=[a.Zero(),a.Zero()],M.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=M;var A=function(){function t(){}return t}();A.Vector3=[e.Zero()],A.Matrix=[u.Zero(),u.Zero()],A.Quaternion=[a.Zero()]}(BABYLON||(BABYLON={}));";
  59646. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  59647. module.exports = BABYLON;
  59648. };